diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..8c11832cf0201457633d66e367712c5f25abae37 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + # any change to common/utils/include/dhardware_ipc_interface_code.h needs to be reviewed by @leonchan5 +common/utils/include/dhardware_ipc_interface_code.h @leonchan5 \ No newline at end of file diff --git a/av_transport/av_trans_control_center/inner_kits/include/av_trans_control_center_callback.h b/av_transport/av_trans_control_center/inner_kits/include/av_trans_control_center_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..8ec6257cacc2d8fa375f0dafe050adc95da056aa --- /dev/null +++ b/av_transport/av_trans_control_center/inner_kits/include/av_trans_control_center_callback.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_H +#define OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_H + +#include "av_trans_control_center_callback_stub.h" + +#include "i_av_receiver_engine.h" +#include "i_av_sender_engine.h" + +namespace OHOS { +namespace DistributedHardware { +class AVTransControlCenterCallback : public AVTransControlCenterCallbackStub { +public: + AVTransControlCenterCallback() = default; + ~AVTransControlCenterCallback() override = default; + + int32_t SetParameter(AVTransTag tag, const std::string &value) override; + int32_t SetSharedMemory(const AVTransSharedMemory &memory) override; + int32_t Notify(const AVTransEvent &event) override; + + void SetSenderEngine(const std::shared_ptr &sender); + void SetReceiverEngine(const std::shared_ptr &receiver); + +private: + std::weak_ptr senderEngine_; + std::weak_ptr receiverEngine_; +}; +} +} +#endif \ No newline at end of file diff --git a/sa_profile/4801.xml b/av_transport/av_trans_control_center/inner_kits/include/av_trans_control_center_callback_stub.h similarity index 32% rename from sa_profile/4801.xml rename to av_transport/av_trans_control_center/inner_kits/include/av_trans_control_center_callback_stub.h index 236e5282e2aee729b893c83cd0f0545f40724150..5732732886299097156a600ab30bd91cb0575e91 100644 --- a/sa_profile/4801.xml +++ b/av_transport/av_trans_control_center/inner_kits/include/av_trans_control_center_callback_stub.h @@ -1,5 +1,4 @@ - - - - dhardware - - 4801 - libdistributedhardwarefwksvr.z.so - - - false - true - 1 - - + */ + +#ifndef OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_STUB_H +#define OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_STUB_H + +#include "iremote_stub.h" +#include "iav_trans_control_center_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class AVTransControlCenterCallbackStub : public IRemoteStub { +public: + AVTransControlCenterCallbackStub(); + virtual ~AVTransControlCenterCallbackStub() override; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t SetParameterInner(MessageParcel &data, MessageParcel &reply); + int32_t SetSharedMemoryInner(MessageParcel &data, MessageParcel &reply); + int32_t NotifyInner(MessageParcel &data, MessageParcel &reply); + +private: + DISALLOW_COPY_AND_MOVE(AVTransControlCenterCallbackStub); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_STUB_H diff --git a/av_transport/av_trans_control_center/inner_kits/src/av_trans_control_center_callback.cpp b/av_transport/av_trans_control_center/inner_kits/src/av_trans_control_center_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..832d0079e282e33ac63261f19cabff660315e51b --- /dev/null +++ b/av_transport/av_trans_control_center/inner_kits/src/av_trans_control_center_callback.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_control_center_callback.h" + +#include "av_trans_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t AVTransControlCenterCallback::SetParameter(AVTransTag tag, const std::string &value) +{ + if ((tag == AVTransTag::START_AV_SYNC) || (tag == AVTransTag::STOP_AV_SYNC) || + (tag == AVTransTag::TIME_SYNC_RESULT)) { + std::shared_ptr rcvEngine = receiverEngine_.lock(); + if (rcvEngine != nullptr) { + rcvEngine->SetParameter(tag, value); + } + } + return DH_AVT_SUCCESS; +} + +int32_t AVTransControlCenterCallback::SetSharedMemory(const AVTransSharedMemory &memory) +{ + DHLOGW("AVTransControlCenterCallback::SetSharedMemory enter."); + + std::shared_ptr sendEngine = senderEngine_.lock(); + if (sendEngine != nullptr) { + sendEngine->SetParameter(AVTransTag::SHARED_MEMORY_FD, MarshalSharedMemory(memory)); + } + + std::shared_ptr rcvEngine = receiverEngine_.lock(); + if (rcvEngine != nullptr) { + rcvEngine->SetParameter(AVTransTag::SHARED_MEMORY_FD, MarshalSharedMemory(memory)); + } + + return DH_AVT_SUCCESS; +} + +int32_t AVTransControlCenterCallback::Notify(const AVTransEvent& event) +{ + DHLOGW("AVTransControlCenterCallback::Notify enter."); + return DH_AVT_SUCCESS; +} + +void AVTransControlCenterCallback::SetSenderEngine(const std::shared_ptr &sender) +{ + if (sender != nullptr) { + senderEngine_ = sender; + } +} + +void AVTransControlCenterCallback::SetReceiverEngine(const std::shared_ptr &receiver) +{ + if (receiver != nullptr) { + receiverEngine_ = receiver; + } +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_control_center/inner_kits/src/av_trans_control_center_callback_stub.cpp b/av_transport/av_trans_control_center/inner_kits/src/av_trans_control_center_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..696bfb12e560ea5221cf78f8190672283a9f6e00 --- /dev/null +++ b/av_transport/av_trans_control_center/inner_kits/src/av_trans_control_center_callback_stub.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_control_center_callback_stub.h" + +#include "av_trans_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +AVTransControlCenterCallbackStub::AVTransControlCenterCallbackStub() +{ +} + +AVTransControlCenterCallbackStub::~AVTransControlCenterCallbackStub() +{ +} + +int32_t AVTransControlCenterCallbackStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + (void)option; + if (data.ReadInterfaceToken() != GetDescriptor()) { + DHLOGE("Read valid token failed"); + return ERR_INVALID_DATA; + } + switch (code) { + case (uint32_t)IAVTransControlCenterCallback::Message::SET_PARAMETER: { + return SetParameterInner(data, reply); + } + case (uint32_t)IAVTransControlCenterCallback::Message::SET_SHARED_MEMORY: { + return SetSharedMemoryInner(data, reply); + } + case (uint32_t)IAVTransControlCenterCallback::Message::NOTIFY_AV_EVENT: { + return NotifyInner(data, reply); + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + + return NO_ERROR; +} + +int32_t AVTransControlCenterCallbackStub::SetParameterInner(MessageParcel &data, MessageParcel &reply) +{ + uint32_t transTag = data.ReadUint32(); + std::string tagValue = data.ReadString(); + int32_t ret = SetParameter((AVTransTag)transTag, tagValue); + if (!reply.WriteInt32(ret)) { + DHLOGE("Write ret code failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + return NO_ERROR; +} + +int32_t AVTransControlCenterCallbackStub::SetSharedMemoryInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t fd = data.ReadFileDescriptor(); + int32_t size = data.ReadInt32(); + std::string name = data.ReadString(); + int32_t ret = SetSharedMemory(AVTransSharedMemory{ fd, size, name }); + if (!reply.WriteInt32(ret)) { + DHLOGE("Write ret code failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + return NO_ERROR; +} + +int32_t AVTransControlCenterCallbackStub::NotifyInner(MessageParcel &data, MessageParcel &reply) +{ + uint32_t type = data.ReadUint32(); + std::string content = data.ReadString(); + std::string peerDevId = data.ReadString(); + int32_t ret = Notify(AVTransEvent{(EventType)type, content, peerDevId}); + if (!reply.WriteInt32(ret)) { + DHLOGE("Write ret code failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + return NO_ERROR; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_control_center/services/include/av_sync_manager.h b/av_transport/av_trans_control_center/services/include/av_sync_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..952bdd2f470e6a80d370213c8120bedad3dedf32 --- /dev/null +++ b/av_transport/av_trans_control_center/services/include/av_sync_manager.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_SYNC_MANAGER_H +#define OHOS_AV_SYNC_MANAGER_H + +#include + +#include "av_sync_utils.h" +#include "av_trans_message.h" +#include "av_trans_types.h" + +namespace OHOS { +namespace DistributedHardware { +constexpr uint32_t AV_SYNC_STREAM_COUNT = 2; + +class AVSyncManager { +public: + AVSyncManager(); + ~AVSyncManager(); + + void AddStreamInfo(const AVStreamInfo &stream); + void RemoveStreamInfo(const AVStreamInfo &stream); + void HandleAvSyncMessage(const std::shared_ptr &message); + +private: + void EnableSenderAVSync(); + void DisableSenderAVSync(); + void EnableReceiverAVSync(const std::string &groupInfo); + void DisableReceiverAVSync(const std::string &groupInfo); + bool MergeGroupInfo(std::string &syncGroupInfo); + +private: + std::mutex listMutex_; + + std::vector streamInfoList_; + AVTransSharedMemory sourceMemory_; + AVTransSharedMemory sinkMemory_; +}; +} +} +#endif \ No newline at end of file diff --git a/av_transport/av_trans_control_center/services/include/av_trans_control_center.h b/av_transport/av_trans_control_center/services/include/av_trans_control_center.h new file mode 100644 index 0000000000000000000000000000000000000000..4f97415cc21772d82726d974a40d157944d0c012 --- /dev/null +++ b/av_transport/av_trans_control_center/services/include/av_trans_control_center.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_CONTROL_CENTER_H +#define OHOS_AV_TRANS_CONTROL_CENTER_H + +#include "av_sync_manager.h" +#include "av_trans_constants.h" +#include "av_trans_message.h" +#include "iav_trans_control_center_callback.h" +#include "single_instance.h" +#include "softbus_channel_adapter.h" + +namespace OHOS { +namespace DistributedHardware { +class AVTransControlCenter : public ISoftbusChannelListener { + DECLARE_SINGLE_INSTANCE_BASE(AVTransControlCenter); +public: + AVTransControlCenter(); + virtual ~AVTransControlCenter(); + + int32_t InitializeAVCenter(const TransRole &transRole, int32_t &engineId); + int32_t ReleaseAVCenter(int32_t engineId); + int32_t CreateControlChannel(int32_t engineId, const std::string &peerDevId); + int32_t NotifyAVCenter(int32_t engineId, const AVTransEvent &event); + int32_t RegisterCtlCenterCallback(int32_t engineId, const sptr &callback); + + // interfaces from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + +public: + int32_t SendMessage(const std::shared_ptr &message); + void SetParam2Engines(AVTransTag tag, const std::string &value); + void SetParam2Engines(const AVTransSharedMemory &memory); + +private: + void HandleChannelEvent(const AVTransEvent &event); + void HandleDataReceived(const std::string &content, const std::string &peerDevId); + bool IsInvalidEngineId(int32_t engineId); + +private: + TransRole transRole_; + std::string sessionName_; + std::atomic rootEngineId_; + std::atomic initialized_ {false}; + std::shared_ptr syncManager_ = nullptr; + + std::mutex devIdMutex_; + std::mutex engineIdMutex_; + std::mutex callbackMutex_; + + std::vector connectedDevIds_; + std::map engine2DevIdMap_; + std::map> callbackMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/av_transport/av_trans_control_center/services/include/ipc/av_trans_control_center_callback_proxy.h b/av_transport/av_trans_control_center/services/include/ipc/av_trans_control_center_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..9b657f4bf9fe2b9519341e652be97dec2913a12a --- /dev/null +++ b/av_transport/av_trans_control_center/services/include/ipc/av_trans_control_center_callback_proxy.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_PROXY_H +#define OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_PROXY_H + +#include + +#include "iremote_proxy.h" +#include "refbase.h" +#include "iav_trans_control_center_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class AVTransControlCenterCallbackProxy : public IRemoteProxy { +public: + explicit AVTransControlCenterCallbackProxy(const sptr &impl) + : IRemoteProxy(impl) + { + } + virtual ~AVTransControlCenterCallbackProxy() {} + + int32_t SetParameter(AVTransTag tag, const std::string &value) override; + int32_t SetSharedMemory(const AVTransSharedMemory &memory) override; + int32_t Notify(const AVTransEvent &event) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_PROXY_H diff --git a/av_transport/av_trans_control_center/services/src/av_sync_manager.cpp b/av_transport/av_trans_control_center/services/src/av_sync_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a61c407996b4896a482e16b4a1e0889d3193136 --- /dev/null +++ b/av_transport/av_trans_control_center/services/src/av_sync_manager.cpp @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_sync_manager.h" + +#include +#include "nlohmann/json.hpp" + +#include "av_trans_control_center.h" +#include "av_trans_log.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVSyncManager" + +AVSyncManager::AVSyncManager() +{ + AVTRANS_LOGI("AVSyncManager ctor."); + sourceMemory_ = { 0, 0, "" }; + sinkMemory_ = { 0, 0, "" }; +} + +AVSyncManager::~AVSyncManager() +{ + AVTRANS_LOGI("AVSyncManager dctor."); + streamInfoList_.clear(); + CloseAVTransSharedMemory(sourceMemory_); + CloseAVTransSharedMemory(sinkMemory_); +} + +void AVSyncManager::AddStreamInfo(const AVStreamInfo &stream) +{ + AVTRANS_LOGI("add new stream info: sceneType=%s, peerDevId=%s", stream.sceneType.c_str(), + GetAnonyString(stream.peerDevId).c_str()); + { + std::lock_guard lock(listMutex_); + streamInfoList_.push_back(stream); + + if (streamInfoList_.size() < AV_SYNC_STREAM_COUNT) { + AVTRANS_LOGI("No need enable sender av sync, stream info list size=%zu", streamInfoList_.size()); + return; + } + } + EnableSenderAVSync(); +} + +void AVSyncManager::RemoveStreamInfo(const AVStreamInfo &stream) +{ + AVTRANS_LOGI("remove stream info: sceneType=%s, peerDevId=%s", stream.sceneType.c_str(), + GetAnonyString(stream.peerDevId).c_str()); + { + std::lock_guard lock(listMutex_); + for (auto iter = streamInfoList_.begin(); iter != streamInfoList_.end();) { + if (((*iter).sceneType == stream.sceneType) && ((*iter).peerDevId == stream.peerDevId)) { + iter = streamInfoList_.erase(iter); + } else { + iter++; + } + } + } + DisableSenderAVSync(); +} + +void AVSyncManager::EnableSenderAVSync() +{ + std::string syncGroupInfo; + if (!MergeGroupInfo(syncGroupInfo)) { + AVTRANS_LOGI("No need start av sync."); + return; + } + AVTRANS_LOGI("merged av sync group info=%s", GetAnonyString(syncGroupInfo).c_str()); + { + std::lock_guard lock(listMutex_); + for (const auto &item : streamInfoList_) { + auto avMessage = std::make_shared((uint32_t)AVTransTag::START_AV_SYNC, + syncGroupInfo, item.peerDevId); + AVTransControlCenter::GetInstance().SendMessage(avMessage); + } + } + + sourceMemory_ = CreateAVTransSharedMemory("sourceSharedMemory", sizeof(uint32_t) + sizeof(int64_t)); + AVTransControlCenter::GetInstance().SetParam2Engines(sourceMemory_); +} + +void AVSyncManager::DisableSenderAVSync() +{ + { + std::lock_guard lock(listMutex_); + if (streamInfoList_.size() >= AV_SYNC_STREAM_COUNT) { + AVTRANS_LOGI("Cannot disable sender av sync, stream info list size=%zu", streamInfoList_.size()); + return; + } + for (const auto &item : streamInfoList_) { + auto avMessage = std::make_shared((uint32_t)AVTransTag::STOP_AV_SYNC, "", item.peerDevId); + AVTransControlCenter::GetInstance().SendMessage(avMessage); + } + } + CloseAVTransSharedMemory(sourceMemory_); + AVTransControlCenter::GetInstance().SetParam2Engines(AVTransSharedMemory{0, 0, "sourceSharedMemory"}); +} + +void AVSyncManager::HandleAvSyncMessage(const std::shared_ptr &message) +{ + if (message->type_ == (uint32_t)AVTransTag::START_AV_SYNC) { + EnableReceiverAVSync(message->content_); + } else if (message->type_ == (uint32_t)AVTransTag::STOP_AV_SYNC) { + DisableReceiverAVSync(message->content_); + } +} + +void AVSyncManager::EnableReceiverAVSync(const std::string &groupInfo) +{ + size_t size = (sizeof(uint32_t) + sizeof(int64_t)) * MAX_CLOCK_UNIT_COUNT; + sinkMemory_ = CreateAVTransSharedMemory("sinkSharedMemory", size); + + AVTransControlCenter::GetInstance().SetParam2Engines(sinkMemory_); + AVTransControlCenter::GetInstance().SetParam2Engines(AVTransTag::START_AV_SYNC, groupInfo); +} + +void AVSyncManager::DisableReceiverAVSync(const std::string &groupInfo) +{ + (void)groupInfo; + CloseAVTransSharedMemory(sinkMemory_); + AVTransControlCenter::GetInstance().SetParam2Engines(AVTransTag::STOP_AV_SYNC, ""); + AVTransControlCenter::GetInstance().SetParam2Engines(AVTransSharedMemory{0, 0, "sinkSharedMemory"}); +} + +bool AVSyncManager::MergeGroupInfo(std::string &syncGroupInfo) +{ + std::set sceneTypeSet; + { + std::lock_guard lock(listMutex_); + for (const auto &item : streamInfoList_) { + sceneTypeSet.insert(item.sceneType); + } + } + if (sceneTypeSet.size() < AV_SYNC_STREAM_COUNT) { + AVTRANS_LOGI("Can not merge av sync group info, because scene type count less than threshold."); + return false; + } + + if ((sceneTypeSet.find(SCENE_TYPE_D_MIC) != sceneTypeSet.end()) && + (sceneTypeSet.find(SCENE_TYPE_D_SPEAKER) != sceneTypeSet.end())) { + AVTRANS_LOGI("Can not merge av sync group info, because scene type are conflicting."); + return false; + } + + bool source2Sink = (sceneTypeSet.find(SCENE_TYPE_D_SCREEN) != sceneTypeSet.end()) && + (sceneTypeSet.find(SCENE_TYPE_D_SPEAKER) != sceneTypeSet.end()); + bool sink2Source = (sceneTypeSet.find(SCENE_TYPE_D_CAMERA_STR) != sceneTypeSet.end()) && + (sceneTypeSet.find(SCENE_TYPE_D_MIC) != sceneTypeSet.end()); + if (!source2Sink && !sink2Source) { + AVTRANS_LOGI("Can not merge av sync group info, because scene type do not meet conditions."); + return false; + } + + std::set groupInfoSet; + for (const auto &item : streamInfoList_) { + if ((item.sceneType == SCENE_TYPE_D_MIC) || (item.sceneType == SCENE_TYPE_D_SPEAKER)) { + nlohmann::json masterStr; + masterStr[KEY_SCENE_TYPE] = item.sceneType; + masterStr[KEY_PEER_DEV_ID] = item.peerDevId; + masterStr[KEY_START_FRAME_NUM] = 0; + masterStr[KEY_AV_SYNC_FLAG] = AvSyncFlag::MASTER; + groupInfoSet.insert(masterStr.dump()); + } else if ((item.sceneType == SCENE_TYPE_D_SCREEN) || (item.sceneType == SCENE_TYPE_D_CAMERA_STR)) { + nlohmann::json slaveStr; + slaveStr[KEY_SCENE_TYPE] = item.sceneType; + slaveStr[KEY_PEER_DEV_ID] = item.peerDevId; + slaveStr[KEY_START_FRAME_NUM] = 0; + slaveStr[KEY_AV_SYNC_FLAG] = AvSyncFlag::SLAVE; + groupInfoSet.insert(slaveStr.dump()); + } else { + continue; + } + } + + nlohmann::json jsonStr = { { KEY_MY_DEV_ID, "" }, { KEY_GROUP_INFO_ARRAY, groupInfoSet }, }; + syncGroupInfo = jsonStr.dump(); + return true; +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_control_center/services/src/av_trans_control_center.cpp b/av_transport/av_trans_control_center/services/src/av_trans_control_center.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8ea42dbd7a61057a897ae38d93f9c0370419d68 --- /dev/null +++ b/av_transport/av_trans_control_center/services/src/av_trans_control_center.cpp @@ -0,0 +1,317 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_control_center.h" + +#include "anonymous_string.h" +#include "av_trans_log.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVTransControlCenter" + +IMPLEMENT_SINGLE_INSTANCE(AVTransControlCenter); + +AVTransControlCenter::AVTransControlCenter() +{ + AVTRANS_LOGI("AVTransControlCenter ctor."); + transRole_ = TransRole::UNKNOWN; + rootEngineId_.store(BASE_ENGINE_ID); + syncManager_ = std::make_shared(); +} + +AVTransControlCenter::~AVTransControlCenter() +{ + AVTRANS_LOGI("AVTransControlCenter dtor."); + SoftbusChannelAdapter::GetInstance().RemoveChannelServer(PKG_NAME_DH_FWK, AV_SYNC_SENDER_CONTROL_SESSION_NAME); + SoftbusChannelAdapter::GetInstance().RemoveChannelServer(PKG_NAME_DH_FWK, AV_SYNC_RECEIVER_CONTROL_SESSION_NAME); + + sessionName_ = ""; + initialized_ = false; + syncManager_ = nullptr; + transRole_ = TransRole::UNKNOWN; + rootEngineId_.store(BASE_ENGINE_ID); +} + +int32_t AVTransControlCenter::InitializeAVCenter(const TransRole &transRole, int32_t &engineId) +{ + engineId = INVALID_ENGINE_ID; + if ((transRole != TransRole::AV_SENDER) && (transRole != TransRole::AV_RECEIVER)) { + AVTRANS_LOGE("Invalid trans role=%d", transRole); + return ERR_DH_AVT_INVALID_PARAM_VALUE; + } + + if (initialized_.load()) { + AVTRANS_LOGI("AV control center already initialized."); + engineId = rootEngineId_.load(); + rootEngineId_++; + return DH_AVT_SUCCESS; + } + + int32_t ret = SoftbusChannelAdapter::GetInstance().CreateChannelServer(PKG_NAME_DH_FWK, + AV_SYNC_SENDER_CONTROL_SESSION_NAME); + TRUE_RETURN_V_MSG_E((ret != DH_AVT_SUCCESS), ret, "Create contro center session server failed, ret=%d", ret); + + ret = SoftbusChannelAdapter::GetInstance().CreateChannelServer(PKG_NAME_DH_FWK, + AV_SYNC_RECEIVER_CONTROL_SESSION_NAME); + TRUE_RETURN_V_MSG_E((ret != DH_AVT_SUCCESS), ret, "Create contro center session server failed, ret=%d", ret); + + ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(AV_SYNC_SENDER_CONTROL_SESSION_NAME, + AV_TRANS_SPECIAL_DEVICE_ID, this); + TRUE_RETURN_V_MSG_E((ret != DH_AVT_SUCCESS), ret, "Register control center channel callback failed, ret=%d", ret); + + ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(AV_SYNC_RECEIVER_CONTROL_SESSION_NAME, + AV_TRANS_SPECIAL_DEVICE_ID, this); + TRUE_RETURN_V_MSG_E((ret != DH_AVT_SUCCESS), ret, "Register control center channel callback failed, ret=%d", ret); + + initialized_ = true; + transRole_ = transRole; + engineId = rootEngineId_.load(); + rootEngineId_++; + + return DH_AVT_SUCCESS; +} + +int32_t AVTransControlCenter::ReleaseAVCenter(int32_t engineId) +{ + AVTRANS_LOGI("Release av control center channel for engineId=%d.", engineId); + TRUE_RETURN_V_MSG_E(IsInvalidEngineId(engineId), ERR_DH_AVT_INVALID_PARAM_VALUE, + "Invalid input engine id = %d", engineId); + + { + std::lock_guard lock(callbackMutex_); + callbackMap_.erase(engineId); + } + + std::string peerDevId; + { + std::lock_guard lock(engineIdMutex_); + if (engine2DevIdMap_.find(engineId) == engine2DevIdMap_.end()) { + AVTRANS_LOGE("Input engine id is not exist, engineId = %d", engineId); + return DH_AVT_SUCCESS; + } + peerDevId = engine2DevIdMap_[engineId]; + engine2DevIdMap_.erase(engineId); + + bool IsDevIdUsedByOthers = false; + for (auto it = engine2DevIdMap_.begin(); it != engine2DevIdMap_.end(); it++) { + if (it->second == peerDevId) { + IsDevIdUsedByOthers = true; + break; + } + } + if (IsDevIdUsedByOthers) { + AVTRANS_LOGI("Control channel is still being used by other engine, peerDevId=%s.", + GetAnonyString(peerDevId).c_str()); + return DH_AVT_SUCCESS; + } + } + + { + std::lock_guard lock(devIdMutex_); + auto iter = std::find(connectedDevIds_.begin(), connectedDevIds_.end(), peerDevId); + if (iter == connectedDevIds_.end()) { + AVTRANS_LOGE("Control channel has not been opened successfully for peerDevId=%s.", + GetAnonyString(peerDevId).c_str()); + return DH_AVT_SUCCESS; + } else { + connectedDevIds_.erase(iter); + } + } + + SoftbusChannelAdapter::GetInstance().StopDeviceTimeSync(PKG_NAME_DH_FWK, sessionName_, peerDevId); + SoftbusChannelAdapter::GetInstance().CloseSoftbusChannel(sessionName_, peerDevId); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(AV_SYNC_SENDER_CONTROL_SESSION_NAME, + AV_TRANS_SPECIAL_DEVICE_ID); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(AV_SYNC_RECEIVER_CONTROL_SESSION_NAME, + AV_TRANS_SPECIAL_DEVICE_ID); + + return DH_AVT_SUCCESS; +} + +int32_t AVTransControlCenter::CreateControlChannel(int32_t engineId, const std::string &peerDevId) +{ + AVTRANS_LOGI("Create control center channel for engineId=%d, peerDevId=%s.", engineId, + GetAnonyString(peerDevId).c_str()); + + TRUE_RETURN_V_MSG_E(IsInvalidEngineId(engineId), ERR_DH_AVT_INVALID_PARAM_VALUE, + "Invalid input engine id = %d", engineId); + + TRUE_RETURN_V_MSG_E(!initialized_.load(), ERR_DH_AVT_CREATE_CHANNEL_FAILED, + "AV control center has not been initialized."); + + { + std::lock_guard devLock(devIdMutex_); + auto iter = std::find(connectedDevIds_.begin(), connectedDevIds_.end(), peerDevId); + if (iter != connectedDevIds_.end()) { + { + std::lock_guard lock(engineIdMutex_); + engine2DevIdMap_.insert(std::make_pair(engineId, peerDevId)); + } + AVTRANS_LOGE("AV control center channel has already created, peerDevId=%s.", + GetAnonyString(peerDevId).c_str()); + return ERR_DH_AVT_CHANNEL_ALREADY_CREATED; + } + } + + int32_t ret = SoftbusChannelAdapter::GetInstance().OpenSoftbusChannel(AV_SYNC_SENDER_CONTROL_SESSION_NAME, + AV_SYNC_RECEIVER_CONTROL_SESSION_NAME, peerDevId); + TRUE_RETURN_V_MSG_E(((ret != DH_AVT_SUCCESS) && (ret != ERR_DH_AVT_SESSION_HAS_OPENED)), ret, + "Create av control center channel failed, ret=%d", ret); + + std::lock_guard lk(engineIdMutex_); + engine2DevIdMap_.insert(std::make_pair(engineId, peerDevId)); + + return DH_AVT_SUCCESS; +} + +int32_t AVTransControlCenter::NotifyAVCenter(int32_t engineId, const AVTransEvent& event) +{ + TRUE_RETURN_V_MSG_E(IsInvalidEngineId(engineId), ERR_DH_AVT_INVALID_PARAM_VALUE, + "Invalid input engine id = %d", engineId); + + switch (event.type) { + case EventType::EVENT_ADD_STREAM: { + syncManager_->AddStreamInfo(AVStreamInfo{ event.content, event.peerDevId }); + break; + } + case EventType::EVENT_REMOVE_STREAM: { + syncManager_->RemoveStreamInfo(AVStreamInfo{ event.content, event.peerDevId }); + break; + } + default: + AVTRANS_LOGE("Unsupported event type."); + } + return DH_AVT_SUCCESS; +} + +int32_t AVTransControlCenter::RegisterCtlCenterCallback(int32_t engineId, + const sptr &callback) +{ + TRUE_RETURN_V_MSG_E(IsInvalidEngineId(engineId), ERR_DH_AVT_INVALID_PARAM_VALUE, + "Invalid input engine id = %d", engineId); + + if (callback == nullptr) { + AVTRANS_LOGE("Input callback is nullptr."); + return ERR_DH_AVT_INVALID_PARAM_VALUE; + } + + std::lock_guard lock(callbackMutex_); + callbackMap_.insert(std::make_pair(engineId, callback)); + + return DH_AVT_SUCCESS; +} + +int32_t AVTransControlCenter::SendMessage(const std::shared_ptr &message) +{ + AVTRANS_LOGI("SendMessage enter."); + TRUE_RETURN_V_MSG_E(message == nullptr, ERR_DH_AVT_INVALID_PARAM, "Input message is nullptr."); + + std::string msgData = message->MarshalMessage(); + return SoftbusChannelAdapter::GetInstance().SendBytesData(sessionName_, message->dstDevId_, msgData); +} + +void AVTransControlCenter::SetParam2Engines(AVTransTag tag, const std::string &value) +{ + std::lock_guard lock(callbackMutex_); + for (auto iter = callbackMap_.begin(); iter != callbackMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->SetParameter(tag, value); + } + } +} + +void AVTransControlCenter::SetParam2Engines(const AVTransSharedMemory &memory) +{ + std::lock_guard lock(callbackMutex_); + for (auto iter = callbackMap_.begin(); iter != callbackMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->SetSharedMemory(memory); + } + } +} + +void AVTransControlCenter::OnChannelEvent(const AVTransEvent &event) +{ + AVTRANS_LOGI("OnChannelEvent enter. event type:%d", event.type); + switch (event.type) { + case EventType::EVENT_CHANNEL_OPENED: + case EventType::EVENT_CHANNEL_CLOSED: + case EventType::EVENT_CHANNEL_OPEN_FAIL: { + HandleChannelEvent(event); + break; + } + case EventType::EVENT_DATA_RECEIVED: { + HandleDataReceived(event.content, event.peerDevId); + break; + } + case EventType::EVENT_TIME_SYNC_RESULT: { + SetParam2Engines(AVTransTag::TIME_SYNC_RESULT, event.content); + break; + } + default: + AVTRANS_LOGE("Unsupported event type."); + } +} + +void AVTransControlCenter::HandleChannelEvent(const AVTransEvent &event) +{ + if (event.type == EventType::EVENT_CHANNEL_CLOSED) { + AVTRANS_LOGI("Control channel has been closed."); + return; + } + + if (event.type == EventType::EVENT_CHANNEL_OPEN_FAIL) { + AVTRANS_LOGE("Open control channel failed for peerDevId=%s.", GetAnonyString(event.peerDevId).c_str()); + return; + } + + if (event.type == EventType::EVENT_CHANNEL_OPENED) { + sessionName_ = event.content; + if (sessionName_ == AV_SYNC_RECEIVER_CONTROL_SESSION_NAME) { + SoftbusChannelAdapter::GetInstance().StartDeviceTimeSync(PKG_NAME_DH_FWK, sessionName_, event.peerDevId); + } + std::lock_guard lock(devIdMutex_); + connectedDevIds_.push_back(event.peerDevId); + } +} + +void AVTransControlCenter::HandleDataReceived(const std::string &content, const std::string &peerDevId) +{ + auto avMessage = std::make_shared(); + if (!avMessage->UnmarshalMessage(content, peerDevId)) { + AVTRANS_LOGE("unmarshal event content to av message failed"); + return; + } + AVTRANS_LOGI("Handle data received, av message type = %d", avMessage->type_); + if ((avMessage->type_ == (uint32_t)AVTransTag::START_AV_SYNC) || + (avMessage->type_ == (uint32_t)AVTransTag::STOP_AV_SYNC)) { + syncManager_->HandleAvSyncMessage(avMessage); + } +} + +void AVTransControlCenter::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + (void)data; + (void)ext; +} + +bool AVTransControlCenter::IsInvalidEngineId(int32_t engineId) +{ + return (engineId < BASE_ENGINE_ID) || (engineId > rootEngineId_.load()); +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_control_center/services/src/ipc/av_trans_control_center_callback_proxy.cpp b/av_transport/av_trans_control_center/services/src/ipc/av_trans_control_center_callback_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a8e61c9ec3eb076ba56e77e61e8bc7bdea2a94b --- /dev/null +++ b/av_transport/av_trans_control_center/services/src/ipc/av_trans_control_center_callback_proxy.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_control_center_callback_proxy.h" + +#include +#include "nlohmann/json.hpp" +#include "parcel.h" + +#include "av_trans_constants.h" +#include "av_trans_errno.h" +#include "av_trans_log.h" +#include "av_trans_types.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVTransControlCenterCallbackProxy" + +int32_t AVTransControlCenterCallbackProxy::SetParameter(AVTransTag tag, const std::string& value) +{ + sptr remote = Remote(); + if (remote == nullptr) { + AVTRANS_LOGE("remote service is null"); + return ERR_DH_AVT_SERVICE_REMOTE_IS_NULL; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + AVTRANS_LOGE("WriteInterfaceToken fail!"); + return ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL; + } + if (!data.WriteUint32((uint32_t)tag)) { + AVTRANS_LOGE("Write tag failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteString(value)) { + AVTRANS_LOGE("Write value failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + int32_t ret = remote->SendRequest((uint32_t)IAVTransControlCenterCallback::Message::SET_PARAMETER, + data, reply, option); + if (ret != NO_ERROR) { + AVTRANS_LOGE("Send Request failed, ret: %d", ret); + return ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL; + } + + return reply.ReadInt32(); +} + +int32_t AVTransControlCenterCallbackProxy::SetSharedMemory(const AVTransSharedMemory &memory) +{ + sptr remote = Remote(); + if (remote == nullptr) { + AVTRANS_LOGE("remote service is null"); + return ERR_DH_AVT_SERVICE_REMOTE_IS_NULL; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + AVTRANS_LOGE("WriteInterfaceToken fail!"); + return ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL; + } + if (!data.WriteFileDescriptor(memory.fd)) { + AVTRANS_LOGE("Write memory fd failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteInt32(memory.size)) { + AVTRANS_LOGE("Write memory size failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteString(memory.name)) { + AVTRANS_LOGE("Write memory name failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + int32_t ret = remote->SendRequest((uint32_t)IAVTransControlCenterCallback::Message::SET_SHARED_MEMORY, + data, reply, option); + if (ret != NO_ERROR) { + AVTRANS_LOGE("Send Request failed, ret: %d", ret); + return ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL; + } + + return reply.ReadInt32(); +} + +int32_t AVTransControlCenterCallbackProxy::Notify(const AVTransEvent& event) +{ + sptr remote = Remote(); + if (remote == nullptr) { + AVTRANS_LOGE("remote service is null"); + return ERR_DH_AVT_SERVICE_REMOTE_IS_NULL; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + AVTRANS_LOGE("WriteInterfaceToken fail!"); + return ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL; + } + if (!data.WriteUint32((uint32_t)event.type)) { + AVTRANS_LOGE("Write event type failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteString(event.content)) { + AVTRANS_LOGE("Write event content failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteString(event.peerDevId)) { + AVTRANS_LOGE("Write event peerDevId failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + int32_t ret = remote->SendRequest((uint32_t)IAVTransControlCenterCallback::Message::NOTIFY_AV_EVENT, + data, reply, option); + if (ret != NO_ERROR) { + AVTRANS_LOGE("Send Request failed, ret: %d", ret); + return ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL; + } + + return reply.ReadInt32(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_control_center/test/unittest/BUILD.gn b/av_transport/av_trans_control_center/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..44cb3efa98097c4cb80f1b2e5a1dccd76c0c0667 --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/av_trans_control_center_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ "//third_party/json/include" ] + + include_dirs += [ + "./inner_kits", + "./services", + "${common_path}/include", + "${dh_fwk_utils_path}/include", + "${interface_path}/", + "${dh_fwk_sdk_path}/include", + "${engine_path}/av_receiver/include", + "${engine_path}/av_sender/include", + "${engine_path}/filters/av_transport_input", + "${distributedhardwarefwk_path}/utils/include/eventbus", + "${control_center_path}/inner_kits/include", + "${control_center_path}/services/include", + "${control_center_path}/services/include/ipc", + ] +} + +## UnitTest av_trans_control_center_test +ohos_unittest("AvTransControlCenterTest") { + module_out_path = module_out_path + + sources = [ + "${control_center_path}/test/unittest/inner_kits/av_trans_control_center_callback_stub_test.cpp", + "${control_center_path}/test/unittest/inner_kits/av_trans_control_center_callback_test.cpp", + "${control_center_path}/test/unittest/services/av_sync_manager_test.cpp", + "${control_center_path}/test/unittest/services/av_trans_control_center_test.cpp", + ] + + configs = [ ":module_private_config" ] + deps = [ + "${dh_fwk_sdk_path}:libdhfwk_sdk", + "${dh_fwk_services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "ipc:ipc_core", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + ] + cflags_cc = cflags + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_stub_test.cpp b/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_stub_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14a6fb0e92de758176a68f11268dacba1c62b256 --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_stub_test.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_control_center_callback_stub_test.h" +#include "av_trans_errno.h" +#include "av_trans_control_center_callback_proxy.h" + +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void AVTransControlCenterCallbackStubTest::SetUpTestCase(void) +{ +} + +void AVTransControlCenterCallbackStubTest::TearDownTestCase(void) +{ +} + +void AVTransControlCenterCallbackStubTest::SetUp() +{ +} + +void AVTransControlCenterCallbackStubTest::TearDown() +{ +} + +int32_t AVTransControlCenterCallbackStubTest::TestControlCenterCallbackStub::SetParameter( + AVTransTag tag, const std::string &value) +{ + (void) tag; + (void) value; + return DH_AVT_SUCCESS; +} +int32_t AVTransControlCenterCallbackStubTest::TestControlCenterCallbackStub::SetSharedMemory( + const AVTransSharedMemory &memory) +{ + (void) memory; + return DH_AVT_SUCCESS; +} +int32_t AVTransControlCenterCallbackStubTest::TestControlCenterCallbackStub::Notify( + const AVTransEvent &event) +{ + (void) event; + return DH_AVT_SUCCESS; +} + +/** + * @tc.name: set_parameter_001 + * @tc.desc: set parameter function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterCallbackStubTest, set_parameter_001, TestSize.Level0) +{ + sptr CallbackStubPtr(new TestControlCenterCallbackStub()); + AVTransControlCenterCallbackProxy callbackProxy(CallbackStubPtr); + + AVTransTag tag = AVTransTag::STOP_AV_SYNC; + std::string value = "value"; + int32_t ret = callbackProxy.SetParameter(tag, value); + EXPECT_EQ(NO_ERROR, ret); +} + +/** + * @tc.name: set_shared_memory_001 + * @tc.desc: set shared memory function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterCallbackStubTest, set_shared_memory_001, TestSize.Level0) +{ + sptr CallbackStubPtr(new TestControlCenterCallbackStub()); + AVTransControlCenterCallbackProxy callbackProxy(CallbackStubPtr); + + AVTransSharedMemory memory; + memory.name = "AVTransSharedMemory"; + int32_t ret = callbackProxy.SetSharedMemory(memory); + EXPECT_EQ(NO_ERROR, ret); +} + +/** + * @tc.name: notify_001 + * @tc.desc: notify function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterCallbackStubTest, notify_001, TestSize.Level0) +{ + sptr CallbackStubPtr(new TestControlCenterCallbackStub()); + AVTransControlCenterCallbackProxy callbackProxy(CallbackStubPtr); + + AVTransEvent event; + event.content = "content"; + int32_t ret = callbackProxy.Notify(event); + EXPECT_EQ(NO_ERROR, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_stub_test.h b/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_stub_test.h new file mode 100644 index 0000000000000000000000000000000000000000..7bbbaf0dd51ef75ce90bf2d6bfd9a5cebc26a4d4 --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_stub_test.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_STUB_TEST_H +#define OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_STUB_TEST_H + +#include +#include "av_trans_control_center_callback_stub.h" + +namespace OHOS { +namespace DistributedHardware { +class AVTransControlCenterCallbackStubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + class TestControlCenterCallbackStub : public OHOS::DistributedHardware::AVTransControlCenterCallbackStub { + public: + TestControlCenterCallbackStub() = default; + virtual ~TestControlCenterCallbackStub() = default; + int32_t SetParameter(AVTransTag tag, const std::string &value) override; + int32_t SetSharedMemory(const AVTransSharedMemory &memory) override; + int32_t Notify(const AVTransEvent &event) override; + }; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_test.cpp b/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cffa468352177fc24c67f837d5a68f7daf9719ea --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_test.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_control_center_callback_test.h" +#include "av_trans_errno.h" + +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void AVTransControlCenterCallbackTest::SetUpTestCase(void) +{ +} + +void AVTransControlCenterCallbackTest::TearDownTestCase(void) +{ +} + +void AVTransControlCenterCallbackTest::SetUp() +{ + callBack_ = std::make_shared(); + callBack_->receiverEngine_ = std::shared_ptr(); + callBack_->senderEngine_ = std::shared_ptr(); +} + +void AVTransControlCenterCallbackTest::TearDown() +{ + callBack_ = nullptr; +} + +/** + * @tc.name: set_parameter_001 + * @tc.desc: set parameter function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterCallbackTest, set_parameter_001, TestSize.Level0) +{ + AVTransTag tag = AVTransTag::START_AV_SYNC; + std::string value; + int32_t ret = callBack_->SetParameter(tag, value); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: set_parameter_002 + * @tc.desc: set parameter function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterCallbackTest, set_parameter_002, TestSize.Level0) +{ + AVTransTag tag = AVTransTag::STOP_AV_SYNC; + std::string value; + int32_t ret = callBack_->SetParameter(tag, value); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: set_parameter_003 + * @tc.desc: set parameter function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterCallbackTest, set_parameter_003, TestSize.Level0) +{ + AVTransTag tag = AVTransTag::TIME_SYNC_RESULT; + std::string value; + int32_t ret = callBack_->SetParameter(tag, value); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: set_shared_memory_001 + * @tc.desc: set shared memory function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterCallbackTest, set_shared_memory_001, TestSize.Level0) +{ + AVTransSharedMemory memory; + int32_t ret = callBack_->SetSharedMemory(memory); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: notify_001 + * @tc.desc: notify function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterCallbackTest, notify_001, TestSize.Level0) +{ + AVTransEvent event; + event.type = EventType::EVENT_ADD_STREAM; + int32_t ret = callBack_->Notify(event); + std::shared_ptr sender = std::shared_ptr(); + callBack_->SetSenderEngine(sender); + std::shared_ptr receiver = std::shared_ptr(); + callBack_->SetReceiverEngine(receiver); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_test.h b/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_test.h new file mode 100644 index 0000000000000000000000000000000000000000..dac38844327f6e1332b707f4d781ee23e3681abc --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/inner_kits/av_trans_control_center_callback_test.h @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_TEST_H +#define OHOS_AV_TRANS_CONTROL_CENTER_CALLBACK_TEST_H + +#include + +#include + +#define private public +#include "av_trans_control_center_callback.h" +#undef private +#include "av_trans_types.h" +#include "av_sync_utils.h" +#include "i_av_receiver_engine.h" +#include "i_av_receiver_engine_callback.h" +#include "i_av_sender_engine.h" +#include "i_av_sender_engine_callback.h" +#include "av_trans_message.h" +#include "av_trans_buffer.h" +namespace OHOS { +namespace DistributedHardware { +class AVTransControlCenterCallbackTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr callBack_ = nullptr; +}; +class ReceiverEngineTest : public IAVReceiverEngine { +public: + ReceiverEngineTest() = default; + ~ReceiverEngineTest() override = default; + int32_t Initialize() override + { + return DH_AVT_SUCCESS; + } + + int32_t Release() override + { + return DH_AVT_SUCCESS; + } + + int32_t Start() override + { + return DH_AVT_SUCCESS; + } + + int32_t Stop() override + { + return DH_AVT_SUCCESS; + } + + int32_t SetParameter(AVTransTag tag, const std::string &value) override + { + (void) tag; + (void) value; + return DH_AVT_SUCCESS; + } + + int32_t SendMessage(const std::shared_ptr &message) override + { + (void) message; + return DH_AVT_SUCCESS; + } + + int32_t CreateControlChannel(const std::vector &dstDevIds, + const ChannelAttribute &attribution) override + { + (void) dstDevIds; + (void) attribution; + return DH_AVT_SUCCESS; + } + + int32_t RegisterReceiverCallback(const std::shared_ptr &callback) override + { + (void) callback; + return DH_AVT_SUCCESS; + } +}; +class SenderEngineTest : public IAVSenderEngine { +public: + SenderEngineTest() = default; + ~SenderEngineTest() override = default; + int32_t Initialize() override + { + return DH_AVT_SUCCESS; + } + + int32_t Release() override + { + return DH_AVT_SUCCESS; + } + + int32_t Start() override + { + return DH_AVT_SUCCESS; + } + + int32_t Stop() override + { + return DH_AVT_SUCCESS; + } + + int32_t PushData(const std::shared_ptr &buffer) override + { + (void) buffer; + return DH_AVT_SUCCESS; + } + + int32_t SetParameter(AVTransTag tag, const std::string &value) override + { + (void) tag; + (void) value; + return DH_AVT_SUCCESS; + } + + int32_t SendMessage(const std::shared_ptr &message) override + { + (void) message; + return DH_AVT_SUCCESS; + } + + int32_t CreateControlChannel(const std::vector &dstDevIds, + const ChannelAttribute &attribution) override + { + (void) dstDevIds; + (void) attribution; + return DH_AVT_SUCCESS; + } + + int32_t RegisterSenderCallback(const std::shared_ptr &callback) override + { + (void) callback; + return DH_AVT_SUCCESS; + } +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/av_transport/av_trans_control_center/test/unittest/services/av_sync_manager_test.cpp b/av_transport/av_trans_control_center/test/unittest/services/av_sync_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7914a82cdee2d11ecbfedbbee56c59e0b6e8b1db --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/services/av_sync_manager_test.cpp @@ -0,0 +1,327 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_sync_manager_test.h" +#include "av_trans_errno.h" + +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void AVSyncManagerTest::SetUpTestCase(void) +{ +} + +void AVSyncManagerTest::TearDownTestCase(void) +{ +} + +void AVSyncManagerTest::SetUp() +{ + syncManager_ = std::make_shared(); +} + +void AVSyncManagerTest::TearDown() +{ + syncManager_ = nullptr; +} + +/** + * @tc.name: add_stream_info_001 + * @tc.desc: add stream info function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, add_stream_info_001, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo stream; + syncManager_->AddStreamInfo(stream); + EXPECT_NE(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: add_stream_info_002 + * @tc.desc: add stream info function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, add_stream_info_002, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + syncManager_->AddStreamInfo(streamFirst); + AVStreamInfo streamSecond; + syncManager_->AddStreamInfo(streamSecond); + EXPECT_NE(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: remove_stream_info_001 + * @tc.desc: remove stream info function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, remove_stream_info_001, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = "streamFirstType"; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + AVStreamInfo streamSecond; + streamSecond.sceneType = "streamSecondType"; + streamSecond.peerDevId = "streamSecondpeerDevId"; + syncManager_->AddStreamInfo(streamSecond); + + syncManager_->RemoveStreamInfo(streamSecond); + EXPECT_NE(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: enable_sender_av_sync_001 + * @tc.desc: enable sender av sync function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, enable_sender_av_sync_001, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = "streamFirstType"; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + syncManager_->EnableSenderAVSync(); + + EXPECT_NE(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: disable_sender_av_sync_001 + * @tc.desc: disable sender av sync function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, disable_sender_av_sync_001, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = "streamFirstType"; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + AVStreamInfo streamSecond; + streamSecond.sceneType = "streamSecondType"; + streamSecond.peerDevId = "streamSecondpeerDevId"; + syncManager_->AddStreamInfo(streamSecond); + syncManager_->DisableSenderAVSync(); + + EXPECT_EQ(2, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: disable_sender_av_sync_002 + * @tc.desc: disable sender av sync function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, disable_sender_av_sync_002, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + syncManager_->DisableSenderAVSync(); + + EXPECT_EQ(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: handle_av_sync_message_001 + * @tc.desc: handle av sync function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, handle_av_sync_message_001, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = "streamFirstType"; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + std::shared_ptr message = std::make_shared(); + message->type_ = (uint32_t)AVTransTag::START_AV_SYNC; + syncManager_->HandleAvSyncMessage(message); + EXPECT_NE(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: handle_av_sync_message_002 + * @tc.desc: handle av sync function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, handle_av_sync_message_002, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = "streamFirstType"; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + std::shared_ptr message = std::make_shared(); + message->type_ = (uint32_t)AVTransTag::STOP_AV_SYNC; + syncManager_->HandleAvSyncMessage(message); + EXPECT_NE(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: enable_receiver_av_sync_001 + * @tc.desc: enable receiver av sync function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, enable_receiver_av_sync_001, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = "streamFirstType"; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + std::string groupInfo = "groupInfo"; + syncManager_->EnableReceiverAVSync(groupInfo); + EXPECT_NE(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: disable_receiver_av_sync_001 + * @tc.desc: disable receiver av sync function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, disable_receiver_av_sync_001, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = "streamFirstType"; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + std::string groupInfo = "groupInfo"; + syncManager_->DisableReceiverAVSync(groupInfo); + EXPECT_NE(0, syncManager_->streamInfoList_.size()); +} + +/** + * @tc.name: merge_group_info_001 + * @tc.desc: merge group info function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, merge_group_info_001, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = "streamFirstType"; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + std::string groupInfo; + bool ret = syncManager_->MergeGroupInfo(groupInfo); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: merge_group_info_002 + * @tc.desc: merge group info function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, merge_group_info_002, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = SCENE_TYPE_D_MIC; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + AVStreamInfo streamSecond; + streamSecond.sceneType = SCENE_TYPE_D_SPEAKER; + streamSecond.peerDevId = "streamSecondpeerDevId"; + syncManager_->AddStreamInfo(streamSecond); + + std::string groupInfo; + bool ret = syncManager_->MergeGroupInfo(groupInfo); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: merge_group_info_003 + * @tc.desc: merge group info function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, merge_group_info_003, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = MIME_VIDEO_RAW; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + AVStreamInfo streamSecond; + streamSecond.sceneType = MIME_VIDEO_H264; + streamSecond.peerDevId = "streamSecondpeerDevId"; + syncManager_->AddStreamInfo(streamSecond); + + std::string groupInfo; + bool ret = syncManager_->MergeGroupInfo(groupInfo); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: merge_group_info_004 + * @tc.desc: merge group info function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVSyncManagerTest, merge_group_info_004, TestSize.Level0) +{ + syncManager_->streamInfoList_.clear(); + AVStreamInfo streamFirst; + streamFirst.sceneType = SCENE_TYPE_D_SCREEN; + streamFirst.peerDevId = "streamFirstpeerDevId"; + syncManager_->AddStreamInfo(streamFirst); + + AVStreamInfo streamSecond; + streamSecond.sceneType = SCENE_TYPE_D_SPEAKER; + streamSecond.peerDevId = "streamSecondpeerDevId"; + syncManager_->AddStreamInfo(streamSecond); + + AVStreamInfo streamThird; + streamThird.sceneType = SCENE_TYPE_D_CAMERA_STR; + streamThird.peerDevId = "streamThirdpeerDevId"; + syncManager_->AddStreamInfo(streamThird); + + AVStreamInfo streamFourth; + streamFourth.sceneType = SCENE_TYPE_D_MIC; + streamFourth.peerDevId = "streamFourthpeerDevId"; + syncManager_->AddStreamInfo(streamFourth); + + std::string groupInfo; + bool ret = syncManager_->MergeGroupInfo(groupInfo); + EXPECT_EQ(false, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_control_center/test/unittest/services/av_sync_manager_test.h b/av_transport/av_trans_control_center/test/unittest/services/av_sync_manager_test.h new file mode 100644 index 0000000000000000000000000000000000000000..5ca461ef9ddd898d6e8d64743049e84e4e853d54 --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/services/av_sync_manager_test.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_SYNC_MANAGER_TEST_H +#define OHOS_AV_SYNC_MANAGER_TEST_H + +#include + +#define private public +#include "av_sync_manager.h" +#undef private +namespace OHOS { +namespace DistributedHardware { +class AVSyncManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr syncManager_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/av_transport/av_trans_control_center/test/unittest/services/av_trans_control_center_test.cpp b/av_transport/av_trans_control_center/test/unittest/services/av_trans_control_center_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68b2268e396eceeb44bd5032ef21d7eafa263c64 --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/services/av_trans_control_center_test.cpp @@ -0,0 +1,471 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_control_center_test.h" +#include "av_trans_errno.h" + +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void AVTransControlCenterTest::SetUpTestCase(void) +{ +} + +void AVTransControlCenterTest::TearDownTestCase(void) +{ +} + +void AVTransControlCenterTest::SetUp() +{ + center_ = std::make_shared(); +} + +void AVTransControlCenterTest::TearDown() +{ + center_ = nullptr; +} + +/** + * @tc.name: initialize_av_center_001 + * @tc.desc: initialize av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, initialize_av_center_001, TestSize.Level0) +{ + TransRole transRole = TransRole::UNKNOWN; + int32_t engineId = BASE_ENGINE_ID; + int32_t ret = center_->InitializeAVCenter(transRole, engineId); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM_VALUE, ret); +} + +/** + * @tc.name: initialize_av_center_002 + * @tc.desc: initialize av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, initialize_av_center_002, TestSize.Level0) +{ + TransRole transRole = TransRole::AV_SENDER; + int32_t engineId = BASE_ENGINE_ID; + center_->initialized_= true; + int32_t ret = center_->InitializeAVCenter(transRole, engineId); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: initialize_av_center_003 + * @tc.desc: initialize av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, initialize_av_center_003, TestSize.Level0) +{ + TransRole transRole = TransRole::AV_SENDER; + int32_t engineId = BASE_ENGINE_ID; + center_->initialized_= false; + int32_t ret = center_->InitializeAVCenter(transRole, engineId); + EXPECT_EQ(ERR_DH_AVT_CREATE_CHANNEL_FAILED, ret); +} + +/** + * @tc.name: release_av_center_001 + * @tc.desc: release av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, release_av_center_001, TestSize.Level0) +{ + int32_t engineId = INVALID_ENGINE_ID; + int32_t ret = center_->ReleaseAVCenter(engineId); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM_VALUE, ret); +} + +/** + * @tc.name: release_av_center_002 + * @tc.desc: release av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, release_av_center_002, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + int32_t engineIdSecond = BASE_ENGINE_ID + 1 ; + center_->engine2DevIdMap_.insert(std::make_pair(engineId, "engineId")); + center_->engine2DevIdMap_.insert(std::make_pair(engineIdSecond, "engineId")); + int32_t ret = center_->ReleaseAVCenter(engineId); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: release_av_center_003 + * @tc.desc: release av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, release_av_center_003, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + center_->engine2DevIdMap_.insert(std::make_pair(engineId, "engineId")); + int32_t ret = center_->ReleaseAVCenter(engineId); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: release_av_center_004 + * @tc.desc: release av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, release_av_center_004, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + center_->engine2DevIdMap_.insert(std::make_pair(engineId, "engineId")); + center_->connectedDevIds_.push_back("engineId"); + int32_t ret = center_->ReleaseAVCenter(engineId); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: create_control_channel_001 + * @tc.desc: create control channel function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, create_control_channel_001, TestSize.Level0) +{ + int32_t engineId = INVALID_ENGINE_ID; + std::string peerDevId = "peerDevId"; + int32_t ret = center_->CreateControlChannel(engineId, peerDevId); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM_VALUE, ret); +} + +/** + * @tc.name: create_control_channel_002 + * @tc.desc: create control channel function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, create_control_channel_002, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + std::string peerDevId = "peerDevId"; + center_->initialized_ = false; + int32_t ret = center_->CreateControlChannel(engineId, peerDevId); + EXPECT_EQ(ERR_DH_AVT_CREATE_CHANNEL_FAILED, ret); +} + +/** + * @tc.name: create_control_channel_003 + * @tc.desc: create control channel function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, create_control_channel_003, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + std::string peerDevId = "peerDevId"; + center_->initialized_ = true; + center_->connectedDevIds_.push_back("peerDevId"); + int32_t ret = center_->CreateControlChannel(engineId, peerDevId); + EXPECT_EQ(ERR_DH_AVT_CHANNEL_ALREADY_CREATED, ret); +} + +/** + * @tc.name: create_control_channel_004 + * @tc.desc: create control channel function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, create_control_channel_004, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + std::string peerDevId = "peerDevId"; + center_->initialized_ = true; + int32_t ret = center_->CreateControlChannel(engineId, peerDevId); + EXPECT_EQ(ERR_DH_AVT_SESSION_ERROR, ret); +} + +/** + * @tc.name: notify_av_center_001 + * @tc.desc: notify av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, notify_av_center_001, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + AVTransEvent event; + event.type = EventType::EVENT_ADD_STREAM; + + int32_t ret = center_->NotifyAVCenter(engineId, event); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: notify_av_center_002 + * @tc.desc: notify av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, notify_av_center_002, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + AVTransEvent event; + event.type = EventType::EVENT_REMOVE_STREAM; + + int32_t ret = center_->NotifyAVCenter(engineId, event); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: notify_av_center_003 + * @tc.desc: notify av center function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, notify_av_center_003, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + AVTransEvent event; + event.type = EventType::EVENT_CHANNEL_OPENED; + + int32_t ret = center_->NotifyAVCenter(engineId, event); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: register_ctl_center_callback_001 + * @tc.desc: register ctl center callback function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, register_ctl_center_callback_001, TestSize.Level0) +{ + int32_t engineId = INVALID_ENGINE_ID; + sptr callback = nullptr; + int32_t ret = center_->RegisterCtlCenterCallback(engineId, callback); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM_VALUE, ret); +} + +/** + * @tc.name: register_ctl_center_callback_002 + * @tc.desc: register ctl center callback function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, register_ctl_center_callback_002, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + sptr callback = nullptr; + int32_t ret = center_->RegisterCtlCenterCallback(engineId, callback); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM_VALUE, ret); +} + +/** + * @tc.name: register_ctl_center_callback_003 + * @tc.desc: register ctl center callback function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, register_ctl_center_callback_003, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID; + sptr callback = new CenterCallback(); + int32_t ret = center_->RegisterCtlCenterCallback(engineId, callback); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: on_channel_event_001 + * @tc.desc: on channel event function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, on_channel_event_001, TestSize.Level0) +{ + AVTransEvent event; + event.type = EventType::EVENT_CHANNEL_CLOSED; + center_->OnChannelEvent(event); + int32_t engineId = BASE_ENGINE_ID; + sptr callback = new CenterCallback(); + int32_t ret = center_->RegisterCtlCenterCallback(engineId, callback); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: on_channel_event_002 + * @tc.desc: on channel event function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, on_channel_event_002, TestSize.Level0) +{ + AVTransEvent event; + event.type = EventType::EVENT_DATA_RECEIVED; + center_->OnChannelEvent(event); + int32_t engineId = BASE_ENGINE_ID; + sptr callback = new CenterCallback(); + int32_t ret = center_->RegisterCtlCenterCallback(engineId, callback); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: on_channel_event_003 + * @tc.desc: on channel event function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, on_channel_event_003, TestSize.Level0) +{ + AVTransEvent event; + event.type = EventType::EVENT_TIME_SYNC_RESULT; + center_->sessionName_ = AV_SYNC_RECEIVER_CONTROL_SESSION_NAME; + center_->OnChannelEvent(event); + int32_t engineId = BASE_ENGINE_ID; + sptr callback = new CenterCallback(); + int32_t ret = center_->RegisterCtlCenterCallback(engineId, callback); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: on_channel_event_004 + * @tc.desc: on channel event function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, on_channel_event_004, TestSize.Level0) +{ + AVTransEvent event; + event.type = EventType::EVENT_REMOVE_STREAM; + center_->sessionName_ = AV_SYNC_RECEIVER_CONTROL_SESSION_NAME; + center_->OnChannelEvent(event); + + StreamData *data = nullptr; + StreamData *ext = nullptr; + center_->OnStreamReceived(data, ext); + int32_t engineId = BASE_ENGINE_ID; + sptr callback = new CenterCallback(); + int32_t ret = center_->RegisterCtlCenterCallback(engineId, callback); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +/** + * @tc.name: send_message_001 + * @tc.desc: send message function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, send_message_001, TestSize.Level0) +{ + std::shared_ptr message = nullptr; + int32_t ret = center_->SendMessage(message);; + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM, ret); +} + +/** + * @tc.name: send_message_002 + * @tc.desc: send message function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, send_message_002, TestSize.Level0) +{ + std::shared_ptr message = std::make_shared(); + int32_t ret = center_->SendMessage(message);; + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM, ret); +} + +/** + * @tc.name: set_param_2_engines_001 + * @tc.desc: set param2engines function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, set_param_2_engines_001, TestSize.Level0) +{ + AVTransTag tag = AVTransTag::START_AV_SYNC; + std::string value = "value"; + int32_t engineId = BASE_ENGINE_ID; + sptr callback = new CenterCallback(); + center_->callbackMap_.insert(std::make_pair(engineId, callback)); + center_->SetParam2Engines(tag, value); + EXPECT_EQ(callback->value_, value); +} + +/** + * @tc.name: set_param_2_engines_002 + * @tc.desc: set param2engines function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, set_param_2_engines_002, TestSize.Level0) +{ + AVTransSharedMemory memory; + memory.name = "memory"; + sptr callback = new CenterCallback(); + center_->callbackMap_.insert(std::make_pair(0, callback)); + center_->SetParam2Engines(memory); + EXPECT_EQ(callback->memory_.name, memory.name); +} + +/** + * @tc.name: handle_channel_event_001 + * @tc.desc: handle channel event function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, handle_channel_event_001, TestSize.Level0) +{ + AVTransEvent event; + event.type = EventType::EVENT_CHANNEL_CLOSED; + center_->HandleChannelEvent(event); + event.type = EventType::EVENT_CHANNEL_OPEN_FAIL; + center_->HandleChannelEvent(event); + event.type = EventType::EVENT_CHANNEL_OPENED; + event.content = AV_SYNC_RECEIVER_CONTROL_SESSION_NAME; + center_->HandleChannelEvent(event); + + EXPECT_NE(0, center_->connectedDevIds_.size()); +} + +/** + * @tc.name: is_invalid_engineId_001 + * @tc.desc: is invalid engineId function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, is_invalid_engineId_001, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID - 1; + bool ret = center_->IsInvalidEngineId(engineId); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: is_invalid_engineId_002 + * @tc.desc: is invalid engineId function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(AVTransControlCenterTest, is_invalid_engineId_002, TestSize.Level0) +{ + int32_t engineId = BASE_ENGINE_ID + 1; + bool ret = center_->IsInvalidEngineId(engineId); + EXPECT_EQ(true, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_control_center/test/unittest/services/av_trans_control_center_test.h b/av_transport/av_trans_control_center/test/unittest/services/av_trans_control_center_test.h new file mode 100644 index 0000000000000000000000000000000000000000..c0ab074435993b279e038334744aa9b3967c02e2 --- /dev/null +++ b/av_transport/av_trans_control_center/test/unittest/services/av_trans_control_center_test.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_CONTROL_CENTER_TEST_H +#define OHOS_AV_TRANS_CONTROL_CENTER_TEST_H + +#include + +#define private public +#include "av_trans_control_center.h" +#undef private +#include "av_trans_control_center_callback_stub.h" +#include "av_trans_types.h" +#include "av_sync_utils.h" + +namespace OHOS { +namespace DistributedHardware { +class AVTransControlCenterTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr center_ = nullptr; +}; +class CenterCallback : public AVTransControlCenterCallbackStub { +public: + CenterCallback() = default; + ~CenterCallback() override = default; + int32_t SetParameter(AVTransTag tag, const std::string &value) override + { + value_ = value; + return DH_AVT_SUCCESS; + } + int32_t SetSharedMemory(const AVTransSharedMemory &memory) override + { + memory_ = memory; + return DH_AVT_SUCCESS; + } + int32_t Notify(const AVTransEvent &event) override + { + return DH_AVT_SUCCESS; + } + std::string value_; + AVTransSharedMemory memory_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/av_transport/av_trans_engine/av_receiver/BUILD.gn b/av_transport/av_trans_engine/av_receiver/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..42e5771f2730b0bc4b3f93367ad54a5e5cb47a68 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/BUILD.gn @@ -0,0 +1,111 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +config("receiver_external_config") { + include_dirs = [ + "${common_path}/include", + "${dh_fwk_sdk_path}/include", + "${engine_path}/av_sender/include", + "${engine_path}/av_receiver/include", + "${interface_path}", + ] +} + +ohos_shared_library("distributed_av_receiver") { + public_configs = [ ":receiver_external_config" ] + + include_dirs = [ + "${drivers_disaplay_path}/interfaces/include", + "${media_standard_path}/interfaces/inner_api/native", + "//third_party/json/include", + "${common_path}/include", + "${engine_path}", + "${engine_path}/av_sender/include", + "${engine_path}/av_receiver/include", + "${interface_path}", + "${dh_fwk_utils_path}/include", + "${dh_fwk_utils_path}/include", + "${control_center_path}/inner_kits/include", + "${control_center_path}/inner_kits/include/ipc", + "${filters_path}/av_transport_input", + "${filters_path}/av_transport_output", + ] + + sources = [ + "${common_path}/src/av_sync_utils.cpp", + "${common_path}/src/av_trans_buffer.cpp", + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_message.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "${common_path}/src/softbus_channel_adapter.cpp", + "${engine_path}/av_receiver/src/av_receiver_engine.cpp", + "${engine_path}/av_receiver/src/av_receiver_engine_provider.cpp", + ] + + deps = [ + "${dh_fwk_sdk_path}:libdhfwk_sdk", + "${filters_path}:avtrans_input_filter", + "${filters_path}:avtrans_output_filter", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"av_trans_receiver\"", + "LOG_DOMAIN=0xD004100", + ] + + defines += [ + "MEDIA_OHOS", + "RECORDER_SUPPORT", + "VIDEO_SUPPORT", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "graphic_2d:libgraphic_utils", + "graphic_2d:surface", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + remove_configs = [ + "//build/config/compiler:no_rtti", + "//build/config/compiler:no_exceptions", + ] + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + ] + cflags_cc = cflags + + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/av_receiver/include/av_receiver_engine.h b/av_transport/av_trans_engine/av_receiver/include/av_receiver_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..6b6d6be32c1ba4c801f7ef6db1876603bb7cb684 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/include/av_receiver_engine.h @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_RECEIVER_ENGINE_H +#define OHOS_AV_RECEIVER_ENGINE_H + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_message.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "i_av_receiver_engine.h" +#include "softbus_channel_adapter.h" +#include "distributed_hardware_fwk_kit.h" +#include "av_trans_control_center_callback.h" +#include "av_transport_input_filter.h" +#include "av_transport_output_filter.h" + +// follwing head files depends on histreamer +#include "error_code.h" +#include "event.h" +#include "pipeline/core/filter.h" +#include "plugin_event.h" +#include "pipeline_core.h" +#include "audio_decoder_filter.h" +#include "video_decoder_filter.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +using namespace OHOS::Media::Pipeline; +using AVBuffer = OHOS::Media::Plugin::Buffer; + +class AVReceiverEngine : public IAVReceiverEngine, + public ISoftbusChannelListener, + public OHOS::Media::Pipeline::EventReceiver, + public std::enable_shared_from_this { +public: + AVReceiverEngine(const std::string &ownerName, const std::string &peerDevId); + ~AVReceiverEngine() override; + AVReceiverEngine(const AVReceiverEngine &other) = delete; + AVReceiverEngine& operator=(const AVReceiverEngine &other) = delete; + + // interfaces from IAVReceiverEngine + int32_t Initialize() override; + int32_t Start() override; + int32_t Stop() override; + int32_t Release() override; + int32_t SetParameter(AVTransTag tag, const std::string &value) override; + int32_t SendMessage(const std::shared_ptr &message) override; + int32_t CreateControlChannel(const std::vector &dstDevIds, + const ChannelAttribute &attribution) override; + int32_t RegisterReceiverCallback(const std::shared_ptr &callback) override; + + // interfaces from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + + // interfaces from OHOS::Media::Pipeline::EventReceiver + void OnEvent(const OHOS::Media::Event &event) override; + +private: + int32_t InitPipeline(); + int32_t InitControlCenter(); + int32_t PreparePipeline(const std::string &configParam); + int32_t HandleOutputBuffer(std::shared_ptr &hisBuffer); + + void RegRespFunMap(); + void SetVideoWidth(const std::string &value); + void SetVideoHeight(const std::string &value); + void SetVideoFrameRate(const std::string &value); + void SetAudioBitRate(const std::string &value); + void SetVideoBitRate(const std::string &value); + void SetVideoCodecType(const std::string &value); + void SetAudioCodecType(const std::string &value); + void SetAudioChannelMask(const std::string &value); + void SetAudioSampleRate(const std::string &value); + void SetAudioChannelLayout(const std::string &value); + void SetAudioSampleFormat(const std::string &value); + void SetAudioFrameSize(const std::string &value); + void SetSyncResult(const std::string &value); + void SetStartAvSync(const std::string &value); + void SetStopAvSync(const std::string &value); + void SetSharedMemoryFd(const std::string &value); + void SetEngineReady(const std::string &value); + + StateId GetCurrentState() + { + std::lock_guard lock(stateMutex_); + return currentState_; + } + + void SetCurrentState(StateId stateId) + { + std::lock_guard lock(stateMutex_); + currentState_ = stateId; + } + +private: + int32_t engineId_ = 0; + std::string ownerName_; + std::string sessionName_; + std::string peerDevId_; + std::mutex stateMutex_; + std::atomic initialized_ {false}; + std::atomic currentState_ = StateId::IDLE; + + sptr ctlCenCallback_ = nullptr; + std::shared_ptr dhfwkKit_ = nullptr; + std::shared_ptr receiverCallback_ = nullptr; + std::shared_ptr pipeline_ = nullptr; + + std::shared_ptr avInput_; + std::shared_ptr avOutput_; + std::shared_ptr audioDecoder_; + std::shared_ptr videoDecoder_; + + using SetParaFunc = void (AVReceiverEngine::*)(const std::string &value); + std::map funcMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_RECEIVER_ENGINE_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_receiver/include/av_receiver_engine_provider.h b/av_transport/av_trans_engine/av_receiver/include/av_receiver_engine_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..d3d0b3d7b8a11f29660bd787791787cbd8808d28 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/include/av_receiver_engine_provider.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_RECEIVER_ENGINE_PROVIDER_H +#define OHOS_AV_RECEIVER_ENGINE_PROVIDER_H + +#include + +#include "i_av_engine_provider.h" +#include "softbus_channel_adapter.h" + +namespace OHOS { +namespace DistributedHardware { +class AVReceiverEngineProvider : public IAVEngineProvider, public ISoftbusChannelListener { +public: + AVReceiverEngineProvider(const std::string &ownerName); + ~AVReceiverEngineProvider() override; + + std::shared_ptr CreateAVReceiverEngine(const std::string &peerDevId) override; + std::vector> GetAVReceiverEngineList() override; + int32_t RegisterProviderCallback(const std::shared_ptr &callback) override; + + // interfaces from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + +private: + std::string ownerName_; + std::string sessionName_; + std::mutex listMutex_; + std::shared_ptr providerCallback_; + std::vector> receiverEngineList_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_RECEIVER_ENGINE_PROVIDER_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_receiver/src/av_receiver_engine.cpp b/av_transport/av_trans_engine/av_receiver/src/av_receiver_engine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71daee5fd44a7781aac81dad3fcefa53a5d98b7d --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/src/av_receiver_engine.cpp @@ -0,0 +1,480 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_receiver_engine.h" + +#include "pipeline/factory/filter_factory.h" +#include "plugin_video_tags.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVReceiverEngine" + +AVReceiverEngine::AVReceiverEngine(const std::string &ownerName, const std::string &peerDevId) + : ownerName_(ownerName), peerDevId_(peerDevId) +{ + AVTRANS_LOGI("AVReceiverEngine ctor."); + sessionName_ = ownerName_ + "_" + RECEIVER_CONTROL_SESSION_NAME_SUFFIX; +} + +AVReceiverEngine::~AVReceiverEngine() +{ + AVTRANS_LOGI("AVReceiverEngine dctor."); + Release(); + + dhfwkKit_ = nullptr; + pipeline_ = nullptr; + avInput_ = nullptr; + avOutput_ = nullptr; + audioDecoder_ = nullptr; + videoDecoder_ = nullptr; + ctlCenCallback_ = nullptr; +} + +int32_t AVReceiverEngine::Initialize() +{ + TRUE_RETURN_V_MSG_E(initialized_.load(), DH_AVT_SUCCESS, "sender engine has been initialized"); + + int32_t ret = InitPipeline(); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_INIT_FAILED, "init pipeline failed"); + + ret = InitControlCenter(); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_INIT_FAILED, "init av control center failed"); + + ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, peerDevId_, this); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_INIT_FAILED, "register receiver channel callback failed"); + RegRespFunMap(); + initialized_ = true; + SetCurrentState(StateId::INITIALIZED); + return DH_AVT_SUCCESS; +} + +int32_t AVReceiverEngine::InitPipeline() +{ + AVTRANS_LOGI("InitPipeline enter."); + FilterFactory::Instance().Init(); + avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + TRUE_RETURN_V_MSG_E(avInput_ == nullptr, ERR_DH_AVT_NULL_POINTER, "create av input filter failed"); + + avOutput_ = FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, "avoutput"); + TRUE_RETURN_V_MSG_E(avOutput_ == nullptr, ERR_DH_AVT_NULL_POINTER, "create av output filter failed"); + + videoDecoder_ = FilterFactory::Instance().CreateFilterWithType(VDECODER_NAME, "videoDec"); + TRUE_RETURN_V_MSG_E(videoDecoder_ == nullptr, ERR_DH_AVT_NULL_POINTER, "create av video decoder filter failed"); + + audioDecoder_ = FilterFactory::Instance().CreateFilterWithType(ADECODER_NAME, "audioDec"); + TRUE_RETURN_V_MSG_E(audioDecoder_ == nullptr, ERR_DH_AVT_NULL_POINTER, "create av audio decoder filter failed"); + + ErrorCode ret; + pipeline_ = std::make_shared(); + pipeline_->Init(this, nullptr); + if ((ownerName_ == OWNER_NAME_D_SCREEN) || (ownerName_ == OWNER_NAME_D_CAMERA)) { + ret = pipeline_->AddFilters({avInput_.get(), videoDecoder_.get(), avOutput_.get()}); + if (ret == ErrorCode::SUCCESS) { + ret = pipeline_->LinkFilters({avInput_.get(), videoDecoder_.get(), avOutput_.get()}); + } + } else if ((ownerName_ == OWNER_NAME_D_MIC) || (ownerName_ == OWNER_NAME_D_SPEAKER)) { + ret = pipeline_->AddFilters({avInput_.get(), avOutput_.get()}); + if (ret == ErrorCode::SUCCESS) { + ret = pipeline_->LinkFilters({avInput_.get(), avOutput_.get()}); + } + } else { + AVTRANS_LOGI("unsupport ownerName:%s", ownerName_.c_str()); + return ERR_DH_AVT_INVALID_PARAM_VALUE; + } + if (ret != ErrorCode::SUCCESS) { + pipeline_->RemoveFilterChain(avInput_.get()); + } + return (ret == ErrorCode::SUCCESS) ? DH_AVT_SUCCESS : ERR_DH_AVT_INVALID_OPERATION; +} + +int32_t AVReceiverEngine::InitControlCenter() +{ + dhfwkKit_ = std::make_shared(); + int32_t ret = dhfwkKit_->InitializeAVCenter(TransRole::AV_RECEIVER, engineId_); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_CTRL_CENTER_INIT_FAIL, "init av trans control center failed"); + + ctlCenCallback_ = new (std::nothrow) AVTransControlCenterCallback(); + TRUE_RETURN_V_MSG_E(ctlCenCallback_ == nullptr, ERR_DH_AVT_REGISTER_CALLBACK_FAIL, + "new control center callback failed"); + + std::shared_ptr engine = std::shared_ptr(shared_from_this()); + ctlCenCallback_->SetReceiverEngine(engine); + + ret = dhfwkKit_->RegisterCtlCenterCallback(engineId_, ctlCenCallback_); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_REGISTER_CALLBACK_FAIL, + "register control center callback failed"); + + return DH_AVT_SUCCESS; +} + +int32_t AVReceiverEngine::CreateControlChannel(const std::vector &dstDevIds, + const ChannelAttribute &attribution) +{ + (void)attribution; + AVTRANS_LOGI("CreateControlChannel enter."); + TRUE_RETURN_V_MSG_E(dstDevIds.empty(), ERR_DH_AVT_NULL_POINTER, "dst deviceId vector is empty"); + + peerDevId_ = dstDevIds[0]; + int32_t ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, peerDevId_, this); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_CREATE_CHANNEL_FAILED, + "register receiver control channel callback failed"); + + std::string peerSessName = ownerName_ + "_" + SENDER_CONTROL_SESSION_NAME_SUFFIX; + ret = SoftbusChannelAdapter::GetInstance().OpenSoftbusChannel(sessionName_, peerSessName, peerDevId_); + TRUE_RETURN_V(ret == ERR_DH_AVT_SESSION_HAS_OPENED, ERR_DH_AVT_CHANNEL_ALREADY_CREATED); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_CREATE_CHANNEL_FAILED, + "create receiver control channel failed"); + + SetCurrentState(StateId::CH_CREATING); + return DH_AVT_SUCCESS; +} + +int32_t AVReceiverEngine::PreparePipeline(const std::string &configParam) +{ + AVTRANS_LOGI("PreparePipeline enter."); + + StateId currentState = GetCurrentState(); + bool isErrState = ((currentState != StateId::INITIALIZED) && (currentState != StateId::CH_CREATED)); + TRUE_RETURN_V_MSG_E(isErrState, ERR_DH_AVT_PREPARE_FAILED, + "current state=%" PRId32 " is invalid.", currentState); + + TRUE_RETURN_V_MSG_E((avInput_ == nullptr) || (avOutput_ == nullptr), ERR_DH_AVT_PREPARE_FAILED, + "av input or output filter is null"); + + ErrorCode ret = avInput_->SetParameter(static_cast(Plugin::Tag::MEDIA_TYPE), + TransName2MediaType(ownerName_)); + TRUE_RETURN_V(ret != ErrorCode::SUCCESS, ERR_DH_AVT_SET_PARAM_FAILED); + + ret = avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_BIT_STREAM_FORMAT), + VideoBitStreamFormat::ANNEXB); + TRUE_RETURN_V(ret != ErrorCode::SUCCESS, ERR_DH_AVT_SET_PARAM_FAILED); + + ret = avInput_->SetParameter(static_cast(Plugin::Tag::MEDIA_DESCRIPTION), + BuildChannelDescription(ownerName_, peerDevId_)); + TRUE_RETURN_V(ret != ErrorCode::SUCCESS, ERR_DH_AVT_SET_PARAM_FAILED); + + ret = pipeline_->Prepare(); + TRUE_RETURN_V(ret != ErrorCode::SUCCESS, ERR_DH_AVT_PREPARE_FAILED); + + SetCurrentState(StateId::CH_CREATED); + return DH_AVT_SUCCESS; +} + +int32_t AVReceiverEngine::Start() +{ + AVTRANS_LOGI("Start enter."); + + bool isErrState = (GetCurrentState() != StateId::CH_CREATED); + TRUE_RETURN_V_MSG_E(isErrState, ERR_DH_AVT_START_FAILED, "current state=%" PRId32 " is invalid.", + GetCurrentState()); + + ErrorCode ret = pipeline_->Start(); + TRUE_RETURN_V(ret != ErrorCode::SUCCESS, ERR_DH_AVT_START_FAILED); + SetCurrentState(StateId::STARTED); + return DH_AVT_SUCCESS; +} + +int32_t AVReceiverEngine::Stop() +{ + AVTRANS_LOGI("Stop enter."); + ErrorCode ret = pipeline_->Stop(); + TRUE_RETURN_V(ret != ErrorCode::SUCCESS, ERR_DH_AVT_STOP_FAILED); + SetCurrentState(StateId::STOPPED); + return DH_AVT_SUCCESS; +} + +int32_t AVReceiverEngine::Release() +{ + AVTRANS_LOGI("Release enter."); + TRUE_RETURN_V(GetCurrentState() == StateId::IDLE, DH_AVT_SUCCESS); + if (pipeline_ != nullptr) { + pipeline_->Stop(); + } + if (dhfwkKit_ != nullptr) { + dhfwkKit_->ReleaseAVCenter(engineId_); + } + SoftbusChannelAdapter::GetInstance().CloseSoftbusChannel(sessionName_, peerDevId_); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(sessionName_, peerDevId_); + initialized_ = false; + pipeline_ = nullptr; + dhfwkKit_ = nullptr; + avInput_ = nullptr; + avOutput_ = nullptr; + audioDecoder_ = nullptr; + videoDecoder_ = nullptr; + ctlCenCallback_ = nullptr; + SetCurrentState(StateId::IDLE); + return DH_AVT_SUCCESS; +} + +int32_t AVReceiverEngine::SetParameter(AVTransTag tag, const std::string &value) +{ + bool isFilterNull = (avInput_ == nullptr) || (avOutput_ == nullptr) || (pipeline_ == nullptr); + TRUE_RETURN_V_MSG_E(isFilterNull, ERR_DH_AVT_SETUP_FAILED, "filter or pipeline is null, set parameter failed."); + auto iter = funcMap_.find(tag); + if (iter == funcMap_.end()) { + AVTRANS_LOGE("AVTransTag %u is undefined.", tag); + return ERR_DH_AVT_INVALID_PARAM; + } + SetParaFunc &func = iter->second; + (this->*func)(value); + return DH_AVT_SUCCESS; +} + +void AVReceiverEngine::RegRespFunMap() +{ + funcMap_[AVTransTag::VIDEO_WIDTH] = &AVReceiverEngine::SetVideoWidth; + funcMap_[AVTransTag::VIDEO_HEIGHT] = &AVReceiverEngine::SetVideoHeight; + funcMap_[AVTransTag::VIDEO_FRAME_RATE] = &AVReceiverEngine::SetVideoFrameRate; + funcMap_[AVTransTag::AUDIO_BIT_RATE] = &AVReceiverEngine::SetAudioBitRate; + funcMap_[AVTransTag::VIDEO_BIT_RATE] = &AVReceiverEngine::SetVideoBitRate; + funcMap_[AVTransTag::VIDEO_CODEC_TYPE] = &AVReceiverEngine::SetVideoCodecType; + funcMap_[AVTransTag::AUDIO_CODEC_TYPE] = &AVReceiverEngine::SetAudioCodecType; + funcMap_[AVTransTag::AUDIO_CHANNEL_MASK] = &AVReceiverEngine::SetAudioChannelMask; + funcMap_[AVTransTag::AUDIO_SAMPLE_RATE] = &AVReceiverEngine::SetAudioSampleRate; + funcMap_[AVTransTag::AUDIO_CHANNEL_LAYOUT] = &AVReceiverEngine::SetAudioChannelLayout; + funcMap_[AVTransTag::AUDIO_SAMPLE_FORMAT] = &AVReceiverEngine::SetAudioSampleFormat; + funcMap_[AVTransTag::AUDIO_FRAME_SIZE] = &AVReceiverEngine::SetAudioFrameSize; + funcMap_[AVTransTag::TIME_SYNC_RESULT] = &AVReceiverEngine::SetSyncResult; + funcMap_[AVTransTag::START_AV_SYNC] = &AVReceiverEngine::SetStartAvSync; + funcMap_[AVTransTag::STOP_AV_SYNC] = &AVReceiverEngine::SetStopAvSync; + funcMap_[AVTransTag::SHARED_MEMORY_FD] = &AVReceiverEngine::SetSharedMemoryFd; + funcMap_[AVTransTag::ENGINE_READY] = &AVReceiverEngine::SetEngineReady; +} + +void AVReceiverEngine::SetVideoWidth(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_WIDTH), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter VIDEO_WIDTH success, video width = %s", value.c_str()); +} + +void AVReceiverEngine::SetVideoHeight(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_HEIGHT), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter VIDEO_HEIGHT success, video height = %s", value.c_str()); +} + +void AVReceiverEngine::SetVideoFrameRate(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_FRAME_RATE), std::atoi(value.c_str())); + avOutput_->SetParameter(static_cast(Plugin::Tag::VIDEO_FRAME_RATE), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter VIDEO_FRAME_RATE success, frame rate = %s", value.c_str()); +} + +void AVReceiverEngine::SetAudioBitRate(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::MEDIA_BITRATE), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter MEDIA_BITRATE success, bit rate = %s", value.c_str()); +} + +void AVReceiverEngine::SetVideoBitRate(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::MEDIA_BITRATE), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter MEDIA_BITRATE success, bit rate = %s", value.c_str()); +} + +void AVReceiverEngine::SetVideoCodecType(const std::string &value) +{ + if (value == MIME_VIDEO_H264) { + std::string mime = MEDIA_MIME_VIDEO_H264; + avInput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + mime = MEDIA_MIME_VIDEO_RAW; + avOutput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + AVTRANS_LOGI("SetParameter VIDEO_CODEC_TYPE = H264 success"); + } else if (value == MIME_VIDEO_H265) { + std::string mime = MEDIA_MIME_VIDEO_H265; + avInput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + mime = MEDIA_MIME_VIDEO_RAW; + avOutput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + AVTRANS_LOGI("SetParameter VIDEO_CODEC_TYPE = H265 success"); + } else { + AVTRANS_LOGE("SetParameter VIDEO_CODEC_TYPE failed, input value invalid."); + } +} + +void AVReceiverEngine::SetAudioCodecType(const std::string &value) +{ + std::string mime = MEDIA_MIME_AUDIO_AAC; + avInput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + mime = MEDIA_MIME_AUDIO_RAW; + avOutput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + AVTRANS_LOGI("SetParameter AUDIO_CODEC_TYPE = AAC success"); +} + +void AVReceiverEngine::SetAudioChannelMask(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_CHANNELS), std::atoi(value.c_str())); + avOutput_->SetParameter(static_cast(Plugin::Tag::AUDIO_CHANNELS), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_CHANNELS success, audio channels = %s", value.c_str()); +} + +void AVReceiverEngine::SetAudioSampleRate(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_SAMPLE_RATE), std::atoi(value.c_str())); + avOutput_->SetParameter(static_cast(Plugin::Tag::AUDIO_SAMPLE_RATE), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_SAMPLE_RATE success, audio sample rate = %s", value.c_str()); +} + +void AVReceiverEngine::SetAudioChannelLayout(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_CHANNEL_LAYOUT), std::atoi(value.c_str())); + avOutput_->SetParameter(static_cast(Plugin::Tag::AUDIO_CHANNEL_LAYOUT), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_CHANNEL_LAYOUT success, audio channel layout = %s", value.c_str()); +} + +void AVReceiverEngine::SetAudioSampleFormat(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_SAMPLE_FORMAT), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_SAMPLE_FORMAT success, audio sample format = %s", value.c_str()); +} + +void AVReceiverEngine::SetAudioFrameSize(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_SAMPLE_PER_FRAME), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_SAMPLE_PER_FRAME success, audio sample per frame = %s", value.c_str()); +} + +void AVReceiverEngine::SetSyncResult(const std::string &value) +{ + avOutput_->SetParameter(static_cast(Plugin::Tag::USER_TIME_SYNC_RESULT), value); + AVTRANS_LOGI("SetParameter USER_TIME_SYNC_RESULT success, time sync result = %s", value.c_str()); +} + +void AVReceiverEngine::SetStartAvSync(const std::string &value) +{ + avOutput_->SetParameter(static_cast(Plugin::Tag::USER_AV_SYNC_GROUP_INFO), value); + AVTRANS_LOGI("SetParameter START_AV_SYNC success."); +} + +void AVReceiverEngine::SetStopAvSync(const std::string &value) +{ + avOutput_->SetParameter(static_cast(Plugin::Tag::USER_AV_SYNC_GROUP_INFO), value); + AVTRANS_LOGI("SetParameter STOP_AV_SYNC success."); +} + +void AVReceiverEngine::SetSharedMemoryFd(const std::string &value) +{ + avOutput_->SetParameter(static_cast(Plugin::Tag::USER_SHARED_MEMORY_FD), value); + AVTRANS_LOGI("SetParameter USER_SHARED_MEMORY_FD success, shared memory info = %s", value.c_str()); +} + +void AVReceiverEngine::SetEngineReady(const std::string &value) +{ + int32_t ret = PreparePipeline(value); + TRUE_LOG_MSG(ret != DH_AVT_SUCCESS, "SetParameter ENGINE_READY failed"); +} + +int32_t AVReceiverEngine::SendMessage(const std::shared_ptr &message) +{ + TRUE_RETURN_V_MSG_E(message == nullptr, ERR_DH_AVT_INVALID_PARAM, "input message is nullptr."); + std::string msgData = message->MarshalMessage(); + return SoftbusChannelAdapter::GetInstance().SendBytesData(sessionName_, message->dstDevId_, msgData); +} + +int32_t AVReceiverEngine::RegisterReceiverCallback(const std::shared_ptr &callback) +{ + AVTRANS_LOGI("RegisterReceiverCallback enter."); + if (callback == nullptr) { + AVTRANS_LOGE("RegisterReceiverCallback failed, receiver engine callback is nullptr."); + return ERR_DH_AVT_INVALID_PARAM; + } + receiverCallback_ = callback; + return DH_AVT_SUCCESS; +} + +int32_t AVReceiverEngine::HandleOutputBuffer(std::shared_ptr &hisBuffer) +{ + StateId currentState = GetCurrentState(); + bool isErrState = (currentState != StateId::STARTED) && (currentState != StateId::PLAYING); + TRUE_RETURN_V_MSG_E(isErrState, ERR_DH_AVT_OUTPUT_DATA_FAILED, + "current state=%" PRId32 " is invalid.", currentState); + + std::shared_ptr transBuffer = HiSBuffer2TransBuffer(hisBuffer); + TRUE_RETURN_V(transBuffer == nullptr, ERR_DH_AVT_OUTPUT_DATA_FAILED); + + SetCurrentState(StateId::PLAYING); + TRUE_RETURN_V(receiverCallback_ == nullptr, ERR_DH_AVT_OUTPUT_DATA_FAILED); + return receiverCallback_->OnDataAvailable(transBuffer); +} + +void AVReceiverEngine::OnChannelEvent(const AVTransEvent &event) +{ + AVTRANS_LOGI("OnChannelEvent enter. event type:%" PRId32, event.type); + TRUE_RETURN(receiverCallback_ == nullptr, "receiver callback is nullptr."); + + switch (event.type) { + case EventType::EVENT_CHANNEL_OPENED: { + SetCurrentState(StateId::CH_CREATED); + receiverCallback_->OnReceiverEvent(event); + break; + } + case EventType::EVENT_CHANNEL_OPEN_FAIL: { + SetCurrentState(StateId::INITIALIZED); + receiverCallback_->OnReceiverEvent(event); + break; + } + case EventType::EVENT_CHANNEL_CLOSED: { + StateId currentState = GetCurrentState(); + if ((currentState != StateId::IDLE) && (currentState != StateId::INITIALIZED)) { + SetCurrentState(StateId::INITIALIZED); + receiverCallback_->OnReceiverEvent(event); + } + break; + } + case EventType::EVENT_DATA_RECEIVED: { + auto avMessage = std::make_shared(); + TRUE_RETURN(!avMessage->UnmarshalMessage(event.content, event.peerDevId), "unmarshal message failed"); + receiverCallback_->OnMessageReceived(avMessage); + break; + } + default: + AVTRANS_LOGE("Invalid event type."); + } +} + +void AVReceiverEngine::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + (void)data; + (void)ext; +} + +void AVReceiverEngine::OnEvent(const OHOS::Media::Event &event) +{ + AVTRANS_LOGI("OnEvent enter. event type:%s", GetEventName(event.type)); + TRUE_RETURN(receiverCallback_ == nullptr, "receiver callback is nullptr."); + + switch (event.type) { + case OHOS::Media::EventType::EVENT_BUFFER_PROGRESS: { + if (event.param.SameTypeWith(typeid(std::shared_ptr))) { + auto hisBuffer = Plugin::AnyCast>(event.param); + TRUE_RETURN(hisBuffer == nullptr, "hisBuffer is null"); + HandleOutputBuffer(hisBuffer); + } + break; + } + case OHOS::Media::EventType::EVENT_PLUGIN_EVENT: { + Plugin::PluginEvent plugEvt = Plugin::AnyCast(event.param); + bool isPlaying = (GetCurrentState() == StateId::PLAYING); + receiverCallback_->OnReceiverEvent(AVTransEvent{CastEventType(plugEvt.type, isPlaying), "", peerDevId_}); + break; + } + default: + AVTRANS_LOGE("Invalid event type."); + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_receiver/src/av_receiver_engine_provider.cpp b/av_transport/av_trans_engine/av_receiver/src/av_receiver_engine_provider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb9ee6141b6b532dcc169f43a1dad460c5651cb4 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/src/av_receiver_engine_provider.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_receiver_engine_provider.h" + +#include "av_receiver_engine.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVReceiverEngineProvider" + +AVReceiverEngineProvider::AVReceiverEngineProvider(const std::string &ownerName) : ownerName_(ownerName) +{ + AVTRANS_LOGI("AVReceiverEngineProvider ctor."); + sessionName_ = ownerName + "_" + RECEIVER_CONTROL_SESSION_NAME_SUFFIX; + SoftbusChannelAdapter::GetInstance().CreateChannelServer(TransName2PkgName(ownerName), sessionName_); + SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, AV_TRANS_SPECIAL_DEVICE_ID, this); +} + +AVReceiverEngineProvider::~AVReceiverEngineProvider() +{ + AVTRANS_LOGI("AVReceiverEngineProvider dctor."); + { + std::lock_guard lock(listMutex_); + for (auto &receiver : receiverEngineList_) { + receiver->Release(); + } + } + SoftbusChannelAdapter::GetInstance().RemoveChannelServer(TransName2PkgName(ownerName_), sessionName_); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(sessionName_, AV_TRANS_SPECIAL_DEVICE_ID); + ownerName_ = ""; + sessionName_ = ""; + receiverEngineList_.clear(); + providerCallback_ = nullptr; +} + +std::shared_ptr AVReceiverEngineProvider::CreateAVReceiverEngine(const std::string &peerDevId) +{ + AVTRANS_LOGI("CreateAVReceiverEngine enter."); + auto receiver = std::make_shared(ownerName_, peerDevId); + if (receiver && receiver->Initialize() == DH_AVT_SUCCESS) { + { + std::lock_guard lock(listMutex_); + receiverEngineList_.push_back(receiver); + } + return receiver; + } + AVTRANS_LOGE("create receiver failed or receiver init failed."); + return nullptr; +} + +std::vector> AVReceiverEngineProvider::GetAVReceiverEngineList() +{ + std::lock_guard lock(listMutex_); + return receiverEngineList_; +} + +int32_t AVReceiverEngineProvider::RegisterProviderCallback( + const std::shared_ptr &callback) +{ + providerCallback_ = callback; + return DH_AVT_SUCCESS; +} + +void AVReceiverEngineProvider::OnChannelEvent(const AVTransEvent &event) +{ + if (providerCallback_ == nullptr) { + return; + } + if ((event.type == EventType::EVENT_CHANNEL_OPENED) || (event.type == EventType::EVENT_CHANNEL_CLOSED)) { + AVTRANS_LOGI("on receiver channel event. event type:%" PRId32, event.type); + providerCallback_->OnProviderEvent(event); + } +} + +void AVReceiverEngineProvider::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + (void)data; + (void)ext; +} +} // namespace DistributedHardware +} // namespace OHOS + +extern "C" __attribute__((visibility("default"))) + OHOS::DistributedHardware::IAVEngineProvider* GetAVReceiverEngineProvider(const std::string ownerName) +{ + return new (std::nothrow) OHOS::DistributedHardware::AVReceiverEngineProvider(ownerName); +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_receiver/test/unittest/BUILD.gn b/av_transport/av_trans_engine/av_receiver/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ac240885fb67b8c1aa13239ce308282884b8aaf7 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/test/unittest/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +group("receiver_test") { + testonly = true + + deps = [ + "av_receiver_engine:av_receiver_engine_test", + "av_receiver_engine_provider:av_receiver_engine_provider_test", + ] +} diff --git a/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/BUILD.gn b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ac59d6679684311586ddf2c7371c64d14fb2e6e3 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/BUILD.gn @@ -0,0 +1,95 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/av_receiver_engine_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${dh_fwk_utils_path}/include", + "${common_path}/include", + "${dh_fwk_sdk_path}/include", + "${engine_path}/av_receiver/include", + "${control_center_path}/inner_kits/include", + "${control_center_path}/inner_kits/include/ipc", + "${filters_path}/av_transport_input", + "${filters_path}/av_transport_output", + "${engine_path}/av_receiver/test/unittest/av_receiver_engine/include", + "${interface_path}", + "${media_standard_path}/interfaces/inner_api/native", + ] +} + +ohos_unittest("AvReceiverEngineTest") { + module_out_path = module_out_path + + sources = [ "src/av_receiver_engine_test.cpp" ] + + configs = [ ":module_private_config" ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + "-Dprotected = public", + ] + cflags_cc = cflags + + deps = [ + "${dh_fwk_sdk_path}:libdhfwk_sdk", + "${engine_path}/av_receiver:distributed_av_receiver", + "${filters_path}:avtrans_input_filter", + "${filters_path}:avtrans_output_filter", + "//third_party/googletest:gtest_rtti", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"AvReceiverEngineTest\"", + "LOG_DOMAIN=0xD004100", + ] + + defines += [ + "MEDIA_OHOS", + "RECORDER_SUPPORT", + "VIDEO_SUPPORT", + ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "graphic_2d:libgraphic_utils", + "graphic_2d:surface", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("av_receiver_engine_test") { + testonly = true + deps = [ ":AvReceiverEngineTest" ] +} diff --git a/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/include/av_receiver_engine_test.h b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/include/av_receiver_engine_test.h new file mode 100644 index 0000000000000000000000000000000000000000..e3e118bc1b4053dd97468715024ebafb3b58057d --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/include/av_receiver_engine_test.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AV_TRANSPORT_INPUT_FILTER_TEST_H +#define AV_TRANSPORT_INPUT_FILTER_TEST_H + +#include + +#include "av_receiver_engine.h" +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_message.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "i_av_receiver_engine.h" +#include "softbus_channel_adapter.h" +#include "distributed_hardware_fwk_kit.h" +#include "av_trans_control_center_callback.h" +#include "av_transport_input_filter.h" +#include "av_transport_output_filter.h" + +// follwing head files depends on histreamer +#include "error_code.h" +#include "event.h" +#include "pipeline/core/filter.h" +#include "pipeline_core.h" +#include "audio_encoder_filter.h" +#include "video_encoder_filter.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +using namespace OHOS::Media::Pipeline; +using AVBuffer = OHOS::Media::Plugin::Buffer; + +class AvReceiverEngineTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // AV_TRANSPORT_INPUT_FILTER_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/src/av_receiver_engine_test.cpp b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/src/av_receiver_engine_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19738955c00505f906e18652f48dacb40d5dce68 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine/src/av_receiver_engine_test.cpp @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_receiver_engine_test.h" + +#include "pipeline/factory/filter_factory.h" +#include "plugin_video_tags.h" + +using namespace testing::ext; +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace DistributedHardware { +const std::string FILTERNAME = "avreceivererengine"; + +void AvReceiverEngineTest::SetUp() +{ +} + +void AvReceiverEngineTest::TearDown() +{ +} + +void AvReceiverEngineTest::SetUpTestCase() +{ +} + +void AvReceiverEngineTest::TearDownTestCase() +{ +} + +HWTEST_F(AvReceiverEngineTest, Initialize_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->initialized_ = true; + int32_t ret = receiver->Initialize(); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +HWTEST_F(AvReceiverEngineTest, Initialize_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->avInput_ = nullptr; + int32_t ret = receiver->Initialize(); + EXPECT_EQ(ERR_DH_AVT_INIT_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, Initialize_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->sessionName_ = ""; + int32_t ret = receiver->Initialize(); + EXPECT_EQ(ERR_DH_AVT_INIT_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, CreateControlChannel_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + std::vector dstDevIds; + int32_t ret = receiver->CreateControlChannel(dstDevIds, ChannelAttribute{TransStrategy::LOW_LATANCY_STRATEGY}); + EXPECT_EQ(ERR_DH_AVT_NULL_POINTER, ret); +} + +HWTEST_F(AvReceiverEngineTest, CreateControlChannel_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + std::vector dstDevIds = {peerDevId}; + int32_t ret = receiver->CreateControlChannel(dstDevIds, ChannelAttribute{TransStrategy::LOW_LATANCY_STRATEGY}); + EXPECT_EQ(ERR_DH_AVT_CREATE_CHANNEL_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, CreateControlChannel_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + std::vector dstDevIds = {peerDevId}; + int32_t ret = receiver->CreateControlChannel(dstDevIds, ChannelAttribute{TransStrategy::LOW_LATANCY_STRATEGY}); + EXPECT_EQ(ERR_DH_AVT_CREATE_CHANNEL_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, Start_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->currentState_ = StateId::IDLE; + receiver->pipeline_ = std::make_shared(); + int32_t ret = receiver->Start(); + EXPECT_EQ(ERR_DH_AVT_START_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, Start_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->currentState_ = StateId::CH_CREATED; + receiver->pipeline_ = std::make_shared(); + int32_t ret = receiver->Start(); + receiver->Stop(); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +HWTEST_F(AvReceiverEngineTest, Stop_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->currentState_ = StateId::CH_CREATED; + receiver->pipeline_ = std::make_shared(); + receiver->Start(); + int32_t ret = receiver->Stop(); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +HWTEST_F(AvReceiverEngineTest, SetParameter_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto receiver = std::make_shared(ownerName, peerDevId); + int32_t ret = receiver->SetParameter(AVTransTag::INVALID, value); + EXPECT_EQ(ERR_DH_AVT_SETUP_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, SetParameter_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + int32_t ret = receiver->SetParameter(AVTransTag::INVALID, value); + EXPECT_EQ(ERR_DH_AVT_SETUP_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, SetParameter_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + receiver->avOutput_ = FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, "avoutput"); + int32_t ret = receiver->SetParameter(AVTransTag::INVALID, value); + EXPECT_EQ(ERR_DH_AVT_SETUP_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, SetParameter_004, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "123"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + receiver->avOutput_ = FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, "avoutput"); + + std::shared_ptr pipeline_ = nullptr; + receiver->pipeline_ = std::make_shared(); + int32_t ret = receiver->SetParameter(AVTransTag::VIDEO_WIDTH, value); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM, ret); +} + +HWTEST_F(AvReceiverEngineTest, PreparePipeline_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->currentState_ = StateId::STARTED; + int32_t ret = receiver->PreparePipeline(configParam); + EXPECT_EQ(ERR_DH_AVT_PREPARE_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, PreparePipeline_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->currentState_ = StateId::INITIALIZED; + int32_t ret = receiver->PreparePipeline(configParam); + EXPECT_EQ(ERR_DH_AVT_PREPARE_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, PreparePipeline_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->currentState_ = StateId::INITIALIZED; + receiver->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + int32_t ret = receiver->PreparePipeline(configParam); + EXPECT_EQ(ERR_DH_AVT_PREPARE_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, PreparePipeline_004, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto receiver = std::make_shared(ownerName, peerDevId); + receiver->currentState_ = StateId::INITIALIZED; + std::shared_ptr avOutput_ = nullptr; + avOutput_ = FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, "avoutput"); + int32_t ret = receiver->PreparePipeline(configParam); + EXPECT_EQ(ERR_DH_AVT_PREPARE_FAILED, ret); +} + +HWTEST_F(AvReceiverEngineTest, SendMessage_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto receiver = std::make_shared(ownerName, peerDevId); + int32_t ret = receiver->SendMessage(nullptr); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/BUILD.gn b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b601242224330357ce3501eae21d742ef67f8790 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/BUILD.gn @@ -0,0 +1,95 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/av_receiver_engine_provider_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${dh_fwk_utils_path}/include", + "${common_path}/include", + "${dh_fwk_sdk_path}/include", + "${engine_path}/av_receiver/include", + "${control_center_path}/inner_kits/include", + "${control_center_path}/inner_kits/include/ipc", + "${filters_path}/av_transport_input", + "${filters_path}/av_transport_output", + "${engine_path}/av_receiver/test/unittest/av_receiver_engine_provider/include", + "${interface_path}", + "${media_standard_path}/interfaces/inner_api/native", + ] +} + +ohos_unittest("AvReceiverEngineProviderTest") { + module_out_path = module_out_path + + sources = [ "src/av_receiver_engine_provider_test.cpp" ] + + configs = [ ":module_private_config" ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + "-Dprotected = public", + ] + cflags_cc = cflags + + deps = [ + "${dh_fwk_sdk_path}:libdhfwk_sdk", + "${engine_path}/av_receiver:distributed_av_receiver", + "${filters_path}:avtrans_input_filter", + "${filters_path}:avtrans_output_filter", + "//third_party/googletest:gtest_rtti", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"AvReceiverEngineProviderTest\"", + "LOG_DOMAIN=0xD004100", + ] + + defines += [ + "MEDIA_OHOS", + "RECORDER_SUPPORT", + "VIDEO_SUPPORT", + ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "graphic_2d:libgraphic_utils", + "graphic_2d:surface", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("av_receiver_engine_provider_test") { + testonly = true + deps = [ ":AvReceiverEngineProviderTest" ] +} diff --git a/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/include/av_receiver_engine_provider_test.h b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/include/av_receiver_engine_provider_test.h new file mode 100644 index 0000000000000000000000000000000000000000..e2d06bef605b71af7afae03bc220e1bab44f36d3 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/include/av_receiver_engine_provider_test.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AV_TRANSPORT_INPUT_FILTER_TEST_H +#define AV_TRANSPORT_INPUT_FILTER_TEST_H + +#include + +#include "av_receiver_engine_provider.h" +#include "i_av_engine_provider.h" +#include "softbus_channel_adapter.h" + + +namespace OHOS { +namespace DistributedHardware { + + +class AvReceiverEngineProviderTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // AV_TRANSPORT_INPUT_FILTER_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/src/av_receiver_engine_provider_test.cpp b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/src/av_receiver_engine_provider_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f00c163c211872ca03e1a7d79b2bd93ecbdd748 --- /dev/null +++ b/av_transport/av_trans_engine/av_receiver/test/unittest/av_receiver_engine_provider/src/av_receiver_engine_provider_test.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_receiver_engine_provider_test.h" + +#include "av_receiver_engine.h" + +using namespace testing::ext; +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace DistributedHardware { + +void AvReceiverEngineProviderTest::SetUp() +{ +} + +void AvReceiverEngineProviderTest::TearDown() +{ +} + +void AvReceiverEngineProviderTest::SetUpTestCase() +{ +} + +void AvReceiverEngineProviderTest::TearDownTestCase() +{ +} + +HWTEST_F(AvReceiverEngineProviderTest, CreateAVReceiverEngine_001, testing::ext::TestSize.Level1) +{ + std::string peerDevId = "peerDevId"; + std::string ownerName = "ownerName"; + auto avReceiveProTest_ = std::make_shared(ownerName); + auto avReceiverEngine = avReceiveProTest_->CreateAVReceiverEngine(peerDevId); + EXPECT_EQ(nullptr, avReceiverEngine); +} + +HWTEST_F(AvReceiverEngineProviderTest, GetAVReceiverEngineList_001, testing::ext::TestSize.Level1) +{ + std::string peerDevId = "peerDevId"; + std::string ownerName = "ownerName"; + auto avReceiveProTest_ = std::make_shared(ownerName); + auto avReceiverEngine = avReceiveProTest_->CreateAVReceiverEngine(peerDevId); + std::vector> receiverEngineList = avReceiveProTest_->GetAVReceiverEngineList(); + bool bRet = (receiverEngineList.empty()) ? false : true; + EXPECT_NE(true, bRet); +} + +HWTEST_F(AvReceiverEngineProviderTest, GetAVReceiverEngineList_002, testing::ext::TestSize.Level1) +{ + std::string peerDevId = "peerDevId"; + std::string ownerName = "ownerName"; + auto avReceiveProTest_ = std::make_shared(ownerName); + auto avReceiverEngine = avReceiveProTest_->CreateAVReceiverEngine(peerDevId); + auto receiver = std::make_shared(ownerName, peerDevId); + avReceiveProTest_->receiverEngineList_.push_back(receiver); + std::vector> receiverEngineList = avReceiveProTest_->GetAVReceiverEngineList(); + bool bRet = (receiverEngineList.empty()) ? false : true; + EXPECT_EQ(true, bRet); +} + +HWTEST_F(AvReceiverEngineProviderTest, RegisterProviderCallback_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "ownerName"; + auto avReceiveProTest_ = std::make_shared(ownerName); + std::shared_ptr callback = nullptr; + int32_t ret = avReceiveProTest_->RegisterProviderCallback(callback); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_sender/BUILD.gn b/av_transport/av_trans_engine/av_sender/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e817cd6eab9fa92868e291bd831a3cb1aec9eb94 --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/BUILD.gn @@ -0,0 +1,106 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +config("sender_external_config") { + include_dirs = [ + "${common_path}/include", + "${dh_fwk_sdk_path}/include", + "${engine_path}/av_sender/include", + "${engine_path}/av_receiver/include", + "${interface_path}", + ] +} + +ohos_shared_library("distributed_av_sender") { + public_configs = [ ":sender_external_config" ] + + include_dirs = [ + "${drivers_disaplay_path}/interfaces/include", + "${media_standard_path}/interfaces/inner_api/native", + "//third_party/json/include", + + "${dh_fwk_utils_path}/include", + "${control_center_path}/inner_kits/include", + "${control_center_path}/inner_kits/include/ipc", + "${filters_path}/av_transport_input", + "${filters_path}/av_transport_output", + ] + + sources = [ + "${common_path}/src/av_sync_utils.cpp", + "${common_path}/src/av_trans_buffer.cpp", + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_message.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "${common_path}/src/softbus_channel_adapter.cpp", + "${engine_path}/av_sender/src/av_sender_engine.cpp", + "${engine_path}/av_sender/src/av_sender_engine_provider.cpp", + ] + + deps = [ + "${dh_fwk_sdk_path}:libdhfwk_sdk", + "${filters_path}:avtrans_input_filter", + "${filters_path}:avtrans_output_filter", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"av_trans_sender\"", + "LOG_DOMAIN=0xD004100", + ] + + defines += [ + "MEDIA_OHOS", + "RECORDER_SUPPORT", + "VIDEO_SUPPORT", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "graphic_2d:libgraphic_utils", + "graphic_2d:surface", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + remove_configs = [ + "//build/config/compiler:no_rtti", + "//build/config/compiler:no_exceptions", + ] + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + ] + cflags_cc = cflags + + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/av_sender/include/av_sender_engine.h b/av_transport/av_trans_engine/av_sender/include/av_sender_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..be806b877286d574bc953ec33d72600afce6eec1 --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/include/av_sender_engine.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_SENDER_ENGINE_H +#define OHOS_AV_SENDER_ENGINE_H + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_message.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "i_av_sender_engine.h" +#include "softbus_channel_adapter.h" +#include "distributed_hardware_fwk_kit.h" +#include "av_trans_control_center_callback.h" +#include "av_transport_input_filter.h" +#include "av_transport_output_filter.h" + +// follwing head files depends on histreamer +#include "error_code.h" +#include "event.h" +#include "pipeline/core/filter.h" +#include "pipeline_core.h" +#include "audio_encoder_filter.h" +#include "video_encoder_filter.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +using namespace OHOS::Media::Pipeline; +using AVBuffer = OHOS::Media::Plugin::Buffer; + +class AVSenderEngine : public IAVSenderEngine, + public ISoftbusChannelListener, + public OHOS::Media::Pipeline::EventReceiver, + public std::enable_shared_from_this { +public: + AVSenderEngine(const std::string &ownerName, const std::string &peerDevId); + ~AVSenderEngine() override; + AVSenderEngine(const AVSenderEngine &other) = delete; + AVSenderEngine& operator=(const AVSenderEngine &other) = delete; + + // interfaces from IAVSenderEngine + int32_t Initialize() override; + int32_t Start() override; + int32_t Stop() override; + int32_t Release() override; + int32_t SetParameter(AVTransTag tag, const std::string &value) override; + int32_t PushData(const std::shared_ptr &buffer) override; + int32_t SendMessage(const std::shared_ptr &message) override; + int32_t CreateControlChannel(const std::vector &dstDevIds, + const ChannelAttribute &attribution) override; + int32_t RegisterSenderCallback(const std::shared_ptr &callback) override; + + // interfaces from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + + // interfaces from OHOS::Media::Pipeline::EventReceiver + void OnEvent(const OHOS::Media::Event &event) override; + +private: + int32_t InitPipeline(); + int32_t InitControlCenter(); + int32_t PreparePipeline(const std::string &configParam); + void NotifyStreamChange(EventType type); + + void RegRespFunMap(); + void SetVideoWidth(const std::string &value); + void SetVideoHeight(const std::string &value); + void SetVideoPixelFormat(const std::string &value); + void SetVideoFrameRate(const std::string &value); + void SetAudioBitRate(const std::string &value); + void SetVideoBitRate(const std::string &value); + void SetVideoCodecType(const std::string &value); + void SetAudioCodecType(const std::string &value); + void SetAudioChannelMask(const std::string &value); + void SetAudioSampleRate(const std::string &value); + void SetAudioChannelLayout(const std::string &value); + void SetAudioSampleFormat(const std::string &value); + void SetAudioFrameSize(const std::string &value); + void SetSharedMemoryFd(const std::string &value); + void SetEngineReady(const std::string &value); + void SetEnginePause(const std::string &value); + void SetEngineResume(const std::string &value); + + StateId GetCurrentState() + { + std::lock_guard lock(stateMutex_); + return currentState_; + } + + void SetCurrentState(StateId stateId) + { + std::lock_guard lock(stateMutex_); + currentState_ = stateId; + } + +private: + int32_t engineId_ = 0; + std::string ownerName_; + std::string sessionName_; + std::string peerDevId_; + + std::mutex stateMutex_; + std::atomic initialized_ {false}; + std::atomic currentState_ = StateId::IDLE; + + sptr ctlCenCallback_ = nullptr; + std::shared_ptr dhfwkKit_ = nullptr; + std::shared_ptr senderCallback_ = nullptr; + std::shared_ptr pipeline_ = nullptr; + + std::shared_ptr avInput_ = nullptr; + std::shared_ptr avOutput_ = nullptr; + std::shared_ptr audioEncoder_ = nullptr; + std::shared_ptr videoEncoder_ = nullptr; + + using SetParaFunc = void (AVSenderEngine::*)(const std::string &value); + std::map funcMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_SENDER_ENGINE_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_sender/include/av_sender_engine_provider.h b/av_transport/av_trans_engine/av_sender/include/av_sender_engine_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..0a2a476170a01cb60ab0f08cba6864cf874d771c --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/include/av_sender_engine_provider.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_SENDER_ENGINE_PROVIDER_H +#define OHOS_AV_SENDER_ENGINE_PROVIDER_H + +#include + +#include "i_av_engine_provider.h" +#include "softbus_channel_adapter.h" + +namespace OHOS { +namespace DistributedHardware { +class AVSenderEngineProvider : public IAVEngineProvider, public ISoftbusChannelListener { +public: + AVSenderEngineProvider(const std::string ownerName); + ~AVSenderEngineProvider() override; + + std::shared_ptr CreateAVSenderEngine(const std::string &peerDevId) override; + std::vector> GetAVSenderEngineList() override; + int32_t RegisterProviderCallback(const std::shared_ptr &callback) override; + + // interfaces from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + +private: + std::string ownerName_; + std::string sessionName_; + std::mutex listMutex_; + std::shared_ptr providerCallback_; + std::vector> senderEngineList_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_SENDER_ENGINE_PROVIDER_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_sender/src/av_sender_engine.cpp b/av_transport/av_trans_engine/av_sender/src/av_sender_engine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8d57abb38c941c8b5d7d01a4fd52be74888119f --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/src/av_sender_engine.cpp @@ -0,0 +1,545 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_sender_engine.h" + +#include "pipeline/factory/filter_factory.h" +#include "plugin_video_tags.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVSenderEngine" + +AVSenderEngine::AVSenderEngine(const std::string &ownerName, const std::string &peerDevId) + : ownerName_(ownerName), peerDevId_(peerDevId) +{ + AVTRANS_LOGI("AVSenderEngine ctor."); + sessionName_ = ownerName_ + "_" + SENDER_CONTROL_SESSION_NAME_SUFFIX; +} + +AVSenderEngine::~AVSenderEngine() +{ + AVTRANS_LOGI("AVSenderEngine dctor."); + Release(); + + dhfwkKit_ = nullptr; + pipeline_ = nullptr; + avInput_ = nullptr; + avOutput_ = nullptr; + audioEncoder_ = nullptr; + videoEncoder_ = nullptr; + senderCallback_ = nullptr; + ctlCenCallback_ = nullptr; +} + +int32_t AVSenderEngine::Initialize() +{ + TRUE_RETURN_V_MSG_E(initialized_.load(), DH_AVT_SUCCESS, "sender engine has been initialized"); + + int32_t ret = InitPipeline(); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_INIT_FAILED, "init pipeline failed"); + + ret = InitControlCenter(); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_INIT_FAILED, "init av control center failed"); + + ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, peerDevId_, this); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_INIT_FAILED, "register sender channel callback failed"); + RegRespFunMap(); + initialized_ = true; + SetCurrentState(StateId::INITIALIZED); + return DH_AVT_SUCCESS; +} + +int32_t AVSenderEngine::InitPipeline() +{ + AVTRANS_LOGI("InitPipeline enter."); + FilterFactory::Instance().Init(); + avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + TRUE_RETURN_V_MSG_E(avInput_ == nullptr, ERR_DH_AVT_NULL_POINTER, "create av input filter failed"); + + avOutput_ = FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, "avoutput"); + TRUE_RETURN_V_MSG_E(avOutput_ == nullptr, ERR_DH_AVT_NULL_POINTER, "create av output filter failed"); + + videoEncoder_ = FilterFactory::Instance().CreateFilterWithType(VENCODER_NAME, "videoencoder"); + TRUE_RETURN_V_MSG_E(videoEncoder_ == nullptr, ERR_DH_AVT_NULL_POINTER, "create av video encoder filter failed"); + + audioEncoder_ = FilterFactory::Instance().CreateFilterWithType(AENCODER_NAME, "audioencoder"); + TRUE_RETURN_V_MSG_E(audioEncoder_ == nullptr, ERR_DH_AVT_NULL_POINTER, "create av audio encoder filter failed"); + + ErrorCode ret; + pipeline_ = std::make_shared(); + pipeline_->Init(this, nullptr); + if ((ownerName_ == OWNER_NAME_D_SCREEN) || (ownerName_ == OWNER_NAME_D_CAMERA)) { + ret = pipeline_->AddFilters({avInput_.get(), videoEncoder_.get(), avOutput_.get()}); + if (ret == ErrorCode::SUCCESS) { + ret = pipeline_->LinkFilters({avInput_.get(), videoEncoder_.get(), avOutput_.get()}); + } + } else if ((ownerName_ == OWNER_NAME_D_MIC) || (ownerName_ == OWNER_NAME_D_SPEAKER)) { + ret = pipeline_->AddFilters({avInput_.get(), avOutput_.get()}); + if (ret == ErrorCode::SUCCESS) { + ret = pipeline_->LinkFilters({avInput_.get(), avOutput_.get()}); + } + } else { + AVTRANS_LOGI("unsupport ownerName:%s", ownerName_.c_str()); + return ERR_DH_AVT_INVALID_PARAM_VALUE; + } + if (ret != ErrorCode::SUCCESS) { + pipeline_->RemoveFilterChain(avInput_.get()); + } + return (ret == ErrorCode::SUCCESS) ? DH_AVT_SUCCESS : ERR_DH_AVT_INVALID_OPERATION; +} + +int32_t AVSenderEngine::InitControlCenter() +{ + dhfwkKit_ = std::make_shared(); + int32_t ret = dhfwkKit_->InitializeAVCenter(TransRole::AV_SENDER, engineId_); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_CTRL_CENTER_INIT_FAIL, "init av trans control center failed"); + + ctlCenCallback_ = new (std::nothrow) AVTransControlCenterCallback(); + TRUE_RETURN_V_MSG_E(ctlCenCallback_ == nullptr, ERR_DH_AVT_REGISTER_CALLBACK_FAIL, + "new control center callback failed"); + + std::shared_ptr engine = std::shared_ptr(shared_from_this()); + ctlCenCallback_->SetSenderEngine(engine); + + ret = dhfwkKit_->RegisterCtlCenterCallback(engineId_, ctlCenCallback_); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_REGISTER_CALLBACK_FAIL, + "register control center callback failed"); + + return DH_AVT_SUCCESS; +} + +int32_t AVSenderEngine::CreateControlChannel(const std::vector &dstDevIds, + const ChannelAttribute &attribution) +{ + (void)attribution; + AVTRANS_LOGI("CreateControlChannel enter."); + TRUE_RETURN_V_MSG_E(dstDevIds.empty(), ERR_DH_AVT_NULL_POINTER, "dst deviceId vector is empty"); + + peerDevId_ = dstDevIds[0]; + int32_t ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, peerDevId_, this); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_CREATE_CHANNEL_FAILED, + "register control channel callback failed"); + + std::string peerSessName = ownerName_ + "_" + RECEIVER_CONTROL_SESSION_NAME_SUFFIX; + ret = SoftbusChannelAdapter::GetInstance().OpenSoftbusChannel(sessionName_, peerSessName, peerDevId_); + TRUE_RETURN_V(ret == ERR_DH_AVT_SESSION_HAS_OPENED, ERR_DH_AVT_CHANNEL_ALREADY_CREATED); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_CREATE_CHANNEL_FAILED, + "create control channel failed"); + + SetCurrentState(StateId::CH_CREATING); + return DH_AVT_SUCCESS; +} + +int32_t AVSenderEngine::Start() +{ + AVTRANS_LOGI("Start sender engine enter."); + + bool isErrState = (GetCurrentState() != StateId::CH_CREATED); + TRUE_RETURN_V_MSG_E(isErrState, ERR_DH_AVT_START_FAILED, "current state=%" PRId32 " is invalid.", + GetCurrentState()); + + ErrorCode errCode = pipeline_->Start(); + TRUE_RETURN_V_MSG_E(errCode != ErrorCode::SUCCESS, ERR_DH_AVT_START_FAILED, "start pipeline failed"); + + if (dhfwkKit_ != nullptr) { + int32_t ret = dhfwkKit_->CreateControlChannel(engineId_, peerDevId_); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_CREATE_CHANNEL_FAILED, + "create av control center channel failed"); + } + + SetCurrentState(StateId::STARTED); + AVTRANS_LOGI("Start sender engine success."); + return DH_AVT_SUCCESS; +} + +int32_t AVSenderEngine::Stop() +{ + AVTRANS_LOGI("Stop sender engine enter."); + ErrorCode ret = pipeline_->Stop(); + TRUE_RETURN_V_MSG_E(ret != ErrorCode::SUCCESS, ERR_DH_AVT_STOP_FAILED, "stop pipeline failed"); + SetCurrentState(StateId::STOPPED); + NotifyStreamChange(EventType::EVENT_REMOVE_STREAM); + AVTRANS_LOGI("Stop sender engine success."); + return DH_AVT_SUCCESS; +} + +int32_t AVSenderEngine::Release() +{ + AVTRANS_LOGI("Release sender engine enter."); + if (pipeline_ != nullptr) { + pipeline_->Stop(); + } + if (dhfwkKit_ != nullptr) { + dhfwkKit_->ReleaseAVCenter(engineId_); + } + SoftbusChannelAdapter::GetInstance().CloseSoftbusChannel(sessionName_, peerDevId_); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(sessionName_, peerDevId_); + initialized_ = false; + pipeline_ = nullptr; + dhfwkKit_ = nullptr; + avInput_ = nullptr; + avOutput_ = nullptr; + audioEncoder_ = nullptr; + videoEncoder_ = nullptr; + senderCallback_ = nullptr; + ctlCenCallback_ = nullptr; + SetCurrentState(StateId::IDLE); + return DH_AVT_SUCCESS; +} + +int32_t AVSenderEngine::SetParameter(AVTransTag tag, const std::string &value) +{ + bool isFilterNull = (avInput_ == nullptr) || (avOutput_ == nullptr) || (pipeline_ == nullptr); + TRUE_RETURN_V_MSG_E(isFilterNull, ERR_DH_AVT_SETUP_FAILED, "filter or pipeline is null, set parameter failed."); + auto iter = funcMap_.find(tag); + if (iter == funcMap_.end()) { + AVTRANS_LOGE("AVTransTag %u is undefined.", tag); + return ERR_DH_AVT_INVALID_PARAM; + } + SetParaFunc &func = iter->second; + (this->*func)(value); + return DH_AVT_SUCCESS; +} + +void AVSenderEngine::RegRespFunMap() +{ + funcMap_[AVTransTag::VIDEO_WIDTH] = &AVSenderEngine::SetVideoWidth; + funcMap_[AVTransTag::VIDEO_HEIGHT] = &AVSenderEngine::SetVideoHeight; + funcMap_[AVTransTag::VIDEO_PIXEL_FORMAT] = &AVSenderEngine::SetVideoPixelFormat; + funcMap_[AVTransTag::VIDEO_FRAME_RATE] = &AVSenderEngine::SetVideoFrameRate; + funcMap_[AVTransTag::AUDIO_BIT_RATE] = &AVSenderEngine::SetAudioBitRate; + funcMap_[AVTransTag::VIDEO_BIT_RATE] = &AVSenderEngine::SetVideoBitRate; + funcMap_[AVTransTag::VIDEO_CODEC_TYPE] = &AVSenderEngine::SetVideoCodecType; + funcMap_[AVTransTag::AUDIO_CODEC_TYPE] = &AVSenderEngine::SetAudioCodecType; + funcMap_[AVTransTag::AUDIO_CHANNEL_MASK] = &AVSenderEngine::SetAudioChannelMask; + funcMap_[AVTransTag::AUDIO_SAMPLE_RATE] = &AVSenderEngine::SetAudioSampleRate; + funcMap_[AVTransTag::AUDIO_CHANNEL_LAYOUT] = &AVSenderEngine::SetAudioChannelLayout; + funcMap_[AVTransTag::AUDIO_SAMPLE_FORMAT] = &AVSenderEngine::SetAudioSampleFormat; + funcMap_[AVTransTag::AUDIO_FRAME_SIZE] = &AVSenderEngine::SetAudioFrameSize; + funcMap_[AVTransTag::SHARED_MEMORY_FD] = &AVSenderEngine::SetSharedMemoryFd; + funcMap_[AVTransTag::ENGINE_READY] = &AVSenderEngine::SetEngineReady; + funcMap_[AVTransTag::ENGINE_PAUSE] = &AVSenderEngine::SetEnginePause; + funcMap_[AVTransTag::ENGINE_RESUME] = &AVSenderEngine::SetEngineResume; +} + +void AVSenderEngine::SetVideoWidth(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_WIDTH), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter VIDEO_WIDTH success, video width = %s", value.c_str()); +} + +void AVSenderEngine::SetVideoHeight(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_HEIGHT), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter VIDEO_HEIGHT success, video height = %s", value.c_str()); +} + +void AVSenderEngine::SetVideoPixelFormat(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_PIXEL_FORMAT), Plugin::VideoPixelFormat::RGBA); + AVTRANS_LOGI("SetParameter VIDEO_PIXEL_FORMAT success, pixel format = %s", value.c_str()); +} + +void AVSenderEngine::SetVideoFrameRate(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_FRAME_RATE), std::atoi(value.c_str())); + avOutput_->SetParameter(static_cast(Plugin::Tag::VIDEO_FRAME_RATE), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter VIDEO_FRAME_RATE success, frame rate = %s", value.c_str()); +} + +void AVSenderEngine::SetAudioBitRate(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::MEDIA_BITRATE), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter MEDIA_BITRATE success, bit rate = %s", value.c_str()); +} + +void AVSenderEngine::SetVideoBitRate(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::MEDIA_BITRATE), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter MEDIA_BITRATE success, bit rate = %s", value.c_str()); +} + +void AVSenderEngine::SetVideoCodecType(const std::string &value) +{ + if (value == MIME_VIDEO_H264) { + Plugin::Meta encoderMeta; + encoderMeta.Set(MEDIA_MIME_VIDEO_H264); + encoderMeta.Set(Plugin::VideoH264Profile::BASELINE); + encoderMeta.Set(VIDEO_H264_LEVEL); + videoEncoder_->SetVideoEncoder(0, std::make_shared(encoderMeta)); + + std::string mime = MEDIA_MIME_VIDEO_RAW; + avInput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + mime = MEDIA_MIME_VIDEO_H264; + avOutput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + AVTRANS_LOGI("SetParameter VIDEO_CODEC_TYPE = H264 success"); + } else if (value == MIME_VIDEO_H265) { + Plugin::Meta encoderMeta; + encoderMeta.Set(MEDIA_MIME_VIDEO_H265); + videoEncoder_->SetVideoEncoder(0, std::make_shared(encoderMeta)); + + std::string mime = MEDIA_MIME_VIDEO_RAW; + avInput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + mime = MEDIA_MIME_VIDEO_H265; + avOutput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + AVTRANS_LOGI("SetParameter VIDEO_CODEC_TYPE = H265 success"); + } else { + AVTRANS_LOGE("SetParameter VIDEO_CODEC_TYPE failed, input value invalid."); + } +} + +void AVSenderEngine::SetAudioCodecType(const std::string &value) +{ + Plugin::Meta encoderMeta; + encoderMeta.Set(MEDIA_MIME_AUDIO_AAC); + encoderMeta.Set(Plugin::AudioAacProfile::LC); + audioEncoder_->SetAudioEncoder(0, std::make_shared(encoderMeta)); + + std::string mime = MEDIA_MIME_AUDIO_RAW; + avInput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + mime = MEDIA_MIME_AUDIO_AAC; + avOutput_->SetParameter(static_cast(Plugin::Tag::MIME), mime); + AVTRANS_LOGI("SetParameter AUDIO_CODEC_TYPE = ACC success"); +} + +void AVSenderEngine::SetAudioChannelMask(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_CHANNELS), std::atoi(value.c_str())); + avOutput_->SetParameter(static_cast(Plugin::Tag::AUDIO_CHANNELS), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_CHANNELS success, audio channels = %s", value.c_str()); +} + +void AVSenderEngine::SetAudioSampleRate(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_SAMPLE_RATE), std::atoi(value.c_str())); + avOutput_->SetParameter(static_cast(Plugin::Tag::AUDIO_SAMPLE_RATE), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_SAMPLE_RATE success, audio sample rate = %s", value.c_str()); +} + +void AVSenderEngine::SetAudioChannelLayout(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_CHANNEL_LAYOUT), std::atoi(value.c_str())); + avOutput_->SetParameter(static_cast(Plugin::Tag::AUDIO_CHANNEL_LAYOUT), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_CHANNEL_LAYOUT success, audio channel layout = %s", value.c_str()); +} + +void AVSenderEngine::SetAudioSampleFormat(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_SAMPLE_FORMAT), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_SAMPLE_FORMAT success, audio sample format = %s", value.c_str()); +} + +void AVSenderEngine::SetAudioFrameSize(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::AUDIO_SAMPLE_PER_FRAME), std::atoi(value.c_str())); + AVTRANS_LOGI("SetParameter AUDIO_SAMPLE_PER_FRAME success, audio sample per frame = %s", value.c_str()); +} + +void AVSenderEngine::SetSharedMemoryFd(const std::string &value) +{ + avInput_->SetParameter(static_cast(Plugin::Tag::USER_SHARED_MEMORY_FD), value); + AVTRANS_LOGI("SetParameter USER_SHARED_MEMORY_FD success, shared memory info = %s", value.c_str()); +} + +void AVSenderEngine::SetEngineReady(const std::string &value) +{ + int32_t ret = PreparePipeline(value); + TRUE_LOG_MSG(ret != DH_AVT_SUCCESS, "SetParameter ENGINE_READY failed"); +} + +void AVSenderEngine::SetEnginePause(const std::string &value) +{ + if (pipeline_ == nullptr) { + AVTRANS_LOGE("pipeline is null, need init first."); + return; + } + + ErrorCode ret = pipeline_->Pause(); + TRUE_LOG_MSG(ret != ErrorCode::SUCCESS, "pipeline pause failed"); +} + +void AVSenderEngine::SetEngineResume(const std::string &value) +{ + if (pipeline_ == nullptr) { + AVTRANS_LOGE("pipeline is null, need init first."); + return; + } + + ErrorCode ret = pipeline_->Resume(); + TRUE_LOG_MSG(ret != ErrorCode::SUCCESS, "pipeline resume failed"); +} + +int32_t AVSenderEngine::PushData(const std::shared_ptr &buffer) +{ + StateId currentState = GetCurrentState(); + bool isErrState = (currentState != StateId::STARTED) && (currentState != StateId::PLAYING); + TRUE_RETURN_V_MSG_E(isErrState, ERR_DH_AVT_PUSH_DATA_FAILED, + "current state=%" PRId32 " is invalid.", currentState); + + if (currentState == StateId::STARTED) { + NotifyStreamChange(EventType::EVENT_ADD_STREAM); + } + TRUE_RETURN_V_MSG_E(avInput_ == nullptr, ERR_DH_AVT_PUSH_DATA_FAILED, "av input filter is null"); + + std::shared_ptr hisBuffer = TransBuffer2HiSBuffer(buffer); + TRUE_RETURN_V(hisBuffer == nullptr, ERR_DH_AVT_PUSH_DATA_FAILED); + + ErrorCode ret = avInput_->PushData(avInput_->GetName(), hisBuffer, -1); + TRUE_RETURN_V(ret != ErrorCode::SUCCESS, ERR_DH_AVT_PUSH_DATA_FAILED); + + SetCurrentState(StateId::PLAYING); + return DH_AVT_SUCCESS; +} + +int32_t AVSenderEngine::PreparePipeline(const std::string &configParam) +{ + AVTRANS_LOGI("PreparePipeline enter."); + + StateId currentState = GetCurrentState(); + bool isErrState = ((currentState != StateId::INITIALIZED) && (currentState != StateId::CH_CREATED)); + TRUE_RETURN_V_MSG_E(isErrState, ERR_DH_AVT_PREPARE_FAILED, + "current state=%" PRId32 " is invalid.", currentState); + + TRUE_RETURN_V_MSG_E((avInput_ == nullptr) || (avOutput_ == nullptr), ERR_DH_AVT_PREPARE_FAILED, + "av input or output filter is null"); + + // First: config av input filter + ErrorCode ret = avInput_->SetParameter(static_cast(Plugin::Tag::MEDIA_TYPE), + TransName2MediaType(ownerName_)); + TRUE_RETURN_V_MSG_E(ret != ErrorCode::SUCCESS, ERR_DH_AVT_SET_PARAM_FAILED, "set media_type failed"); + + ret = avInput_->SetParameter(static_cast(Plugin::Tag::VIDEO_BIT_STREAM_FORMAT), + VideoBitStreamFormat::ANNEXB); + TRUE_RETURN_V_MSG_E(ret != ErrorCode::SUCCESS, ERR_DH_AVT_SET_PARAM_FAILED, "set video_bit_stream_format failed"); + + ret = avInput_->SetParameter(static_cast(Plugin::Tag::INPUT_MEMORY_TYPE), + OHOS::Media::Plugin::MemoryType::VIRTUAL_ADDR); + TRUE_RETURN_V_MSG_E(ret != ErrorCode::SUCCESS, ERR_DH_AVT_SET_PARAM_FAILED, "set input_memory_type failed"); + + // Second: config av output filter + ret = avOutput_->SetParameter(static_cast(Plugin::Tag::MEDIA_DESCRIPTION), + BuildChannelDescription(ownerName_, peerDevId_)); + TRUE_RETURN_V_MSG_E(ret != ErrorCode::SUCCESS, ERR_DH_AVT_SET_PARAM_FAILED, "set media_description failed"); + + ret = pipeline_->Prepare(); + TRUE_RETURN_V_MSG_E(ret != ErrorCode::SUCCESS, ERR_DH_AVT_PREPARE_FAILED, "pipeline prepare failed"); + + SetCurrentState(StateId::CH_CREATED); + return DH_AVT_SUCCESS; +} + +int32_t AVSenderEngine::SendMessage(const std::shared_ptr &message) +{ + TRUE_RETURN_V_MSG_E(message == nullptr, ERR_DH_AVT_INVALID_PARAM, "input message is nullptr."); + std::string msgData = message->MarshalMessage(); + return SoftbusChannelAdapter::GetInstance().SendBytesData(sessionName_, message->dstDevId_, msgData); +} + +int32_t AVSenderEngine::RegisterSenderCallback(const std::shared_ptr &callback) +{ + AVTRANS_LOGI("RegisterSenderCallback enter."); + TRUE_RETURN_V_MSG_E(callback == nullptr, ERR_DH_AVT_INVALID_PARAM, "input sender engine callback is nullptr."); + + senderCallback_ = callback; + return DH_AVT_SUCCESS; +} + +void AVSenderEngine::NotifyStreamChange(EventType type) +{ + AVTRANS_LOGI("NotifyStreamChange enter, change type=%" PRId32, type); + + std::string sceneType = ""; + if (ownerName_ == OWNER_NAME_D_MIC) { + sceneType = SCENE_TYPE_D_MIC; + } else if (ownerName_ == OWNER_NAME_D_SPEAKER) { + sceneType = SCENE_TYPE_D_SPEAKER; + } else if (ownerName_ == OWNER_NAME_D_SCREEN) { + sceneType = SCENE_TYPE_D_SCREEN; + } else if (ownerName_ == OWNER_NAME_D_CAMERA) { + TRUE_RETURN(avInput_ == nullptr, "av input filter is null"); + Plugin::Any value; + avInput_->GetParameter(static_cast(Plugin::Tag::VIDEO_PIXEL_FORMAT), value); + std::string videoFormat = Plugin::AnyCast(value); + sceneType = (videoFormat == VIDEO_FORMAT_JEPG) ? SCENE_TYPE_D_CAMERA_PIC : SCENE_TYPE_D_CAMERA_STR; + } else { + AVTRANS_LOGE("Unknown owner name=%s", ownerName_.c_str()); + return; + } + + TRUE_RETURN(dhfwkKit_ == nullptr, "dh fwk kit is nullptr."); + dhfwkKit_->NotifyAVCenter(engineId_, { type, sceneType, peerDevId_ }); +} + +void AVSenderEngine::OnChannelEvent(const AVTransEvent &event) +{ + AVTRANS_LOGI("OnChannelEvent enter. event type:%" PRId32, event.type); + TRUE_RETURN(senderCallback_ == nullptr, "sender callback is nullptr"); + + switch (event.type) { + case EventType::EVENT_CHANNEL_OPENED: { + SetCurrentState(StateId::CH_CREATED); + senderCallback_->OnSenderEvent(event); + break; + } + case EventType::EVENT_CHANNEL_OPEN_FAIL: { + SetCurrentState(StateId::INITIALIZED); + senderCallback_->OnSenderEvent(event); + break; + } + case EventType::EVENT_CHANNEL_CLOSED: { + StateId currentState = GetCurrentState(); + if ((currentState != StateId::IDLE) && (currentState != StateId::INITIALIZED)) { + SetCurrentState(StateId::INITIALIZED); + senderCallback_->OnSenderEvent(event); + } + break; + } + case EventType::EVENT_DATA_RECEIVED: { + auto avMessage = std::make_shared(); + TRUE_RETURN(!avMessage->UnmarshalMessage(event.content, event.peerDevId), "unmarshal message failed"); + senderCallback_->OnMessageReceived(avMessage); + break; + } + default: + AVTRANS_LOGE("Invalid event type."); + } +} + +void AVSenderEngine::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + (void)data; + (void)ext; +} + +void AVSenderEngine::OnEvent(const Event &event) +{ + AVTRANS_LOGI("OnEvent enter. event type:%s", GetEventName(event.type)); + TRUE_RETURN(senderCallback_ == nullptr, "sender callback is nullptr"); + + switch (event.type) { + case OHOS::Media::EventType::EVENT_PLUGIN_EVENT: { + Plugin::PluginEvent plugEvt = Plugin::AnyCast(event.param); + bool isPlaying = (GetCurrentState() == StateId::PLAYING); + senderCallback_->OnSenderEvent(AVTransEvent{CastEventType(plugEvt.type, isPlaying), "", peerDevId_}); + break; + } + default: + AVTRANS_LOGE("Invalid event type."); + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_sender/src/av_sender_engine_provider.cpp b/av_transport/av_trans_engine/av_sender/src/av_sender_engine_provider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12b1e70c072ea2a262f0dbaae10cb77910109d41 --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/src/av_sender_engine_provider.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_sender_engine_provider.h" + +#include "av_sender_engine.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVSenderEngineProvider" + +AVSenderEngineProvider::AVSenderEngineProvider(const std::string ownerName) : ownerName_(ownerName) +{ + AVTRANS_LOGI("AVSenderEngineProvider ctor."); + sessionName_ = ownerName + "_" + SENDER_CONTROL_SESSION_NAME_SUFFIX; + SoftbusChannelAdapter::GetInstance().CreateChannelServer(TransName2PkgName(ownerName), sessionName_); + SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, AV_TRANS_SPECIAL_DEVICE_ID, this); +} + +AVSenderEngineProvider::~AVSenderEngineProvider() +{ + AVTRANS_LOGI("AVSenderEngineProvider dctor."); + std::lock_guard lock(listMutex_); + for (auto &sender : senderEngineList_) { + sender->Release(); + } + SoftbusChannelAdapter::GetInstance().RemoveChannelServer(TransName2PkgName(ownerName_), sessionName_); + ownerName_ = ""; + sessionName_ = ""; + senderEngineList_.clear(); + providerCallback_ = nullptr; +} + +std::shared_ptr AVSenderEngineProvider::CreateAVSenderEngine(const std::string &peerDevId) +{ + AVTRANS_LOGI("CreateAVSenderEngine enter."); + auto sender = std::make_shared(ownerName_, peerDevId); + if (sender && sender->Initialize() == DH_AVT_SUCCESS) { + { + std::lock_guard lock(listMutex_); + senderEngineList_.push_back(sender); + } + return sender; + } + AVTRANS_LOGE("create sender failed or sender init failed."); + return nullptr; +} + +std::vector> AVSenderEngineProvider::GetAVSenderEngineList() +{ + std::lock_guard lock(listMutex_); + return senderEngineList_; +} + +int32_t AVSenderEngineProvider::RegisterProviderCallback(const std::shared_ptr &callback) +{ + providerCallback_ = callback; + return DH_AVT_SUCCESS; +} + +void AVSenderEngineProvider::OnChannelEvent(const AVTransEvent &event) +{ + if (providerCallback_ == nullptr) { + return; + } + if ((event.type == EventType::EVENT_CHANNEL_OPENED) || (event.type == EventType::EVENT_CHANNEL_CLOSED)) { + AVTRANS_LOGI("on receiver channel event. event type:%" PRId32, event.type); + providerCallback_->OnProviderEvent(event); + } +} + +void AVSenderEngineProvider::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + (void)data; + (void)ext; +} +} // namespace DistributedHardware +} // namespace OHOS + +extern "C" __attribute__((visibility("default"))) + OHOS::DistributedHardware::IAVEngineProvider* GetAVSenderEngineProvider(const std::string ownerName) +{ + return new (std::nothrow) OHOS::DistributedHardware::AVSenderEngineProvider(ownerName); +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_sender/test/unittest/BUILD.gn b/av_transport/av_trans_engine/av_sender/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..57975fec0457c23e10e4e6a61a77d21ab2331bf4 --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/test/unittest/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +group("sender_test") { + testonly = true + + deps = [ + "av_sender_engine:av_sender_engine_test", + "av_sender_engine_provider:av_sender_engine_provider_test", + ] +} diff --git a/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/BUILD.gn b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6ccbf07587894d98980224389f04d5520d43bdad --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/BUILD.gn @@ -0,0 +1,96 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/av_sender_engine_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${dh_fwk_utils_path}/include", + "${common_path}/include", + "${dh_fwk_sdk_path}/include", + "${engine_path}/av_sender/include", + "${control_center_path}/inner_kits/include", + "${control_center_path}/inner_kits/include/ipc", + "${filters_path}/av_transport_input", + "${filters_path}/av_transport_output", + "${engine_path}/av_sender/test/unittest/av_sender_engine/include", + "${interface_path}", + "${media_standard_path}/interfaces/inner_api/native", + ] +} + +ohos_unittest("AvSenderEngineTest") { + module_out_path = module_out_path + + sources = [ "src/av_sender_engine_test.cpp" ] + + configs = [ ":module_private_config" ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + "-Dprotected = public", + ] + cflags_cc = cflags + + deps = [ + "${dh_fwk_sdk_path}:libdhfwk_sdk", + "${engine_path}/av_sender:distributed_av_sender", + "${filters_path}:avtrans_input_filter", + "${filters_path}:avtrans_output_filter", + "//third_party/googletest:gtest_rtti", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"AvSenderEngineTest\"", + "LOG_DOMAIN=0xD004100", + ] + + defines += [ + "MEDIA_OHOS", + "RECORDER_SUPPORT", + "VIDEO_SUPPORT", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "graphic_2d:libgraphic_utils", + "graphic_2d:surface", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("av_sender_engine_test") { + testonly = true + deps = [ ":AvSenderEngineTest" ] +} diff --git a/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/include/av_sender_engine_test.h b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/include/av_sender_engine_test.h new file mode 100644 index 0000000000000000000000000000000000000000..6cdca1e1cc2231ebbf502f7f43c9b721a73d0e1c --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/include/av_sender_engine_test.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AV_TRANSPORT_INPUT_FILTER_TEST_H +#define AV_TRANSPORT_INPUT_FILTER_TEST_H + +#include + +#include "av_sender_engine.h" +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_message.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "i_av_sender_engine.h" +#include "softbus_channel_adapter.h" +#include "distributed_hardware_fwk_kit.h" +#include "av_trans_control_center_callback.h" +#include "av_transport_input_filter.h" +#include "av_transport_output_filter.h" + +// follwing head files depends on histreamer +#include "error_code.h" +#include "event.h" +#include "pipeline/core/filter.h" +#include "pipeline_core.h" +#include "audio_encoder_filter.h" +#include "video_encoder_filter.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +using namespace OHOS::Media::Pipeline; +using AVBuffer = OHOS::Media::Plugin::Buffer; + +class AvSenderEngineTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // AV_TRANSPORT_INPUT_FILTER_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/src/av_sender_engine_test.cpp b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/src/av_sender_engine_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7edd3151fd4e0eb1fc0fb674825a0127a67856f3 --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine/src/av_sender_engine_test.cpp @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_sender_engine_test.h" + +#include "pipeline/factory/filter_factory.h" +#include "plugin_video_tags.h" + +using namespace testing::ext; +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace DistributedHardware { +const std::string FILTERNAME = "avsenderengine"; + +void AvSenderEngineTest::SetUp() +{ +} + +void AvSenderEngineTest::TearDown() +{ +} + +void AvSenderEngineTest::SetUpTestCase() +{ +} + +void AvSenderEngineTest::TearDownTestCase() +{ +} + +HWTEST_F(AvSenderEngineTest, Initialize_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->initialized_ = true; + int32_t ret = sender->Initialize(); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +HWTEST_F(AvSenderEngineTest, Initialize_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->avInput_ = nullptr; + int32_t ret = sender->Initialize(); + EXPECT_EQ(ERR_DH_AVT_INIT_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, Initialize_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->sessionName_ = ""; + int32_t ret = sender->Initialize(); + EXPECT_EQ(ERR_DH_AVT_INIT_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, CreateControlChannel_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + std::vector dstDevIds; + int32_t ret = sender->CreateControlChannel(dstDevIds, ChannelAttribute{TransStrategy::LOW_LATANCY_STRATEGY}); + EXPECT_EQ(ERR_DH_AVT_NULL_POINTER, ret); +} + +HWTEST_F(AvSenderEngineTest, CreateControlChannel_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + std::vector dstDevIds = {peerDevId}; + int32_t ret = sender->CreateControlChannel(dstDevIds, ChannelAttribute{TransStrategy::LOW_LATANCY_STRATEGY}); + EXPECT_EQ(ERR_DH_AVT_CREATE_CHANNEL_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, CreateControlChannel_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + std::vector dstDevIds = {peerDevId}; + int32_t ret = sender->CreateControlChannel(dstDevIds, ChannelAttribute{TransStrategy::LOW_LATANCY_STRATEGY}); + EXPECT_EQ(ERR_DH_AVT_CREATE_CHANNEL_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, Start_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->currentState_ = StateId::IDLE; + sender->pipeline_ = std::make_shared(); + int32_t ret = sender->Start(); + EXPECT_EQ(ERR_DH_AVT_START_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, Start_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->currentState_ = StateId::CH_CREATED; + sender->pipeline_ = std::make_shared(); + int32_t ret = sender->Start(); + sender->Stop(); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +HWTEST_F(AvSenderEngineTest, Stop_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->currentState_ = StateId::CH_CREATED; + sender->pipeline_ = std::make_shared(); + sender->Start(); + int32_t ret = sender->Stop(); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} + +HWTEST_F(AvSenderEngineTest, SetParameter_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + int32_t ret = sender->SetParameter(AVTransTag::INVALID, value); + EXPECT_EQ(ERR_DH_AVT_SETUP_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, SetParameter_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + int32_t ret = sender->SetParameter(AVTransTag::INVALID, value); + EXPECT_EQ(ERR_DH_AVT_SETUP_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, SetParameter_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + sender->avOutput_ = FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, "avoutput"); + int32_t ret = sender->SetParameter(AVTransTag::INVALID, value); + EXPECT_EQ(ERR_DH_AVT_SETUP_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, SetParameter_004, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "123"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + sender->avOutput_ = FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, "avoutput"); + + std::shared_ptr pipeline_ = nullptr; + sender->pipeline_ = std::make_shared(); + int32_t ret = sender->SetParameter(AVTransTag::VIDEO_WIDTH, value); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM, ret); +} + +HWTEST_F(AvSenderEngineTest, PushData_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + std::shared_ptr buffer = std::make_shared(); + sender->currentState_ = StateId::IDLE; + int32_t ret = sender->PushData(buffer); + EXPECT_EQ(ERR_DH_AVT_PUSH_DATA_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, PushData_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + std::shared_ptr buffer = std::make_shared(); + sender->currentState_ = StateId::IDLE; + int32_t ret = sender->PushData(buffer); + EXPECT_EQ(ERR_DH_AVT_PUSH_DATA_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, PushData_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + std::shared_ptr buffer = std::make_shared(); + sender->currentState_ = StateId::STARTED; + int32_t ret = sender->PushData(buffer); + EXPECT_EQ(ERR_DH_AVT_PUSH_DATA_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, PushData_004, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + std::shared_ptr buffer = std::make_shared(); + sender->currentState_ = StateId::STARTED; + sender->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + int32_t ret = sender->PushData(buffer); + EXPECT_EQ(ERR_DH_AVT_PUSH_DATA_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, PushData_005, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string value = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + std::shared_ptr buffer = nullptr; + sender->currentState_ = StateId::STARTED; + sender->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + int32_t ret = sender->PushData(buffer); + EXPECT_EQ(ERR_DH_AVT_PUSH_DATA_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, PreparePipeline_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->currentState_ = StateId::STARTED; + int32_t ret = sender->PreparePipeline(configParam); + EXPECT_EQ(ERR_DH_AVT_PREPARE_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, PreparePipeline_002, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->currentState_ = StateId::INITIALIZED; + int32_t ret = sender->PreparePipeline(configParam); + EXPECT_EQ(ERR_DH_AVT_PREPARE_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, PreparePipeline_003, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->currentState_ = StateId::INITIALIZED; + sender->avInput_ = FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, "avinput"); + int32_t ret = sender->PreparePipeline(configParam); + EXPECT_EQ(ERR_DH_AVT_PREPARE_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, PreparePipeline_004, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + sender->currentState_ = StateId::INITIALIZED; + std::shared_ptr avOutput_ = nullptr; + avOutput_ = FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, "avoutput"); + int32_t ret = sender->PreparePipeline(configParam); + EXPECT_EQ(ERR_DH_AVT_PREPARE_FAILED, ret); +} + +HWTEST_F(AvSenderEngineTest, SendMessage_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "001"; + std::string peerDevId = "pEid"; + std::string configParam = "value"; + auto sender = std::make_shared(ownerName, peerDevId); + int32_t ret = sender->SendMessage(nullptr); + EXPECT_EQ(ERR_DH_AVT_INVALID_PARAM, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/BUILD.gn b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..111c7b4198021755245e0f475696451622eb0fe4 --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/BUILD.gn @@ -0,0 +1,96 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/av_sender_engine_provider_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${dh_fwk_utils_path}/include", + "${common_path}/include", + "${dh_fwk_sdk_path}/include", + "${engine_path}/av_sender/include", + "${control_center_path}/inner_kits/include", + "${control_center_path}/inner_kits/include/ipc", + "${filters_path}/av_transport_input", + "${filters_path}/av_transport_output", + "${engine_path}/av_sender/test/unittest/av_sender_engine_provider/include", + "${interface_path}", + "${media_standard_path}/interfaces/inner_api/native", + ] +} + +ohos_unittest("AvSenderEngineProviderTest") { + module_out_path = module_out_path + + sources = [ "src/av_sender_engine_provider_test.cpp" ] + + configs = [ ":module_private_config" ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + "-Dprotected = public", + ] + cflags_cc = cflags + + deps = [ + "${dh_fwk_sdk_path}:libdhfwk_sdk", + "${engine_path}/av_sender:distributed_av_sender", + "${filters_path}:avtrans_input_filter", + "${filters_path}:avtrans_output_filter", + "//third_party/googletest:gtest_rtti", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"AvSenderEngineProviderTest\"", + "LOG_DOMAIN=0xD004100", + ] + + defines += [ + "MEDIA_OHOS", + "RECORDER_SUPPORT", + "VIDEO_SUPPORT", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "graphic_2d:libgraphic_utils", + "graphic_2d:surface", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("av_sender_engine_provider_test") { + testonly = true + deps = [ ":AvSenderEngineProviderTest" ] +} diff --git a/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/include/av_sender_engine_provider_test.h b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/include/av_sender_engine_provider_test.h new file mode 100644 index 0000000000000000000000000000000000000000..f3f6edaf9022a6a42590f67423e891e3360c61d6 --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/include/av_sender_engine_provider_test.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AV_TRANSPORT_INPUT_FILTER_TEST_H +#define AV_TRANSPORT_INPUT_FILTER_TEST_H + +#include + +#include "av_sender_engine_provider.h" +#include "i_av_engine_provider.h" +#include "softbus_channel_adapter.h" + + +namespace OHOS { +namespace DistributedHardware { + + +class AvSenderEngineProviderTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // AV_TRANSPORT_INPUT_FILTER_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/src/av_sender_engine_provider_test.cpp b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/src/av_sender_engine_provider_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0db2c6d6c262954ffe6c5279db90685920e668a4 --- /dev/null +++ b/av_transport/av_trans_engine/av_sender/test/unittest/av_sender_engine_provider/src/av_sender_engine_provider_test.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_sender_engine_provider_test.h" + +#include "av_sender_engine.h" + +using namespace testing::ext; +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace DistributedHardware { + +void AvSenderEngineProviderTest::SetUp() +{ +} + +void AvSenderEngineProviderTest::TearDown() +{ +} + +void AvSenderEngineProviderTest::SetUpTestCase() +{ +} + +void AvSenderEngineProviderTest::TearDownTestCase() +{ +} + +HWTEST_F(AvSenderEngineProviderTest, CreateAVSenderEngine_001, testing::ext::TestSize.Level1) +{ + std::string peerDevId = "peerDevId"; + std::string ownerName = "ownerName"; + auto avSendProTest_ = std::make_shared(ownerName); + auto avSenderEngine = avSendProTest_->CreateAVSenderEngine(peerDevId); + EXPECT_EQ(nullptr, avSenderEngine); +} + +HWTEST_F(AvSenderEngineProviderTest, GetAVSenderEngineList_001, testing::ext::TestSize.Level1) +{ + std::string peerDevId = "peerDevId"; + std::string ownerName = "ownerName"; + auto avSendProTest_ = std::make_shared(ownerName); + auto avSenderEngine = avSendProTest_->CreateAVSenderEngine(peerDevId); + std::vector> senderEngineList = avSendProTest_->GetAVSenderEngineList(); + bool bRet = (senderEngineList.empty()) ? false : true; + EXPECT_NE(true, bRet); +} + +HWTEST_F(AvSenderEngineProviderTest, GetAVSenderEngineList_002, testing::ext::TestSize.Level1) +{ + std::string peerDevId = "peerDevId"; + std::string ownerName = "ownerName"; + auto avSendProTest_ = std::make_shared(ownerName); + auto avSenderEngine = avSendProTest_->CreateAVSenderEngine(peerDevId); + auto sender = std::make_shared(ownerName, peerDevId); + avSendProTest_->senderEngineList_.push_back(sender); + std::vector> senderEngineList = avSendProTest_->GetAVSenderEngineList(); + bool bRet = (senderEngineList.empty()) ? false : true; + EXPECT_EQ(true, bRet); +} + +HWTEST_F(AvSenderEngineProviderTest, RegisterProviderCallback_001, testing::ext::TestSize.Level1) +{ + std::string ownerName = "ownerName"; + auto avSendProTest_ = std::make_shared(ownerName); + std::shared_ptr callback = nullptr; + int32_t ret = avSendProTest_->RegisterProviderCallback(callback); + EXPECT_EQ(DH_AVT_SUCCESS, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/filters/BUILD.gn b/av_transport/av_trans_engine/filters/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5afe86d98027ec4dec8147b8890ccd97b677fdda --- /dev/null +++ b/av_transport/av_trans_engine/filters/BUILD.gn @@ -0,0 +1,112 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("avtrans_input_filter") { + include_dirs = [ + "${plugin_path}/core", + "${plugin_path}/interface", + "${common_path}/include", + ] + + sources = [ + "${plugin_path}/core/avtrans_input.cpp", + "av_transport_input/av_transport_input_filter.cpp", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_deps = [ + "${plugin_path}/plugins/av_trans_input/daudio_input:plugin_AVTransDaudioInput", + "${plugin_path}/plugins/av_trans_input/dscreen_input:plugin_AVTransDscreenInput", + "${plugin_path}/plugins/av_trans_input/dsoftbus_input:plugin_AVTransDsoftbusInput", + "${plugin_path}/plugins/av_trans_input/dsoftbus_input_audio:plugin_AVTransDsoftbusInputAudio", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Wno-unused-but-set-variable", + "-Wno-format", + ] + cflags_cc = cflags + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"av_transport_input_filter\"", + "LOG_DOMAIN=0xD004100", + ] +} + +ohos_source_set("avtrans_output_filter") { + include_dirs = [ + "${plugin_path}/core", + "${plugin_path}/interface", + "${common_path}/include", + ] + + sources = [ + "${plugin_path}/core/avtrans_output.cpp", + "av_transport_output/av_transport_output_filter.cpp", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_deps = [ + "${plugin_path}/plugins/av_trans_output/daudio_output:plugin_AVTransDaudioOutput", + "${plugin_path}/plugins/av_trans_output/dscreen_output:plugin_AVTransDscreenOutput", + "${plugin_path}/plugins/av_trans_output/dsoftbus_output:plugin_AVTransDsoftbusOutput", + "${plugin_path}/plugins/av_trans_output/dsoftbus_output_audio:plugin_AVTransDsoftbusOutputAudio", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Wno-unused-but-set-variable", + "-Wno-format", + ] + cflags_cc = cflags + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"av_transport_output_filter\"", + "LOG_DOMAIN=0xD004100", + ] +} diff --git a/av_transport/av_trans_engine/filters/av_transport_input/av_transport_input_filter.cpp b/av_transport/av_trans_engine/filters/av_transport_input/av_transport_input_filter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0876194b69be53a4ea7b8165e2a319fc8a659f5 --- /dev/null +++ b/av_transport/av_trans_engine/filters/av_transport_input/av_transport_input_filter.cpp @@ -0,0 +1,589 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define HST_LOG_TAG "AVInputFilter" +#include "av_transport_input_filter.h" +#include "av_trans_log.h" +#include "av_trans_constants.h" +#include "pipeline/filters/common/plugin_utils.h" +#include "pipeline/factory/filter_factory.h" +#include "plugin/common/plugin_attr_desc.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVInputFilter" + +static AutoRegisterFilter g_registerFilterHelper("builtin.avtransport.avinput"); + +AVInputFilter::AVInputFilter(const std::string& name) : FilterBase(name), plugin_(nullptr), pluginInfo_(nullptr) +{ + AVTRANS_LOGI("ctor called"); +} + +AVInputFilter::~AVInputFilter() +{ + AVTRANS_LOGI("dtor called"); +} + +std::vector AVInputFilter::GetWorkModes() +{ + return {WorkMode::PUSH}; +} + +ErrorCode AVInputFilter::SetParameter(int32_t key, const Any& value) +{ + Tag tag; + if (!TranslateIntoParameter(key, tag)) { + AVTRANS_LOGE("This key is invalid!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + if (plugin_ != nullptr) { + plugin_->SetParameter(static_cast(key), value); + } + { + OSAL::ScopedLock lock(inputFilterMutex_); + paramsMap_[tag] = value; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::GetParameter(int32_t key, Any& value) +{ + Tag tag; + if (!TranslateIntoParameter(key, tag)) { + AVTRANS_LOGE("This key is invalid!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + { + OSAL::ScopedLock lock(inputFilterMutex_); + value = paramsMap_[tag]; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::Prepare() +{ + AVTRANS_LOGI("Prepare entered."); + if (state_ != FilterState::INITIALIZED) { + AVTRANS_LOGE("The current state is invalid"); + return ErrorCode::ERROR_INVALID_STATE; + } + state_ = FilterState::PREPARING; + ErrorCode err = FindPlugin(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Find plugin fail"); + state_ = FilterState::INITIALIZED; + return err; + } + err = DoConfigure(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Configure downStream fail"); + state_ = FilterState::INITIALIZED; + return err; + } + err = PreparePlugin(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Prepare plugin fail"); + state_ = FilterState::INITIALIZED; + return err; + } + state_ = FilterState::READY; + AVTRANS_LOGI("Prepare end."); + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::Start() +{ + AVTRANS_LOGI("Start"); + OSAL::ScopedLock lock(inputFilterMutex_); + if (state_ != FilterState::READY && state_ != FilterState::PAUSED) { + AVTRANS_LOGE("The current state is invalid"); + return ErrorCode::ERROR_INVALID_STATE; + } + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + if (TranslatePluginStatus(plugin_->Start()) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("The plugin start fail!"); + return ErrorCode::ERROR_INVALID_OPERATION; + } + state_ = FilterState::RUNNING; + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::Stop() +{ + AVTRANS_LOGI("Stop"); + OSAL::ScopedLock lock(inputFilterMutex_); + if (state_ != FilterState::RUNNING && state_ != FilterState::PAUSED) { + AVTRANS_LOGE("The current state is invalid"); + return ErrorCode::ERROR_INVALID_STATE; + } + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + if (TranslatePluginStatus(plugin_->Stop()) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("The plugin stop fail!"); + return ErrorCode::ERROR_INVALID_OPERATION; + } + plugin_->Deinit(); + plugin_ = nullptr; + state_ = FilterState::READY; + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::Pause() +{ + AVTRANS_LOGI("Pause"); + OSAL::ScopedLock lock(inputFilterMutex_); + if (state_ == FilterState::PAUSED) { + return ErrorCode::SUCCESS; + } + if ((state_ != FilterState::READY) && (state_ != FilterState::RUNNING)) { + AVTRANS_LOGE("The current state is invalid"); + return ErrorCode::ERROR_INVALID_STATE; + } + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + ErrorCode ret = TranslatePluginStatus(plugin_->Pause()); + if (ret != ErrorCode::SUCCESS) { + AVTRANS_LOGE("The plugin pause fail!"); + return ret; + } + state_ = FilterState::PAUSED; + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::Resume() +{ + AVTRANS_LOGI("Resume"); + OSAL::ScopedLock lock(inputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + ErrorCode ret = TranslatePluginStatus(plugin_->Resume()); + if (ret != ErrorCode::SUCCESS) { + AVTRANS_LOGE("The plugin resume fail!"); + return ret; + } + state_ = FilterState::RUNNING; + return ErrorCode::SUCCESS; +} + +void AVInputFilter::InitPorts() +{ + AVTRANS_LOGI("InitPorts"); + auto outPort = std::make_shared(this); + { + OSAL::ScopedLock lock(inputFilterMutex_); + outPorts_.push_back(outPort); + } +} + +ErrorCode AVInputFilter::FindPlugin() +{ + OSAL::ScopedLock lock(inputFilterMutex_); + std::string mime; + if (paramsMap_.find(Tag::MIME) == paramsMap_.end() || + !paramsMap_[Tag::MIME].SameTypeWith(typeid(std::string))) { + AVTRANS_LOGE("Must set mime correctly first"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + mime = Plugin::AnyCast(paramsMap_[Tag::MIME]); + auto nameList = PluginManager::Instance().ListPlugins(PluginType::GENERIC_PLUGIN); + for (const std::string& name : nameList) { + auto info = PluginManager::Instance().GetPluginInfo(PluginType::GENERIC_PLUGIN, name); + if (info->outCaps.empty() || mime != info->outCaps[0].mime) { + continue; + } + if (DoNegotiate(info->outCaps) && CreatePlugin(info) == ErrorCode::SUCCESS) { + AVTRANS_LOGI("CreatePlugin %s success", name_.c_str()); + return ErrorCode::SUCCESS; + } + } + AVTRANS_LOGI("Cannot find any plugin"); + return ErrorCode::ERROR_UNSUPPORTED_FORMAT; +} + +bool AVInputFilter::DoNegotiate(const CapabilitySet& outCaps) +{ + AVTRANS_LOGI("DoNegotiate start"); + if (outCaps.empty()) { + AVTRANS_LOGE("Input plugin must have out caps"); + return false; + } + for (const auto& outCap : outCaps) { + auto thisOutCap = std::make_shared(outCap); + AVTRANS_LOGI("thisOutCap %s", thisOutCap->mime.c_str()); + Meta upstreamParams; + Meta downstreamParams; + if (outPorts_.size() == 0 || outPorts_[0] == nullptr) { + AVTRANS_LOGE("outPorts is empty or invalid!"); + return false; + } + if (outPorts_[0]->Negotiate(thisOutCap, capNegWithDownstream_, upstreamParams, downstreamParams)) { + AVTRANS_LOGI("Negotiate success"); + return true; + } + } + AVTRANS_LOGI("DoNegotiate end"); + return false; +} + +ErrorCode AVInputFilter::CreatePlugin(const std::shared_ptr& selectedInfo) +{ + AVTRANS_LOGI("CreatePlugin"); + if (selectedInfo == nullptr || selectedInfo->name.empty()) { + AVTRANS_LOGE("selectedInfo is nullptr or pluginName is invalid!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + if ((plugin_ != nullptr) && (pluginInfo_ != nullptr)) { + if (selectedInfo->name == pluginInfo_->name && TranslatePluginStatus(plugin_->Reset()) == ErrorCode::SUCCESS) { + AVTRANS_LOGI("Reuse last plugin: %s", selectedInfo->name.c_str()); + return ErrorCode::SUCCESS; + } + if (TranslatePluginStatus(plugin_->Deinit()) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Deinit last plugin: %s error", pluginInfo_->name.c_str()); + } + } + plugin_ = PluginManager::Instance().CreateGenericPlugin(selectedInfo->name); + if (plugin_ == nullptr) { + AVTRANS_LOGE("PluginManager CreatePlugin %s fail", selectedInfo->name.c_str()); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + pluginInfo_ = selectedInfo; + AVTRANS_LOGI("Create new plugin: %s success", pluginInfo_->name.c_str()); + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::DoConfigure() +{ + Plugin::Meta emptyMeta; + Plugin::Meta targetMeta; + if (MergeMeta(emptyMeta, targetMeta) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Merge Meta fail!"); + return ErrorCode::ERROR_INVALID_OPERATION; + } + if (ConfigMeta(targetMeta) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Config Meta fail!"); + return ErrorCode::ERROR_INVALID_OPERATION; + } + if (ConfigDownStream(targetMeta) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Config DownStream fail!"); + return ErrorCode::ERROR_INVALID_OPERATION; + } + auto err = InitPlugin(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Init plugin fail"); + state_ = FilterState::INITIALIZED; + return ErrorCode::ERROR_INVALID_OPERATION; + } + err = ConfigPlugin(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Configure plugin fail"); + state_ = FilterState::INITIALIZED; + return ErrorCode::ERROR_INVALID_OPERATION; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::MergeMeta(const Plugin::Meta& meta, Plugin::Meta& targetMeta) +{ + OSAL::ScopedLock lock(inputFilterMutex_); + if (!MergeMetaWithCapability(meta, capNegWithDownstream_, targetMeta)) { + AVTRANS_LOGE("cannot find available capability of plugin %s", pluginInfo_->name.c_str()); + return ErrorCode::ERROR_INVALID_OPERATION; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::ConfigMeta(Plugin::Meta& meta) +{ + AVTRANS_LOGI("ConfigMeta start!"); + OSAL::ScopedLock lock(inputFilterMutex_); + if (paramsMap_.find(Tag::MEDIA_TYPE) == paramsMap_.end() || + !paramsMap_[Tag::MEDIA_TYPE].SameTypeWith(typeid(Plugin::MediaType))) { + AVTRANS_LOGE("MEDIA_TYPE in ParamsMap is not exist!"); + return ErrorCode::ERROR_NOT_EXISTED; + } + auto mediaType = Plugin::AnyCast(paramsMap_[Tag::MEDIA_TYPE]); + if (mediaType == MediaType::VIDEO) { + ConfigVideoMeta(meta); + } else { + ConfigAudioMeta(meta); + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::ConfigVideoMeta(Plugin::Meta& meta) +{ + AVTRANS_LOGI("ConfigVideoMeta start!"); + if (paramsMap_.find(Tag::VIDEO_WIDTH) != paramsMap_.end() && + paramsMap_[Tag::VIDEO_WIDTH].SameTypeWith(typeid(int))) { + uint32_t width = static_cast(Plugin::AnyCast(paramsMap_[Tag::VIDEO_WIDTH])); + AVTRANS_LOGI("ConfigVideoMeta: VIDEO_WIDTH is %d", width); + meta.Set(width); + } + if (paramsMap_.find(Tag::VIDEO_HEIGHT) != paramsMap_.end() && + paramsMap_[Tag::VIDEO_HEIGHT].SameTypeWith(typeid(int))) { + uint32_t height = static_cast(Plugin::AnyCast(paramsMap_[Tag::VIDEO_HEIGHT])); + AVTRANS_LOGI("ConfigVideoMeta: VIDEO_HEIGHT is %d", height); + meta.Set(height); + } + if (paramsMap_.find(Tag::MEDIA_BITRATE) != paramsMap_.end() && + paramsMap_[Tag::MEDIA_BITRATE].SameTypeWith(typeid(int))) { + int64_t mediaBitRate = Plugin::AnyCast(paramsMap_[Tag::MEDIA_BITRATE]); + AVTRANS_LOGI("ConfigVideoMeta: MEDIA_BITRATE is %ld", mediaBitRate); + meta.Set(mediaBitRate); + } + if (paramsMap_.find(Tag::VIDEO_FRAME_RATE) != paramsMap_.end() && + paramsMap_[Tag::VIDEO_FRAME_RATE].SameTypeWith(typeid(int))) { + uint32_t videoFrameRate = static_cast(Plugin::AnyCast(paramsMap_[Tag::VIDEO_FRAME_RATE])); + AVTRANS_LOGI("ConfigVideoMeta: VIDEO_FRAME_RATE is %d", videoFrameRate); + meta.Set(videoFrameRate); + } + if (paramsMap_.find(Tag::VIDEO_BIT_STREAM_FORMAT) != paramsMap_.end() && + paramsMap_[Tag::VIDEO_BIT_STREAM_FORMAT].SameTypeWith(typeid(VideoBitStreamFormat))) { + auto videoBitStreamFormat = Plugin::AnyCast(paramsMap_[Tag::VIDEO_BIT_STREAM_FORMAT]); + AVTRANS_LOGI("ConfigVideoMeta: VIDEO_BIT_STREAM_FORMAT is %d", videoBitStreamFormat); + meta.Set(std::vector{videoBitStreamFormat}); + } + if (paramsMap_.find(Tag::VIDEO_PIXEL_FORMAT) != paramsMap_.end() && + paramsMap_[Tag::VIDEO_PIXEL_FORMAT].SameTypeWith(typeid(VideoPixelFormat))) { + auto videoPixelFormat = Plugin::AnyCast(paramsMap_[Tag::VIDEO_PIXEL_FORMAT]); + AVTRANS_LOGI("ConfigVideoMeta: VIDEO_PIXEL_FORMAT is %d", videoPixelFormat); + meta.Set(videoPixelFormat); + } + return ErrorCode::SUCCESS; +} + +OHOS::Media::Plugin::AudioChannelLayout AVInputFilter::TransAudioChannelLayout(int layoutPtr) +{ + const static std::pair mapArray[] = { + {1, OHOS::Media::Plugin::AudioChannelLayout::MONO}, + {2, OHOS::Media::Plugin::AudioChannelLayout::STEREO}, + }; + for (const auto& item : mapArray) { + if (item.first == layoutPtr) { + return item.second; + } + } + return OHOS::Media::Plugin::AudioChannelLayout::UNKNOWN; +} + +OHOS::Media::Plugin::AudioSampleFormat AVInputFilter::TransAudioSampleFormat(int sampleFormat) +{ + const static std::pair mapArray[] = { + {0, OHOS::Media::Plugin::AudioSampleFormat::U8}, + {1, OHOS::Media::Plugin::AudioSampleFormat::S16}, + {2, OHOS::Media::Plugin::AudioSampleFormat::S24}, + {3, OHOS::Media::Plugin::AudioSampleFormat::S32}, + {4, OHOS::Media::Plugin::AudioSampleFormat::F32P}, + {-1, OHOS::Media::Plugin::AudioSampleFormat::NONE}, + }; + for (const auto& item : mapArray) { + if (item.first == sampleFormat) { + return item.second; + } + } + return OHOS::Media::Plugin::AudioSampleFormat::NONE; +} + +ErrorCode AVInputFilter::ConfigAudioMeta(Plugin::Meta& meta) +{ + AVTRANS_LOGI("ConfigAudioMeta start"); + if (paramsMap_.find(Tag::AUDIO_CHANNELS) != paramsMap_.end() && + paramsMap_[Tag::AUDIO_CHANNELS].SameTypeWith(typeid(int))) { + uint32_t audioChannel = static_cast(Plugin::AnyCast(paramsMap_[Tag::AUDIO_CHANNELS])); + AVTRANS_LOGI("ConfigAudioMeta: AUDIO_CHANNELS is %d", audioChannel); + meta.Set(audioChannel); + } + if (paramsMap_.find(Tag::AUDIO_SAMPLE_RATE) != paramsMap_.end() && + paramsMap_[Tag::AUDIO_SAMPLE_RATE].SameTypeWith(typeid(int))) { + uint32_t sampleRate = static_cast(Plugin::AnyCast(paramsMap_[Tag::AUDIO_SAMPLE_RATE])); + AVTRANS_LOGI("ConfigAudioMeta: AUDIO_SAMPLE_RATE is %d", sampleRate); + meta.Set(sampleRate); + } + if (paramsMap_.find(Tag::MEDIA_BITRATE) != paramsMap_.end() && + paramsMap_[Tag::MEDIA_BITRATE].SameTypeWith(typeid(int))) { + int64_t mediaBitRate = Plugin::AnyCast(paramsMap_[Tag::MEDIA_BITRATE]); + AVTRANS_LOGI("ConfigAudioMeta: MEDIA_BITRATE is %ld", mediaBitRate); + meta.Set(mediaBitRate); + } + if (paramsMap_.find(Tag::AUDIO_SAMPLE_FORMAT) != paramsMap_.end() && + paramsMap_[Tag::AUDIO_SAMPLE_FORMAT].SameTypeWith(typeid(int))) { + auto audioSampleFmtPtr = Plugin::AnyCast(paramsMap_[Tag::AUDIO_SAMPLE_FORMAT]); + AVTRANS_LOGI("ConfigAudioMeta: AUDIO_SAMPLE_FORMAT is %d", audioSampleFmtPtr); + meta.Set(TransAudioSampleFormat(audioSampleFmtPtr)); + } + if (paramsMap_.find(Tag::AUDIO_CHANNEL_LAYOUT) != paramsMap_.end() && + paramsMap_[Tag::AUDIO_CHANNEL_LAYOUT].SameTypeWith(typeid(int))) { + auto layoutPtr = Plugin::AnyCast(paramsMap_[Tag::AUDIO_CHANNEL_LAYOUT]); + AVTRANS_LOGI("ConfigAudioMeta: AUDIO_CHANNEL_LAYOUT is %d", layoutPtr); + meta.Set(TransAudioChannelLayout(layoutPtr)); + } + if (paramsMap_.find(Tag::AUDIO_SAMPLE_PER_FRAME) != paramsMap_.end() && + paramsMap_[Tag::AUDIO_SAMPLE_PER_FRAME].SameTypeWith(typeid(int))) { + uint32_t samplePerFrame = static_cast(Plugin::AnyCast(paramsMap_[Tag::AUDIO_SAMPLE_PER_FRAME])); + AVTRANS_LOGI("ConfigAudioMeta: AUDIO_SAMPLE_PER_FRAME is %d", samplePerFrame); + meta.Set(samplePerFrame); + } + if (paramsMap_.find(Tag::AUDIO_AAC_LEVEL) != paramsMap_.end() && + paramsMap_[Tag::AUDIO_AAC_LEVEL].SameTypeWith(typeid(int))) { + uint32_t aacLevel = static_cast(Plugin::AnyCast(paramsMap_[Tag::AUDIO_AAC_LEVEL])); + AVTRANS_LOGI("ConfigAudioMeta: AUDIO_AAC_LEVEL is %d", aacLevel); + meta.Set(aacLevel); + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::ConfigDownStream(const Plugin::Meta& meta) +{ + Meta upstreamParams; + Meta downstreamParams; + OSAL::ScopedLock lock(inputFilterMutex_); + if (outPorts_.size() == 0 || outPorts_[0] == nullptr) { + AVTRANS_LOGE("outPorts is empty or invalid!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + if (!outPorts_[0]->Configure(std::make_shared(meta), upstreamParams, downstreamParams)) { + AVTRANS_LOGE("Configure downstream fail"); + return ErrorCode::ERROR_INVALID_OPERATION; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::InitPlugin() +{ + AVTRANS_LOGI("InitPlugin"); + OSAL::ScopedLock lock(inputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + return TranslatePluginStatus(plugin_->Init()); +} + +ErrorCode AVInputFilter::ConfigPlugin() +{ + AVTRANS_LOGI("Configure"); + ErrorCode err = SetPluginParams(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Set Plugin fail!"); + return err; + } + err = SetEventCallBack(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Plugin SetEventCallBack fail!"); + return err; + } + err = SetDataCallBack(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Plugin SetDataCallBack fail!"); + return err; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::SetPluginParams() +{ + OSAL::ScopedLock lock(inputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + if (paramsMap_.find(Tag::MEDIA_DESCRIPTION) != paramsMap_.end()) { + plugin_->SetParameter(Tag::MEDIA_DESCRIPTION, paramsMap_[Tag::MEDIA_DESCRIPTION]); + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::PreparePlugin() +{ + OSAL::ScopedLock lock(inputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + return TranslatePluginStatus(plugin_->Prepare()); +} + +ErrorCode AVInputFilter::PushData(const std::string& inPort, const AVBufferPtr& buffer, int64_t offset) +{ + OSAL::ScopedLock lock(inputFilterMutex_); + if (name_.compare(inPort) != 0) { + AVTRANS_LOGE("FilterName is not targetName!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + if (buffer == nullptr || plugin_ == nullptr) { + AVTRANS_LOGE("buffer or plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + + if (TranslatePluginStatus(plugin_->PushData(inPort, buffer, offset)) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("PushData to plugin fail!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + + if (outPorts_.size() == 0 || outPorts_[0] == nullptr) { + AVTRANS_LOGE("outPorts is empty or invalid!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + outPorts_[0]->PushData(buffer, 0); + return ErrorCode::SUCCESS; +} + +ErrorCode AVInputFilter::SetEventCallBack() +{ + OSAL::ScopedLock lock(inputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER ; + } + return TranslatePluginStatus(plugin_->SetCallback(this)); +} + +ErrorCode AVInputFilter::SetDataCallBack() +{ + OSAL::ScopedLock lock(inputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + return TranslatePluginStatus(plugin_->SetDataCallback(std::bind(&AVInputFilter::OnDataCallback, this, + std::placeholders::_1))); +} + +void AVInputFilter::OnDataCallback(std::shared_ptr buffer) +{ + OSAL::ScopedLock lock(inputFilterMutex_); + if (buffer == nullptr) { + AVTRANS_LOGE("buffer is nullptr!"); + return; + } + if (outPorts_.size() == 0 || outPorts_[0] == nullptr) { + AVTRANS_LOGE("outPorts is invalid!"); + return; + } + outPorts_[0]->PushData(buffer, 0); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/filters/av_transport_input/av_transport_input_filter.h b/av_transport/av_trans_engine/filters/av_transport_input/av_transport_input_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..8debcd5fca2e88b0dc0848899249e6ede73dc920 --- /dev/null +++ b/av_transport/av_trans_engine/filters/av_transport_input/av_transport_input_filter.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MEDIA_PIPELINE_INPUT_FILTER_H +#define MEDIA_PIPELINE_INPUT_FILTER_H + +#include +#include + +#include "foundation/osal/utils/util.h" +#include "foundation/utils/constants.h" +#include "pipeline/core/error_code.h" +#include "pipeline/core/filter_base.h" +#include "plugin/common/plugin_video_tags.h" +#include "plugin/core/plugin_manager.h" +#include "pipeline/core/type_define.h" +#include "../../plugin/interface/avtrans_input_plugin.h" +#include "../../plugin/core/avtrans_input.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Pipeline; + +class AVInputFilter : public FilterBase { +public: + explicit AVInputFilter(const std::string& name); + ~AVInputFilter() override; + + std::vector GetWorkModes() override; + ErrorCode SetParameter(int32_t key, const Plugin::Any& value) override; + ErrorCode GetParameter(int32_t key, Plugin::Any& value) override; + ErrorCode Prepare() override; + ErrorCode Start() override; + ErrorCode Stop() override; + ErrorCode Pause() override; + ErrorCode Resume() override; + ErrorCode PushData(const std::string& inPort, const AVBufferPtr& buffer, int64_t offset) override; + +private: + void InitPorts() override; + ErrorCode FindPlugin(); + bool DoNegotiate(const CapabilitySet& outCaps); + ErrorCode CreatePlugin(const std::shared_ptr& selectedInfo); + ErrorCode DoConfigure(); + ErrorCode MergeMeta(const Plugin::Meta& meta, Plugin::Meta& targetMeta); + ErrorCode ConfigMeta(Plugin::Meta& meta); + ErrorCode ConfigVideoMeta(Plugin::Meta& meta); + ErrorCode ConfigAudioMeta(Plugin::Meta& meta); + ErrorCode ConfigDownStream(const Plugin::Meta& meta); + ErrorCode InitPlugin(); + ErrorCode ConfigPlugin(); + ErrorCode PreparePlugin(); + ErrorCode SetEventCallBack(); + ErrorCode SetDataCallBack(); + ErrorCode SetPluginParams(); + void OnDataCallback(std::shared_ptr buffer); + OHOS::Media::Plugin::AudioChannelLayout TransAudioChannelLayout(int layoutPtr); + OHOS::Media::Plugin::AudioSampleFormat TransAudioSampleFormat(int sampleFormat); + + std::shared_ptr plugin_ {nullptr}; + std::shared_ptr pluginInfo_ {nullptr}; + Capability capNegWithDownstream_ {}; + std::unordered_map paramsMap_; + OSAL::Mutex inputFilterMutex_ {}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif \ No newline at end of file diff --git a/av_transport/av_trans_engine/filters/av_transport_output/av_transport_output_filter.cpp b/av_transport/av_trans_engine/filters/av_transport_output/av_transport_output_filter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c46b4912b50939d5e976a3e4e6594d664eab29b --- /dev/null +++ b/av_transport/av_trans_engine/filters/av_transport_output/av_transport_output_filter.cpp @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define HST_LOG_TAG "AVOutputFilter" +#include "av_transport_output_filter.h" +#include "av_trans_log.h" +#include "av_trans_constants.h" +#include "pipeline/filters/common/plugin_utils.h" +#include "pipeline/factory/filter_factory.h" +#include "plugin/common/plugin_attr_desc.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "AVOutputFilter" + +static AutoRegisterFilter g_registerFilterHelper("builtin.avtransport.avoutput"); + +AVOutputFilter::AVOutputFilter(const std::string& name) : FilterBase(name), plugin_(nullptr), pluginInfo_(nullptr) +{ + AVTRANS_LOGI("ctor called"); +} + +AVOutputFilter::~AVOutputFilter() +{ + AVTRANS_LOGI("dtor called"); +} + +std::vector AVOutputFilter::GetWorkModes() +{ + return {WorkMode::PUSH}; +} + +ErrorCode AVOutputFilter::SetParameter(int32_t key, const Any& value) +{ + Tag tag; + if (!TranslateIntoParameter(key, tag)) { + AVTRANS_LOGE("This key is invalid!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + if (plugin_ != nullptr) { + plugin_->SetParameter(static_cast(key), value); + } + { + OSAL::ScopedLock lock(outputFilterMutex_); + paramsMap_[tag] = value; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::GetParameter(int32_t key, Any& value) +{ + Tag tag; + if (!TranslateIntoParameter(key, tag)) { + AVTRANS_LOGE("This key is invalid!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + { + OSAL::ScopedLock lock(outputFilterMutex_); + value = paramsMap_[tag]; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::Prepare() +{ + AVTRANS_LOGI("Prepare entered."); + if (state_ != FilterState::INITIALIZED) { + AVTRANS_LOGE("The current state is invalid"); + return ErrorCode::ERROR_INVALID_STATE; + } + state_ = FilterState::PREPARING; + ErrorCode err = FindPlugin(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Find plugin fail"); + state_ = FilterState::INITIALIZED; + return err; + } + err = InitPlugin(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Init plugin fail"); + state_ = FilterState::INITIALIZED; + return err; + } + err = ConfigPlugin(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Configure downStream fail"); + state_ = FilterState::INITIALIZED; + return err; + } + err = PreparePlugin(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Prepare plugin fail"); + state_ = FilterState::INITIALIZED; + return err; + } + state_ = FilterState::READY; + AVTRANS_LOGI("Prepare end."); + return err; +} + +ErrorCode AVOutputFilter::Start() +{ + AVTRANS_LOGI("Start"); + OSAL::ScopedLock lock(outputFilterMutex_); + if (state_ != FilterState::READY && state_ != FilterState::PAUSED) { + AVTRANS_LOGE("The current state is invalid"); + return ErrorCode::ERROR_INVALID_STATE; + } + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + if (TranslatePluginStatus(plugin_->Start()) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("The plugin start fail!"); + return ErrorCode::ERROR_INVALID_OPERATION; + } + state_ = FilterState::RUNNING; + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::Stop() +{ + AVTRANS_LOGI("Stop"); + OSAL::ScopedLock lock(outputFilterMutex_); + if (state_ != FilterState::RUNNING) { + AVTRANS_LOGE("The current state is invalid"); + return ErrorCode::ERROR_INVALID_STATE; + } + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + if (TranslatePluginStatus(plugin_->Stop()) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("The plugin stop fail!"); + return ErrorCode::ERROR_INVALID_OPERATION; + } + plugin_->Deinit(); + plugin_ = nullptr; + state_ = FilterState::READY; + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::Pause() +{ + AVTRANS_LOGI("Pause"); + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::Resume() +{ + AVTRANS_LOGI("Resume"); + return ErrorCode::SUCCESS; +} + +void AVOutputFilter::InitPorts() +{ + AVTRANS_LOGI("InitPorts"); + auto inPort = std::make_shared(this); + { + OSAL::ScopedLock lock(outputFilterMutex_); + inPorts_.push_back(inPort); + } +} + +ErrorCode AVOutputFilter::FindPlugin() +{ + OSAL::ScopedLock lock(outputFilterMutex_); + std::string mime; + if (paramsMap_.find(Tag::MIME) == paramsMap_.end() || + !paramsMap_[Tag::MIME].SameTypeWith(typeid(std::string))) { + AVTRANS_LOGE("Must set mime correctly first"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + mime = Plugin::AnyCast(paramsMap_[Tag::MIME]); + auto nameList = PluginManager::Instance().ListPlugins(PluginType::GENERIC_PLUGIN); + for (const std::string& name : nameList) { + auto info = PluginManager::Instance().GetPluginInfo(PluginType::GENERIC_PLUGIN, name); + if (info->inCaps.empty() || mime != info->inCaps[0].mime) { + continue; + } + if (CreatePlugin(info) == ErrorCode::SUCCESS) { + AVTRANS_LOGI("CreatePlugin %s success", name_.c_str()); + return ErrorCode::SUCCESS; + } + } + AVTRANS_LOGI("Cannot find any plugin"); + return ErrorCode::ERROR_UNSUPPORTED_FORMAT; +} + +bool AVOutputFilter::Negotiate(const std::string& inPort, const std::shared_ptr& upstreamCap, + Plugin::Capability& negotiatedCap, const Plugin::Meta& upstreamParams, Plugin::Meta& downstreamParams) +{ + AVTRANS_LOGI("Negotiate"); + if (pluginInfo_ == nullptr) { + AVTRANS_LOGE("pluginInfo_ is nullptr"); + return false; + } + negotiatedCap = pluginInfo_->inCaps[0]; + return true; +} + +ErrorCode AVOutputFilter::CreatePlugin(const std::shared_ptr& selectedInfo) +{ + AVTRANS_LOGI("CreatePlugin"); + if (selectedInfo == nullptr || selectedInfo->name.empty()) { + AVTRANS_LOGE("selectedInfo is nullptr or pluginName is invalid!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + if ((plugin_ != nullptr) && (pluginInfo_ != nullptr)) { + if (selectedInfo->name == pluginInfo_->name && TranslatePluginStatus(plugin_->Reset()) == ErrorCode::SUCCESS) { + AVTRANS_LOGI("Reuse last plugin: %s", selectedInfo->name.c_str()); + return ErrorCode::SUCCESS; + } + if (TranslatePluginStatus(plugin_->Deinit()) != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Deinit last plugin: %s error", pluginInfo_->name.c_str()); + } + } + plugin_ = PluginManager::Instance().CreateGenericPlugin(selectedInfo->name); + if (plugin_ == nullptr) { + AVTRANS_LOGE("PluginManager CreatePlugin %s fail", selectedInfo->name.c_str()); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + pluginInfo_ = selectedInfo; + AVTRANS_LOGI("Create new plugin: %s success", pluginInfo_->name.c_str()); + return ErrorCode::SUCCESS; +} + +bool AVOutputFilter::Configure(const std::string& inPort, const std::shared_ptr& upstreamMeta, + Plugin::Meta& upstreamParams, Plugin::Meta& downstreamParams) +{ + AVTRANS_LOGI("DoConfigure"); + return true; +} + +ErrorCode AVOutputFilter::InitPlugin() +{ + AVTRANS_LOGI("InitPlugin"); + OSAL::ScopedLock lock(outputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + return TranslatePluginStatus(plugin_->Init()); +} + +ErrorCode AVOutputFilter::ConfigPlugin() +{ + AVTRANS_LOGI("Configure"); + ErrorCode err = SetPluginParams(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Set Plugin fail!"); + return err; + } + err = SetEventCallBack(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Plugin SetEventCallBack fail!"); + return err; + } + err = SetDataCallBack(); + if (err != ErrorCode::SUCCESS) { + AVTRANS_LOGE("Plugin SetDataCallBack fail!"); + return err; + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::PreparePlugin() +{ + OSAL::ScopedLock lock(outputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_INVALID_PARAMETER_TYPE; + } + return TranslatePluginStatus(plugin_->Prepare()); +} + +ErrorCode AVOutputFilter::PushData(const std::string& inPort, const AVBufferPtr& buffer, int64_t offset) +{ + OSAL::ScopedLock lock(outputFilterMutex_); + if (buffer == nullptr || plugin_ == nullptr) { + AVTRANS_LOGE("buffer or plugin is nullptr!"); + return ErrorCode::ERROR_INVALID_PARAMETER_TYPE; + } + plugin_->PushData(inPort, buffer, offset); + AVTRANS_LOGE("push buffer to plugin."); + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::SetPluginParams() +{ + OSAL::ScopedLock lock(outputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_NULL_POINTER; + } + if (paramsMap_.find(Tag::MEDIA_DESCRIPTION) != paramsMap_.end()) { + plugin_->SetParameter(Tag::MEDIA_DESCRIPTION, paramsMap_[Tag::MEDIA_DESCRIPTION]); + } + if (paramsMap_.find(Tag::AUDIO_CHANNELS) != paramsMap_.end()) { + plugin_->SetParameter(Tag::AUDIO_CHANNELS, paramsMap_[Tag::AUDIO_CHANNELS]); + } + if (paramsMap_.find(Tag::AUDIO_SAMPLE_RATE) != paramsMap_.end()) { + plugin_->SetParameter(Tag::AUDIO_SAMPLE_RATE, paramsMap_[Tag::AUDIO_SAMPLE_RATE]); + } + if (paramsMap_.find(Tag::AUDIO_CHANNEL_LAYOUT) != paramsMap_.end()) { + plugin_->SetParameter(Tag::AUDIO_CHANNEL_LAYOUT, paramsMap_[Tag::AUDIO_CHANNEL_LAYOUT]); + } + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::SetEventCallBack() +{ + OSAL::ScopedLock lock(outputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + plugin_->SetCallback(this); + return ErrorCode::SUCCESS; +} + +ErrorCode AVOutputFilter::SetDataCallBack() +{ + OSAL::ScopedLock lock(outputFilterMutex_); + if (plugin_ == nullptr) { + AVTRANS_LOGE("plugin is nullptr!"); + return ErrorCode::ERROR_INVALID_PARAMETER_VALUE; + } + plugin_->SetDataCallback(std::bind(&AVOutputFilter::OnDataCallback, this, std::placeholders::_1)); + return ErrorCode::SUCCESS; +} + +void AVOutputFilter::OnDataCallback(std::shared_ptr buffer) +{ + OSAL::ScopedLock lock(outputFilterMutex_); + if (buffer == nullptr) { + AVTRANS_LOGE("buffer is nullptr!"); + return; + } + OnEvent(Event{name_, EventType::EVENT_BUFFER_PROGRESS, buffer}); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/filters/av_transport_output/av_transport_output_filter.h b/av_transport/av_trans_engine/filters/av_transport_output/av_transport_output_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..5390ae7902ce8a34d28d8183b7fe4059e046479a --- /dev/null +++ b/av_transport/av_trans_engine/filters/av_transport_output/av_transport_output_filter.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MEDIA_PIPELINE_OUTPUT_FILTER_H +#define MEDIA_PIPELINE_OUTPUT_FILTER_H + +#include +#include + +#include "foundation/osal/utils/util.h" +#include "foundation/utils/constants.h" +#include "pipeline/core/error_code.h" +#include "pipeline/core/filter_base.h" +#include "plugin/common/plugin_video_tags.h" +#include "plugin/core/plugin_manager.h" +#include "pipeline/core/type_define.h" +#include "../../plugin/interface/avtrans_output_plugin.h" +#include "../../plugin/core/avtrans_output.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Pipeline; + +class AVOutputFilter : public FilterBase { +public: + explicit AVOutputFilter(const std::string& name); + ~AVOutputFilter() override; + + std::vector GetWorkModes() override; + ErrorCode SetParameter(int32_t key, const Plugin::Any& value) override; + ErrorCode GetParameter(int32_t key, Plugin::Any& value) override; + ErrorCode Prepare() override; + ErrorCode Start() override; + ErrorCode Stop() override; + ErrorCode Pause() override; + ErrorCode Resume() override; + ErrorCode PushData(const std::string& inPort, const AVBufferPtr& buffer, int64_t offset) override; + bool Negotiate(const std::string& inPort, const std::shared_ptr& upstreamCap, + Plugin::Capability& negotiatedCap, const Plugin::Meta& upstreamParams, + Plugin::Meta& downstreamParams) override; + bool Configure(const std::string& inPort, const std::shared_ptr& upstreamMeta, + Plugin::Meta& upstreamParams, Plugin::Meta& downstreamParams) override; + +private: + void InitPorts() override; + ErrorCode FindPlugin(); + ErrorCode CreatePlugin(const std::shared_ptr& selectedInfo); + ErrorCode InitPlugin(); + ErrorCode ConfigPlugin(); + ErrorCode PreparePlugin(); + ErrorCode SetEventCallBack(); + ErrorCode SetDataCallBack(); + ErrorCode SetPluginParams(); + void OnDataCallback(std::shared_ptr buffer); + + std::shared_ptr plugin_ {nullptr}; + std::shared_ptr pluginInfo_ {nullptr}; + std::unordered_map paramsMap_; + OSAL::Mutex outputFilterMutex_ {}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif \ No newline at end of file diff --git a/av_transport/av_trans_engine/filters/test/BUILD.gn b/av_transport/av_trans_engine/filters/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..43090d382b3c6657ce521de691608a0850a56660 --- /dev/null +++ b/av_transport/av_trans_engine/filters/test/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +group("filter_test") { + testonly = true + + deps = [ + "av_transport_input_filter_test:input_filter_unittest", + "av_transport_output_filter_test:output_filter_unittest", + ] +} diff --git a/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/BUILD.gn b/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..44dba5d1329ddee8b2c9914aa4594edce35b05d9 --- /dev/null +++ b/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/av_transport" + +ohos_unittest("AvTransportInputFilterTest") { + module_out_path = module_out_path + + include_dirs = [ + "${filters_path}/av_transport_input", + "${common_path}/include", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_sync_utils.cpp", + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "${common_path}/src/softbus_channel_adapter.cpp", + "av_transport_input_filter_test.cpp", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + "-Dprotected = public", + ] + cflags_cc = cflags + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"av_transport_input_filter_test\"", + "LOG_DOMAIN=0xD004100", + ] + + deps = [ + "${engine_path}/filters:avtrans_input_filter", + "${plugin_path}/plugins/av_trans_input/dsoftbus_input:plugin_AVTransDsoftbusInput", + "//third_party/googletest:gtest_rtti", + "//third_party/libevdev:libevdev", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] +} + +group("input_filter_unittest") { + testonly = true + + deps = [ ":AvTransportInputFilterTest" ] +} diff --git a/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/av_transport_input_filter_test.cpp b/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/av_transport_input_filter_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45464582a664c409f881ebf8dad0a1660c442998 --- /dev/null +++ b/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/av_transport_input_filter_test.cpp @@ -0,0 +1,382 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_transport_input_filter_test.h" + +#include "av_trans_constants.h" +#include "pipeline/filters/common/plugin_utils.h" +#include "pipeline/factory/filter_factory.h" +#include "plugin/common/plugin_attr_desc.h" +#include "pipeline/core/filter_base.h" +#include "pipeline/core/filter.h" + +using namespace testing::ext; +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace DistributedHardware { +const std::string FILTERNAME = "avinput"; + +void AvTransportInputFilterTest::SetUp() +{ +} + +void AvTransportInputFilterTest::TearDown() +{ +} + +void AvTransportInputFilterTest::SetUpTestCase() +{ +} + +void AvTransportInputFilterTest::TearDownTestCase() +{ +} + +HWTEST_F(AvTransportInputFilterTest, SetParameter_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + int32_t key = -1; + Any value = VideoBitStreamFormat::ANNEXB; + ErrorCode ret = avInputTest_->SetParameter(key, value); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, SetParameter_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + int32_t key = static_cast(Plugin::Tag::MIME); + Any value = MEDIA_MIME_VIDEO_H264; + ErrorCode ret = avInputTest_->SetParameter(key, value); + EXPECT_EQ(ErrorCode::SUCCESS, ret); +} + +HWTEST_F(AvTransportInputFilterTest, GetParameter_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + int32_t key = -1; + Any value = VideoBitStreamFormat::ANNEXB; + ErrorCode ret = avInputTest_->GetParameter(key, value); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, GetParameter_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + int32_t key = static_cast(Plugin::Tag::MIME); + Any value = VideoBitStreamFormat::ANNEXB; + ErrorCode ret = avInputTest_->GetParameter(key, value); + EXPECT_EQ(ErrorCode::SUCCESS, ret); +} + +HWTEST_F(AvTransportInputFilterTest, Prepare_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->Prepare(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_STATE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, Prepare_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + avInputTest_->state_ = FilterState::INITIALIZED; + ErrorCode ret = avInputTest_->Prepare(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, Start_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->Start(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_STATE, ret); + + avInputTest_->state_ = FilterState::READY; + ret = avInputTest_->Start(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); + + avInputTest_->state_ = FilterState::PAUSED; + ret = avInputTest_->Start(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportInputFilterTest, Stop_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->Stop(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_STATE, ret); + + avInputTest_->state_ = FilterState::RUNNING; + ret = avInputTest_->Stop(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); + + avInputTest_->state_ = FilterState::PAUSED; + ret = avInputTest_->Stop(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportInputFilterTest, Pause_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->Pause(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_STATE, ret); + + avInputTest_->state_ = FilterState::PAUSED; + ret = avInputTest_->Pause(); + EXPECT_EQ(ErrorCode::SUCCESS, ret); +} + +HWTEST_F(AvTransportInputFilterTest, Pause_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + avInputTest_->state_ = FilterState::READY; + ErrorCode ret = avInputTest_->Pause(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); + + avInputTest_->state_ = FilterState::RUNNING; + ret = avInputTest_->Pause(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportInputFilterTest, Resume_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->Resume(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); + + avInputTest_->plugin_ = PluginManager::Instance().CreateGenericPlugin("name"); + ret = avInputTest_->Resume(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportInputFilterTest, FindPlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->FindPlugin(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); + + int32_t key = static_cast(Plugin::Tag::MIME); + Any value = MEDIA_MIME_VIDEO_H264; + avInputTest_->SetParameter(key, value); + ret = avInputTest_->FindPlugin(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, DoNegotiate_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + CapabilitySet outCaps; + bool ret = avInputTest_->DoNegotiate(outCaps); + EXPECT_EQ(false, ret); +} + +HWTEST_F(AvTransportInputFilterTest, CreatePlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + std::shared_ptr selectedInfo = nullptr; + ErrorCode ret = avInputTest_->CreatePlugin(selectedInfo); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, CreatePlugin_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + std::shared_ptr selectedInfo = std::make_shared(); + selectedInfo->name = "name"; + ErrorCode ret = avInputTest_->CreatePlugin(selectedInfo); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, CreatePlugin_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + std::shared_ptr selectedInfo = std::make_shared(); + selectedInfo->name = "name"; + avInputTest_->plugin_ = PluginManager::Instance().CreateGenericPlugin("name"); + avInputTest_->pluginInfo_ = std::make_shared(); + avInputTest_->pluginInfo_->name = "name"; + ErrorCode ret = avInputTest_->CreatePlugin(selectedInfo); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, ConfigMeta_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + Plugin::Meta meta; + ErrorCode ret = avInputTest_->ConfigMeta(meta); + EXPECT_EQ(ErrorCode::ERROR_NOT_EXISTED, ret); + + int32_t key = static_cast(Plugin::Tag::MIME); + Any value = MEDIA_MIME_VIDEO_H264; + avInputTest_->SetParameter(key, value); + ret = avInputTest_->ConfigMeta(meta); + EXPECT_EQ(ErrorCode::ERROR_NOT_EXISTED, ret); + + key = static_cast(Plugin::Tag::MEDIA_TYPE); + avInputTest_->SetParameter(key, value); + ret = avInputTest_->ConfigMeta(meta); + EXPECT_EQ(ErrorCode::ERROR_NOT_EXISTED, ret); +} + +HWTEST_F(AvTransportInputFilterTest, ConfigVideoMeta_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + Plugin::Meta meta; + ErrorCode ret = avInputTest_->ConfigVideoMeta(meta); + EXPECT_EQ(ErrorCode::SUCCESS, ret); + + int32_t key = static_cast(Plugin::Tag::VIDEO_WIDTH); + int value = 100; + avInputTest_->SetParameter(key, value); + ret = avInputTest_->ConfigVideoMeta(meta); + EXPECT_EQ(ErrorCode::SUCCESS, ret); + + key = static_cast(Plugin::Tag::VIDEO_HEIGHT); + avInputTest_->SetParameter(key, value); + ret = avInputTest_->ConfigVideoMeta(meta); + EXPECT_EQ(ErrorCode::SUCCESS, ret); + + key = static_cast(Plugin::Tag::MEDIA_BITRATE); + avInputTest_->SetParameter(key, value); + ret = avInputTest_->ConfigVideoMeta(meta); + EXPECT_EQ(ErrorCode::SUCCESS, ret); + + key = static_cast(Plugin::Tag::VIDEO_FRAME_RATE); + avInputTest_->SetParameter(key, value); + ret = avInputTest_->ConfigVideoMeta(meta); + EXPECT_EQ(ErrorCode::SUCCESS, ret); +} + +HWTEST_F(AvTransportInputFilterTest, TransAudioChannelLayout_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + int layoutPtr = 3; + OHOS::Media::Plugin::AudioChannelLayout ret = avInputTest_->TransAudioChannelLayout(layoutPtr); + EXPECT_EQ(OHOS::Media::Plugin::AudioChannelLayout::UNKNOWN, ret); + + layoutPtr = 1; + ret = avInputTest_->TransAudioChannelLayout(layoutPtr); + EXPECT_EQ(OHOS::Media::Plugin::AudioChannelLayout::MONO, ret); +} + +HWTEST_F(AvTransportInputFilterTest, TransAudioSampleFormat_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + int layoutPtr = 5; + OHOS::Media::Plugin::AudioSampleFormat ret = avInputTest_->TransAudioSampleFormat(layoutPtr); + EXPECT_EQ(OHOS::Media::Plugin::AudioSampleFormat::NONE, ret); + + layoutPtr = 1; + ret = avInputTest_->TransAudioSampleFormat(layoutPtr); + EXPECT_EQ(OHOS::Media::Plugin::AudioSampleFormat::S16, ret); +} + +HWTEST_F(AvTransportInputFilterTest, ConfigAudioMeta_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + Plugin::Meta meta; + int32_t key = static_cast(Plugin::Tag::AUDIO_CHANNELS); + uint32_t value = 100; + avInputTest_->SetParameter(key, value); + ErrorCode ret = avInputTest_->ConfigAudioMeta(meta); + EXPECT_EQ(ErrorCode::SUCCESS, ret); +} + +HWTEST_F(AvTransportInputFilterTest, InitPlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + avInputTest_->plugin_ = nullptr; + ErrorCode ret = avInputTest_->InitPlugin(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, ConfigPlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->ConfigPlugin(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportInputFilterTest, SetPluginParams_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->SetPluginParams(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportInputFilterTest, PreparePlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + ErrorCode ret = avInputTest_->PreparePlugin(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportInputFilterTest, PushData_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + std::string inPort; + AVBufferPtr buffer; + int64_t offset = 0; + ErrorCode ret = avInputTest_->PushData(inPort, buffer, offset); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportInputFilterTest, SetEventCallBack_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + avInputTest_->plugin_ = nullptr; + ErrorCode ret = avInputTest_->SetEventCallBack(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportInputFilterTest, SetDataCallBack_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avInputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVINPUT_NAME, FILTERNAME); + std::shared_ptr buffer = nullptr; + avInputTest_->OnDataCallback(buffer); + avInputTest_->plugin_ = nullptr; + ErrorCode ret = avInputTest_->SetDataCallBack(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/av_transport_input_filter_test.h b/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/av_transport_input_filter_test.h new file mode 100644 index 0000000000000000000000000000000000000000..c58ac8470d507f1b7d04fefac31c3d81549034d1 --- /dev/null +++ b/av_transport/av_trans_engine/filters/test/av_transport_input_filter_test/av_transport_input_filter_test.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AV_TRANSPORT_INPUT_FILTER_TEST_H +#define AV_TRANSPORT_INPUT_FILTER_TEST_H + +#include + +#include "av_transport_input_filter.h" +#include "foundation/osal/utils/util.h" +#include "foundation/utils/constants.h" +#include "pipeline/core/error_code.h" +#include "plugin/common/plugin_video_tags.h" +#include "plugin/core/plugin_manager.h" +#include "pipeline/core/type_define.h" + + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Pipeline; + +class AvTransportInputFilterTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // AV_TRANSPORT_INPUT_FILTER_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/BUILD.gn b/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fc5ec098ce0547a4c73a2dd6c23dea1ab850dc65 --- /dev/null +++ b/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/av_transport" + +ohos_unittest("AvTransportOutputFilterTest") { + module_out_path = module_out_path + + include_dirs = [ + "${filters_path}/av_transport_output", + "${common_path}/include", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_sync_utils.cpp", + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "${common_path}/src/softbus_channel_adapter.cpp", + "av_transport_output_filter_test.cpp", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + "-Dprotected = public", + ] + cflags_cc = cflags + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"av_transport_output_filter_test\"", + "LOG_DOMAIN=0xD004100", + ] + + deps = [ + "${engine_path}/filters:avtrans_output_filter", + "${plugin_path}/plugins/av_trans_output/dsoftbus_output_audio:plugin_AVTransDsoftbusOutputAudio", + "//third_party/googletest:gtest_rtti", + "//third_party/libevdev:libevdev", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] +} + +group("output_filter_unittest") { + testonly = true + + deps = [ ":AvTransportOutputFilterTest" ] +} diff --git a/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/av_transport_output_filter_test.cpp b/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/av_transport_output_filter_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eee47e2f655fdd9473315ed392062a3c0692bc59 --- /dev/null +++ b/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/av_transport_output_filter_test.cpp @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_transport_output_filter_test.h" + +#include "av_trans_constants.h" +#include "pipeline/filters/common/plugin_utils.h" +#include "pipeline/factory/filter_factory.h" +#include "plugin/common/plugin_attr_desc.h" + +using namespace testing::ext; +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace DistributedHardware { +const std::string FILTERNAME = "avoutput"; + +void AvTransportOutputFilterTest::SetUp() +{ +} + +void AvTransportOutputFilterTest::TearDown() +{ +} + +void AvTransportOutputFilterTest::SetUpTestCase() +{ +} + +void AvTransportOutputFilterTest::TearDownTestCase() +{ +} + +HWTEST_F(AvTransportOutputFilterTest, SetParameter_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + int32_t key = -1; + Any value = VideoBitStreamFormat::ANNEXB; + ErrorCode ret = avOutputTest_->SetParameter(key, value); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, SetParameter_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + int32_t key = static_cast(Plugin::Tag::MIME); + Any value = MEDIA_MIME_AUDIO_RAW; + ErrorCode ret = avOutputTest_->SetParameter(key, value); + EXPECT_EQ(ErrorCode::SUCCESS, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, SetParameter_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + int32_t key = static_cast(Plugin::Tag::MIME); + Any value = MEDIA_MIME_AUDIO_RAW; + avOutputTest_->plugin_ = PluginManager::Instance().CreateGenericPlugin("name"); + ErrorCode ret = avOutputTest_->SetParameter(key, value); + EXPECT_EQ(ErrorCode::SUCCESS, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, GetParameter_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + int32_t key = -1; + Any value = VideoBitStreamFormat::ANNEXB; + ErrorCode ret = avOutputTest_->GetParameter(key, value); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, GetParameter_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + int32_t key = static_cast(Plugin::Tag::MIME); + Any value = VideoBitStreamFormat::ANNEXB; + ErrorCode ret = avOutputTest_->GetParameter(key, value); + EXPECT_EQ(ErrorCode::SUCCESS, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, Prepare_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + ErrorCode ret = avOutputTest_->Prepare(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_STATE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, Prepare_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + avOutputTest_->state_ = FilterState::INITIALIZED; + ErrorCode ret = avOutputTest_->Prepare(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, Start_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + ErrorCode ret = avOutputTest_->Start(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_STATE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, Start_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + avOutputTest_->state_ = FilterState::READY; + avOutputTest_->plugin_ = nullptr; + ErrorCode ret = avOutputTest_->Start(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, Stop_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + ErrorCode ret = avOutputTest_->Stop(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_STATE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, Stop_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + avOutputTest_->state_ = FilterState::RUNNING; + avOutputTest_->plugin_ = nullptr; + ErrorCode ret = avOutputTest_->Stop(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, FindPlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + ErrorCode ret = avOutputTest_->FindPlugin(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, FindPlugin_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + int32_t key = static_cast(Plugin::Tag::MIME); + Any value = 100; + avOutputTest_->plugin_ = PluginManager::Instance().CreateGenericPlugin("name"); + avOutputTest_->SetParameter(key, value); + ErrorCode ret = avOutputTest_->FindPlugin(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, Negotiate_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + std::string inPort = "inPort_test"; + std::shared_ptr upstreamCap; + Plugin::Capability negotiatedCap; + Plugin::Meta upstreamParams; + Plugin::Meta downstreamParams; + bool ret = avOutputTest_->Negotiate(inPort, upstreamCap, negotiatedCap, upstreamParams, downstreamParams); + EXPECT_EQ(false, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, CreatePlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + std::shared_ptr selectedInfo = nullptr; + ErrorCode ret = avOutputTest_->CreatePlugin(selectedInfo); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, CreatePlugin_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + std::shared_ptr selectedInfo = PluginManager::Instance().GetPluginInfo( + PluginType::GENERIC_PLUGIN, ""); + ErrorCode ret = avOutputTest_->CreatePlugin(selectedInfo); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, InitPlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + avOutputTest_->plugin_ = nullptr; + ErrorCode ret = avOutputTest_->InitPlugin(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, ConfigPlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + ErrorCode ret = avOutputTest_->ConfigPlugin(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, PreparePlugin_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + ErrorCode ret = avOutputTest_->PreparePlugin(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_TYPE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, PushData_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + std::string inPort; + AVBufferPtr buffer; + int64_t offset = 0; + ErrorCode ret = avOutputTest_->PushData(inPort, buffer, offset); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_TYPE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, SetPluginParams_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + ErrorCode ret = avOutputTest_->SetPluginParams(); + EXPECT_EQ(ErrorCode::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, SetEventCallBack_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + ErrorCode ret = avOutputTest_->SetEventCallBack(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, SetEventCallBack_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + avOutputTest_->plugin_ = PluginManager::Instance().CreateGenericPlugin("name"); + ErrorCode ret = avOutputTest_->SetEventCallBack(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, SetDataCallBack_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + std::shared_ptr buffer = nullptr; + avOutputTest_->OnDataCallback(buffer); + + ErrorCode ret = avOutputTest_->SetDataCallBack(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} + +HWTEST_F(AvTransportOutputFilterTest, SetDataCallBack_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr avOutputTest_ = + FilterFactory::Instance().CreateFilterWithType(AVOUTPUT_NAME, FILTERNAME); + std::shared_ptr buffer = nullptr; + avOutputTest_->OnDataCallback(buffer); + + avOutputTest_->plugin_ = PluginManager::Instance().CreateGenericPlugin("name"); + ErrorCode ret = avOutputTest_->SetDataCallBack(); + EXPECT_EQ(ErrorCode::ERROR_INVALID_PARAMETER_VALUE, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/av_transport_output_filter_test.h b/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/av_transport_output_filter_test.h new file mode 100644 index 0000000000000000000000000000000000000000..c3ddbf21c7291cd3be57747743a3af4f02d88e88 --- /dev/null +++ b/av_transport/av_trans_engine/filters/test/av_transport_output_filter_test/av_transport_output_filter_test.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AV_TRANSPORT_OUTPUT_FILTER_TEST_H +#define AV_TRANSPORT_OUTPUT_FILTER_TEST_H + +#include + +#include "av_transport_output_filter.h" +#include "foundation/osal/utils/util.h" +#include "foundation/utils/constants.h" +#include "pipeline/core/error_code.h" +#include "pipeline/core/filter_base.h" +#include "plugin/common/plugin_video_tags.h" +#include "plugin/core/plugin_manager.h" +#include "pipeline/core/type_define.h" + + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Pipeline; + +class AvTransportOutputFilterTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // AV_TRANSPORT_OUTPUT_FILTER_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/core/avtrans_input.cpp b/av_transport/av_trans_engine/plugin/core/avtrans_input.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48908b09cdd99d11b53c762aaf3002c7f53906e6 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/core/avtrans_input.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "avtrans_input.h" + +#include "../interface/avtrans_input_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +AvTransInput::AvTransInput(uint32_t pkgVer, uint32_t apiVer, std::shared_ptr plugin) + : Base(pkgVer, apiVer, plugin), AvTransInputPlugin_(std::move(plugin)) {} + +Status AvTransInput::Pause() +{ + return AvTransInputPlugin_->Pause(); +} + +Status AvTransInput::Resume() +{ + return AvTransInputPlugin_->Resume(); +} + +Status AvTransInput::PushData(const std::string& inPort, std::shared_ptr buffer, int32_t offset) +{ + return AvTransInputPlugin_->PushData(inPort, buffer, offset); +} + +Status AvTransInput::SetDataCallback(std::function)> callback) +{ + return AvTransInputPlugin_->SetDataCallback(callback); +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/core/avtrans_input.h b/av_transport/av_trans_engine/plugin/core/avtrans_input.h new file mode 100644 index 0000000000000000000000000000000000000000..6101ffb2e06cedf78b49c0c92de6ebecf50b817f --- /dev/null +++ b/av_transport/av_trans_engine/plugin/core/avtrans_input.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_PLUGIN_CORE_AVTRANS_INPUT_H +#define HISTREAMER_PLUGIN_CORE_AVTRANS_INPUT_H + +#include +#include +#include + +#include "plugin/core/base.h" +#include "plugin/common/plugin_types.h" + +namespace OHOS { +namespace DistributedHardware { +struct AvTransInputPlugin; + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; + +class AvTransInput : public Base { +public: + AvTransInput(const AvTransInput &) = delete; + AvTransInput operator=(const AvTransInput &) = delete; + ~AvTransInput() override = default; + + Status Pause(); + + Status Resume(); + + Status PushData(const std::string& inPort, std::shared_ptr buffer, int32_t offset); + + Status SetDataCallback(std::function)> callback); + + AvTransInput(uint32_t pkgVer, uint32_t apiVer, std::shared_ptr plugin); + +private: + std::shared_ptr AvTransInputPlugin_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // HISTREAMER_PLUGIN_CORE_AVTRANS_INPUT_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/core/avtrans_output.cpp b/av_transport/av_trans_engine/plugin/core/avtrans_output.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5de623cac8432667b43f7e04c5f8ef63afc4d78 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/core/avtrans_output.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "avtrans_output.h" + +#include "../interface/avtrans_output_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +AvTransOutput::AvTransOutput(uint32_t pkgVer, uint32_t apiVer, std::shared_ptr plugin) + : Base(pkgVer, apiVer, plugin), AvTransOutputPlugin_(std::move(plugin)) {} + +Status AvTransOutput::PushData(const std::string& inPort, std::shared_ptr buffer, int32_t offset) +{ + return AvTransOutputPlugin_->PushData(inPort, buffer, offset); +} + +Status AvTransOutput::SetDataCallback(std::function)> callback) +{ + return AvTransOutputPlugin_->SetDataCallback(callback); +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/core/avtrans_output.h b/av_transport/av_trans_engine/plugin/core/avtrans_output.h new file mode 100644 index 0000000000000000000000000000000000000000..7c3f168926b2cc42372362effd970d8195f0d3f8 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/core/avtrans_output.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_PLUGIN_CORE_AVTRANS_OUTPUT_H +#define HISTREAMER_PLUGIN_CORE_AVTRANS_OUTPUT_H + +#include +#include +#include + +#include "plugin/core/base.h" +#include "plugin/common/plugin_types.h" + +namespace OHOS { +namespace DistributedHardware { +struct AvTransOutputPlugin; + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; + +class AvTransOutput : public Base { +public: + AvTransOutput(const AvTransOutput &) = delete; + AvTransOutput operator=(const AvTransOutput &) = delete; + ~AvTransOutput() override = default; + + Status PushData(const std::string& inPort, std::shared_ptr buffer, int32_t offset); + + Status SetDataCallback(std::function)> callback); + + AvTransOutput(uint32_t pkgVer, uint32_t apiVer, std::shared_ptr plugin); + +private: + std::shared_ptr AvTransOutputPlugin_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // HISTREAMER_PLUGIN_CORE_AVTRANS_OUTPUT_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/interface/avtrans_input_plugin.h b/av_transport/av_trans_engine/plugin/interface/avtrans_input_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..45bb9c8551a1e1f0f27d082bf1491fe67f20a372 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/interface/avtrans_input_plugin.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_PLUGIN_INTF_AVTRANS_INPUT_PLUGIN_H +#define HISTREAMER_PLUGIN_INTF_AVTRANS_INPUT_PLUGIN_H + +#include +#include + +#include "plugin/common/media_source.h" +#include "plugin/common/plugin_source_tags.h" +#include "plugin/common/plugin_buffer.h" +#include "plugin/common/plugin_caps.h" +#include "plugin/interface/plugin_base.h" +#include "plugin/interface/plugin_definition.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; + +struct AvTransInputPlugin : public PluginBase { +explicit AvTransInputPlugin(std::string name): PluginBase(std::move(name)) {} + +virtual OHOS::Media::Plugin::Status Pause() = 0; + +virtual OHOS::Media::Plugin::Status Resume() = 0; + +virtual OHOS::Media::Plugin::Status PushData(const std::string& inPort, std::shared_ptr buffer, + int32_t offset) = 0; + +virtual OHOS::Media::Plugin::Status SetDataCallback(std::function)> callback) = 0; +}; + +/// Avtrans input plugin api major number. +#define AVTRANS_INPUT_API_VERSION_MAJOR (1) + +/// Avtrans input plugin api minor number +#define AVTRANS_INPUT_API_VERSION_MINOR (0) + +/// Avtrans input plugin version +#define AVTRANS_INPUT_API_VERSION MAKE_VERSION(AVTRANS_INPUT_API_VERSION_MAJOR, AVTRANS_INPUT_API_VERSION_MINOR) + +} // namespace DistributedHardware +} // namespace OHOS +#endif \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/interface/avtrans_output_plugin.h b/av_transport/av_trans_engine/plugin/interface/avtrans_output_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..ae8301bb8af535e6e2b81fcf16b5c8c6ba9c10db --- /dev/null +++ b/av_transport/av_trans_engine/plugin/interface/avtrans_output_plugin.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_PLUGIN_INTF_AVTRANS_OUTPUT_PLUGIN_H +#define HISTREAMER_PLUGIN_INTF_AVTRANS_OUTPUT_PLUGIN_H + +#include +#include + +#include "plugin/common/media_source.h" +#include "plugin/common/plugin_source_tags.h" +#include "plugin/common/plugin_buffer.h" +#include "plugin/common/plugin_caps.h" +#include "plugin/interface/plugin_base.h" +#include "plugin/interface/plugin_definition.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; + +struct AvTransOutputPlugin : public PluginBase { +explicit AvTransOutputPlugin(std::string name): PluginBase(std::move(name)) {} + +virtual OHOS::Media::Plugin::Status PushData(const std::string& inPort, std::shared_ptr buffer, + int32_t offset) = 0; + +virtual OHOS::Media::Plugin::Status SetDataCallback(std::function)> callback) = 0; +}; + +/// Avtrans output plugin api major number. +#define AVTRANS_OUTPUT_API_VERSION_MAJOR (1) + +/// Avtrans output plugin api minor number +#define AVTRANS_OUTPUT_API_VERSION_MINOR (0) + +/// Avtrans output plugin version +#define AVTRANS_OUTPUT_API_VERSION MAKE_VERSION(AVTRANS_OUTPUT_API_VERSION_MAJOR, AVTRANS_OUTPUT_API_VERSION_MINOR) + +} // namespace DistributedHardware +} // namespace OHOS +#endif \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..aae9560b016d5153921d8e7bed5b15688ccc8339 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +config("avtrans_cflags") { + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Wno-unused-but-set-variable", + "-Wno-format", + ] + cflags_cc = cflags +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8fdc22b1e293e7f811a01af35331a59cce34dee3 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("plugin_AVTransDaudioInput") { + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "//third_party/json/include", + ] + + sources = [ "daudio_input_plugin.cpp" ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_configs = [ "${plugin_path}/plugins:avtrans_cflags" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"daudio_input_plugin\"", + "LOG_DOMAIN=0xD004100", + ] + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/daudio_input_plugin.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/daudio_input_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4044de0a9cfcc732310dbb9e3c3064875baea71f --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/daudio_input_plugin.cpp @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "daudio_input_plugin.h" + +#include "foundation/utils/constants.h" +#include "plugin/common/plugin_caps_builder.h" +#include "plugin/factory/plugin_factory.h" +#include "plugin/interface/generic_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +GenericPluginDef CreateDaudioInputPluginDef() +{ + GenericPluginDef definition; + definition.name = "AVTransDaudioInputPlugin"; + definition.pkgName = "AVTransDaudioInputPlugin"; + definition.description = "Audio transport from daudio service"; + definition.rank = PLUGIN_RANK; + definition.creator = [] (const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + + definition.pkgVersion = AVTRANS_INPUT_API_VERSION; + definition.license = LicenseType::APACHE_V2; + + CapabilityBuilder capBuilder; + capBuilder.SetMime(OHOS::Media::MEDIA_MIME_AUDIO_RAW); + DiscreteCapability values = {8000, 11025, 12000, 16000, + 22050, 24000, 32000, 44100, 48000, 64000, 96000}; + capBuilder.SetAudioSampleRateList(values); + definition.outCaps.push_back(capBuilder.Build()); + return definition; +} + +static AutoRegisterPlugin g_registerPluginHelper(CreateDaudioInputPluginDef()); + +DaudioInputPlugin::DaudioInputPlugin(std::string name) + : AvTransInputPlugin(std::move(name)) +{ + AVTRANS_LOGI("DaudioInputPlugin ctor."); +} + +DaudioInputPlugin::~DaudioInputPlugin() +{ + AVTRANS_LOGI("DaudioInputPlugin dtor."); +} + +Status DaudioInputPlugin::Init() +{ + AVTRANS_LOGI("Init enter."); + frameNumber_.store(0); + return Status::OK; +} + +Status DaudioInputPlugin::Deinit() +{ + AVTRANS_LOGI("Deinit enter."); + return Reset(); +} + +Status DaudioInputPlugin::Reset() +{ + AVTRANS_LOGI("Reset enter."); + Media::OSAL::ScopedLock lock(operationMutes_); + tagMap_.clear(); + frameNumber_.store(0); + return Status::OK; +} + +Status DaudioInputPlugin::Pause() +{ + AVTRANS_LOGI("Pause enter."); + Media::OSAL::ScopedLock lock(operationMutes_); + if ((sharedMemory_.fd > 0) && (sharedMemory_.size > 0) && !sharedMemory_.name.empty()) { + ResetSharedMemory(sharedMemory_); + } + return Status::OK; +} + +Status DaudioInputPlugin::Resume() +{ + AVTRANS_LOGI("Resume enter."); + return Status::OK; +} + +Status DaudioInputPlugin::GetParameter(Tag tag, ValueType &value) +{ + { + Media::OSAL::ScopedLock lock(operationMutes_); + auto iter = tagMap_.find(tag); + if (iter != tagMap_.end()) { + value = iter->second; + return Status::OK; + } + } + return Status::ERROR_NOT_EXISTED; +} + +Status DaudioInputPlugin::SetParameter(Tag tag, const ValueType &value) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + tagMap_.insert(std::make_pair(tag, value)); + if (tag == Plugin::Tag::USER_SHARED_MEMORY_FD) { + sharedMemory_ = UnmarshalSharedMemory(Media::Plugin::AnyCast(value)); + } + return Status::OK; +} + +Status DaudioInputPlugin::PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + TRUE_RETURN_V(buffer == nullptr, Status::ERROR_NULL_POINTER); + + if (buffer->IsEmpty()) { + AVTRANS_LOGE("bufferData is Empty."); + return Status::ERROR_INVALID_PARAMETER; + } + + auto bufferMeta = buffer->GetBufferMeta(); + TRUE_RETURN_V(bufferMeta == nullptr, Status::ERROR_NULL_POINTER); + if (bufferMeta->GetType() != BufferMetaType::AUDIO) { + AVTRANS_LOGE("bufferMeta is wrong."); + return Status::ERROR_INVALID_PARAMETER; + } + + ++frameNumber_; + buffer->pts = GetCurrentTime(); + bufferMeta->SetMeta(Tag::USER_FRAME_PTS, buffer->pts); + bufferMeta->SetMeta(Tag::USER_FRAME_NUMBER, frameNumber_.load()); + AVTRANS_LOGI("Push audio buffer pts: %ld, bufferLen: %d, indexNumber: %zu.", + buffer->pts, buffer->GetMemory()->GetSize(), + Plugin::AnyCast(buffer->GetBufferMeta()->GetMeta(Tag::USER_FRAME_NUMBER))); + + if ((sharedMemory_.fd > 0) && (sharedMemory_.size > 0) && !sharedMemory_.name.empty()) { + WriteFrameInfoToMemory(sharedMemory_, frameNumber_.load(), buffer->pts); + } + + return Status::OK; +} + +Status DaudioInputPlugin::SetCallback(Callback *cb) +{ + (void)cb; + return Status::OK; +} + +Status DaudioInputPlugin::SetDataCallback(AVDataCallback callback) +{ + (void)callback; + return Status::OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/daudio_input_plugin.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/daudio_input_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..3596e47091a95b42e35f85e80d976a732494ba29 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/daudio_input/daudio_input_plugin.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DAUDIO_H +#define OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DAUDIO_H + +#include +#include +#include +#include + +#include "av_sync_utils.h" +#include "av_trans_buffer.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_input_plugin.h" +#include "foundation/osal/thread/mutex.h" +#include "foundation/osal/thread/scoped_lock.h" +#include "foundation/osal/thread/task.h" +#include "nlohmann/json.hpp" +#include "plugin_manager.h" +#include "plugin_types.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; + +using json = nlohmann::json; +using AVDataCallback = std::function)>; + +class DaudioInputPlugin : public AvTransInputPlugin { +public: + explicit DaudioInputPlugin(std::string name); + ~DaudioInputPlugin(); + + Status Init() override; + Status Deinit() override; + Status Reset() override; + Status Pause() override; + Status Resume() override; + Status GetParameter(Tag tag, ValueType &value) override; + Status SetParameter(Tag tag, const ValueType &value) override; + Status PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) override; + Status SetCallback(Callback *cb) override; + Status SetDataCallback(AVDataCallback callback) override; + +private: + std::atomic frameNumber_; + std::map tagMap_; + OSAL::Mutex operationMutes_ {}; + AVTransSharedMemory sharedMemory_ = AVTransSharedMemory{ 0, 0, "" }; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DAUDIO_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..17fa914fd62f9805b1e4ca07867273024a5680b9 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("plugin_AVTransDscreenInput") { + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "//third_party/json/include", + ] + + sources = [ "dscreen_input_plugin.cpp" ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_configs = [ "${plugin_path}/plugins:avtrans_cflags" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dscreen_input_plugin\"", + "LOG_DOMAIN=0xD004100", + ] + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/dscreen_input_plugin.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/dscreen_input_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01f96f5f043372fa774dafc223a3090bfd2035cb --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/dscreen_input_plugin.cpp @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dscreen_input_plugin.h" + +#include "av_trans_utils.h" +#include "foundation/utils/constants.h" +#include "nlohmann/json.hpp" +#include "plugin/factory/plugin_factory.h" +#include "plugin/interface/generic_plugin.h" + +namespace OHOS { +namespace DistributedHardware { +using json = nlohmann::json; + +GenericPluginDef CreateDscreenInputPluginDef() +{ + GenericPluginDef definition; + definition.name = "AVTransDscreenInputPlugin"; + definition.pkgName = "AVTransDscreenInputPlugin"; + definition.description = "Video transport from dscreen service"; + definition.rank = PLUGIN_RANK; + definition.creator = [] (const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + + definition.pkgVersion = AVTRANS_INPUT_API_VERSION; + definition.license = LicenseType::APACHE_V2; + + Capability outCap(Media::MEDIA_MIME_VIDEO_RAW); + outCap.AppendDiscreteKeys( + Capability::Key::VIDEO_PIXEL_FORMAT, {VideoPixelFormat::RGBA}); + definition.outCaps.push_back(outCap); + return definition; +} + +static AutoRegisterPlugin g_registerPluginHelper(CreateDscreenInputPluginDef()); + +DscreenInputPlugin::DscreenInputPlugin(std::string name) + : AvTransInputPlugin(std::move(name)) +{ + AVTRANS_LOGI("ctor."); +} + +DscreenInputPlugin::~DscreenInputPlugin() +{ + AVTRANS_LOGI("dtor."); +} + +Status DscreenInputPlugin::Init() +{ + AVTRANS_LOGI("Init."); + frameNumber_.store(0); + return Status::OK; +} + +Status DscreenInputPlugin::Deinit() +{ + AVTRANS_LOGI("Deinit."); + return Reset(); +} + +Status DscreenInputPlugin::Reset() +{ + AVTRANS_LOGI("Reset"); + Media::OSAL::ScopedLock lock(operationMutes_); + paramsMap_.clear(); + frameNumber_.store(0); + return Status::OK; +} + +Status DscreenInputPlugin::Pause() +{ + AVTRANS_LOGD("Pause not supported."); + return Status::OK; +} + +Status DscreenInputPlugin::Resume() +{ + AVTRANS_LOGD("Resume not supported."); + return Status::OK; +} + +Status DscreenInputPlugin::GetParameter(Tag tag, ValueType &value) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + auto res = paramsMap_.find(tag); + if (res != paramsMap_.end()) { + value = res->second; + return Status::OK; + } + return Status::ERROR_NOT_EXISTED; +} + +Status DscreenInputPlugin::SetParameter(Tag tag, const ValueType &value) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + paramsMap_.insert(std::pair(tag, value)); + if (tag == Plugin::Tag::USER_SHARED_MEMORY_FD) { + sharedMemory_ = UnmarshalSharedMemory(Media::Plugin::AnyCast(value)); + } + return Status::OK; +} + +Status DscreenInputPlugin::PushData(const std::string& inPort, std::shared_ptr buffer, int32_t offset) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (!buffer || buffer->IsEmpty()) { + AVTRANS_LOGE("buffer is nullptr or empty."); + return Status::ERROR_NULL_POINTER; + } + + auto bufferMeta = buffer->GetBufferMeta(); + if (!bufferMeta || bufferMeta->GetType() != BufferMetaType::VIDEO) { + AVTRANS_LOGE("bufferMeta is nullptr or empty."); + return Status::ERROR_NULL_POINTER; + } + + ++frameNumber_; + bufferMeta->SetMeta(Tag::USER_FRAME_NUMBER, frameNumber_.load()); + AVTRANS_LOGI("Push video buffer pts: %ld, bufferLen: %d, frameNumber: %zu.", + buffer->pts, buffer->GetMemory()->GetSize(), + Plugin::AnyCast(bufferMeta->GetMeta(Tag::USER_FRAME_NUMBER))); + + if ((sharedMemory_.fd > 0) && (sharedMemory_.size > 0) && !sharedMemory_.name.empty()) { + int64_t audioTimestamp = 0; + uint32_t audioFrameNum = 0; + int32_t ret = ReadFrameInfoFromMemory(sharedMemory_, audioFrameNum, audioTimestamp); + if ((ret == DH_AVT_SUCCESS) && (audioFrameNum > 0) && (audioTimestamp > 0)) { + bufferMeta->SetMeta(Tag::MEDIA_START_TIME, audioTimestamp); + bufferMeta->SetMeta(Tag::AUDIO_SAMPLE_PER_FRAME, audioFrameNum); + } + } + + return Status::OK; +} + +Status DscreenInputPlugin::SetCallback(Callback *cb) +{ + AVTRANS_LOGI("SetCallBack."); + return Status::OK; +} + +Status DscreenInputPlugin::SetDataCallback(AVDataCallback callback) +{ + AVTRANS_LOGI("SetDataCallback."); + return Status::OK; +} + +} +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/dscreen_input_plugin.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/dscreen_input_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..f8b8f110ceaf5ef5598e2cc0ec9cd7ad3841f0e2 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dscreen_input/dscreen_input_plugin.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DSRCEEN_H +#define OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DSRCEEN_H + +#include +#include +#include +#include + +#include "av_sync_utils.h" +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "avtrans_input_plugin.h" +#include "foundation/osal/thread/task.h" +#include "plugin_types.h" +#include "plugin_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace Media::Plugin; +using AVDataCallback = std::function)>; + +class DscreenInputPlugin : public AvTransInputPlugin { +public: + explicit DscreenInputPlugin(std::string name); + ~DscreenInputPlugin(); + + Status Init() override; + Status Deinit() override; + Status Reset() override; + Status Pause() override; + Status Resume() override; + Status GetParameter(Tag tag, ValueType &value) override; + Status SetParameter(Tag tag, const ValueType &value) override; + Status PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) override; + Status SetCallback(Callback *cb) override; + Status SetDataCallback(AVDataCallback callback) override; + +private: + std::atomic frameNumber_; + Media::OSAL::Mutex operationMutes_ {}; + std::map paramsMap_; + AVTransSharedMemory sharedMemory_ = AVTransSharedMemory{ 0, 0, "" }; +}; + +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DSRCEEN_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e96e3168bba8832af80cc6a8afc292bc7aeb1577 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("plugin_AVTransDsoftbusInput") { + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${dsoftbus_path}/interfaces/kits/transport", + "${dsoftbus_path}/interfaces/kits/bus_center", + "${dsoftbus_path}/interfaces/kits/common", + "//third_party/json/include", + ] + + sources = [ "dsoftbus_input_plugin.cpp" ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_configs = [ "${plugin_path}/plugins:avtrans_cflags" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dsoftbus_input_video_plugin\"", + "LOG_DOMAIN=0xD004100", + ] + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/dsoftbus_input_plugin.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/dsoftbus_input_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1555cf0c3a07c9a43b6731d3c89b23901d0150fe --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/dsoftbus_input_plugin.cpp @@ -0,0 +1,327 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dsoftbus_input_plugin.h" + +#include "foundation/utils/constants.h" +#include "plugin/common/share_memory.h" +#include "plugin/common/plugin_caps_builder.h" +#include "plugin/factory/plugin_factory.h" +#include "plugin/interface/generic_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +std::vector CreateDsoftbusInputPluginDef() +{ + int32_t capNum = 2; + std::vector definitionList; + for (int i = 0; i < capNum; i++) { + GenericPluginDef definition; + definition.name = "AVTransDsoftbusInputPlugin_H264"; + definition.pkgName = "AVTransDsoftbusInputPlugin"; + definition.description = "Video transport from dsoftbus"; + definition.rank = PLUGIN_RANK; + definition.creator = [] (const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + + definition.pkgVersion = AVTRANS_INPUT_API_VERSION; + definition.license = LicenseType::APACHE_V2; + + CapabilityBuilder capBuilder; + capBuilder.SetMime(Media::MEDIA_MIME_VIDEO_H264); + if (i == 1) { + definition.name = "AVTransDsoftbusInputPlugin_H265"; + capBuilder.SetMime(Media::MEDIA_MIME_VIDEO_H265); + } + definition.outCaps.push_back(capBuilder.Build()); + definitionList.push_back(definition); + } + return definitionList; +} + +static AutoRegisterPlugin g_registerPluginHelper(CreateDsoftbusInputPluginDef()); + +DsoftbusInputPlugin::DsoftbusInputPlugin(std::string name) + : AvTransInputPlugin(std::move(name)) +{ + AVTRANS_LOGI("ctor"); +} + +DsoftbusInputPlugin::~DsoftbusInputPlugin() +{ + AVTRANS_LOGI("dtor"); +} + +Status DsoftbusInputPlugin::Init() +{ + AVTRANS_LOGI("Init"); + Media::OSAL::ScopedLock lock(operationMutes_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DsoftbusInputPlugin::Deinit() +{ + AVTRANS_LOGI("Deinit"); + return Reset(); +} + +Status DsoftbusInputPlugin::Prepare() +{ + AVTRANS_LOGI("Prepare"); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::INITIALIZED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + + sessionName_ = ownerName_ + "_" + RECEIVER_DATA_SESSION_NAME_SUFFIX; + int32_t ret = SoftbusChannelAdapter::GetInstance().CreateChannelServer(TransName2PkgName(ownerName_), sessionName_); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Create Session Server failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, peerDevId_, this); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Register channel listener failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + + if (!bufferPopTask_) { + bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + bufferPopTask_->RegisterHandler([this] { HandleData(); }); + } + state_ = State::PREPARED; + return Status::OK; +} + +Status DsoftbusInputPlugin::Reset() +{ + AVTRANS_LOGI("Reset"); + Media::OSAL::ScopedLock lock(operationMutes_); + eventsCb_ = nullptr; + dataCb_ = nullptr; + paramsMap_.clear(); + if (bufferPopTask_) { + bufferPopTask_->Stop(); + bufferPopTask_.reset(); + } + DataQueueClear(dataQueue_); + SoftbusChannelAdapter::GetInstance().RemoveChannelServer(TransName2PkgName(ownerName_), sessionName_); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(sessionName_, peerDevId_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DsoftbusInputPlugin::Start() +{ + AVTRANS_LOGI("Start"); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::PREPARED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + DataQueueClear(dataQueue_); + bufferPopTask_->Start(); + state_ = State::RUNNING; + return Status::OK; +} + +Status DsoftbusInputPlugin::Stop() +{ + AVTRANS_LOGI("Stop"); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::RUNNING) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + state_ = State::PREPARED; + bufferPopTask_->Stop(); + DataQueueClear(dataQueue_); + return Status::OK; +} + +Status DsoftbusInputPlugin::Pause() +{ + AVTRANS_LOGD("Pause not supported."); + return Status::OK; +} + +Status DsoftbusInputPlugin::Resume() +{ + AVTRANS_LOGD("Resume not supported."); + return Status::OK; +} + +Status DsoftbusInputPlugin::GetParameter(Tag tag, ValueType &value) +{ + auto res = paramsMap_.find(tag); + if (res != paramsMap_.end()) { + value = res->second; + return Status::OK; + } + return Status::ERROR_NOT_EXISTED; +} + +Status DsoftbusInputPlugin::SetParameter(Tag tag, const ValueType &value) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (tag == Tag::MEDIA_DESCRIPTION) { + ParseChannelDescription(Plugin::AnyCast(value), ownerName_, peerDevId_); + } + paramsMap_.insert(std::pair(tag, value)); + return Status::OK; +} + +Status DsoftbusInputPlugin::SetCallback(Callback *cb) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (cb == nullptr) { + AVTRANS_LOGE("SetCallBack failed, callback is nullptr."); + return Status::ERROR_NULL_POINTER; + } + eventsCb_ = cb; + AVTRANS_LOGI("SetCallBack success."); + return Status::OK; +} + +Status DsoftbusInputPlugin::SetDataCallback(AVDataCallback callback) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + dataCb_ = callback; + AVTRANS_LOGI("SetDataCallback success."); + return Status::OK; +} + +void DsoftbusInputPlugin::OnChannelEvent(const AVTransEvent &event) +{ + AVTRANS_LOGI("OnChannelEvent enter, event type: %d", event.type); + if (eventsCb_ == nullptr) { + AVTRANS_LOGE("OnChannelEvent failed, event callback is nullptr."); + return; + } + switch (event.type) { + case EventType::EVENT_CHANNEL_OPENED: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_OPENED}); + break; + } + case EventType::EVENT_CHANNEL_OPEN_FAIL: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_OPEN_FAIL}); + break; + } + case EventType::EVENT_CHANNEL_CLOSED: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_CLOSED}); + break; + } + default: + AVTRANS_LOGE("Unsupported event type."); + } +} + +void DsoftbusInputPlugin::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + std::string message(reinterpret_cast(ext->buf), ext->bufLen); + AVTRANS_LOGI("Receive message : %s", message.c_str()); + + json resMsg = json::parse(message, nullptr, false); + TRUE_RETURN(resMsg.is_discarded(), "The resMsg parse failed"); + TRUE_RETURN(!IsUInt32(resMsg, AVT_DATA_META_TYPE), "invalid data type"); + uint32_t metaType = resMsg[AVT_DATA_META_TYPE]; + + auto buffer = CreateBuffer(metaType, data, resMsg); + if (buffer != nullptr) { + DataEnqueue(buffer); + } +} + +std::shared_ptr DsoftbusInputPlugin::CreateBuffer(uint32_t metaType, + const StreamData *data, const json &resMsg) +{ + auto buffer = Buffer::CreateDefaultBuffer(static_cast(metaType), data->bufLen); + auto bufData = buffer->GetMemory(); + + auto writeSize = bufData->Write(reinterpret_cast(data->buf), data->bufLen, 0); + if (static_cast(writeSize) != data->bufLen) { + AVTRANS_LOGE("write buffer data failed."); + return buffer; + } + + auto meta = std::make_shared(); + if (!meta->UnmarshalVideoMeta(resMsg[AVT_DATA_PARAM])) { + AVTRANS_LOGE("Unmarshal video buffer eta failed."); + return nullptr; + } + buffer->pts = meta->pts_; + buffer->GetBufferMeta()->SetMeta(Tag::USER_FRAME_NUMBER, meta->frameNum_); + if ((meta->extFrameNum_ > 0) && (meta->extPts_ > 0)) { + buffer->GetBufferMeta()->SetMeta(Tag::MEDIA_START_TIME, meta->extPts_); + buffer->GetBufferMeta()->SetMeta(Tag::AUDIO_SAMPLE_PER_FRAME, meta->extFrameNum_); + } + AVTRANS_LOGI("buffer pts: %ld, bufferLen: %zu, frameNumber: %zu", buffer->pts, buffer->GetMemory()->GetSize(), + meta->frameNum_); + return buffer; +} + +void DsoftbusInputPlugin::DataEnqueue(std::shared_ptr &buffer) +{ + while (dataQueue_.size() >= DATA_QUEUE_MAX_SIZE) { + AVTRANS_LOGE("Data queue overflow."); + dataQueue_.pop(); + } + dataQueue_.push(buffer); + dataCond_.notify_all(); +} + +void DsoftbusInputPlugin::HandleData() +{ + while (state_ == State::RUNNING) { + std::shared_ptr buffer; + { + std::unique_lock lock(dataQueueMtx_); + dataCond_.wait_for(lock, std::chrono::milliseconds(PLUGIN_TASK_WAIT_TIME), + [this]() { return !dataQueue_.empty(); }); + if (state_ != State::RUNNING) { + return; + } + if (dataQueue_.empty()) { + continue; + } + buffer = dataQueue_.front(); + dataQueue_.pop(); + } + if (buffer == nullptr) { + AVTRANS_LOGE("Data is null"); + continue; + } + dataCb_(buffer); + } +} + +void DsoftbusInputPlugin::DataQueueClear(std::queue> &queue) +{ + std::queue> empty; + swap(empty, queue); +} + +Status DsoftbusInputPlugin::PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) +{ + (void) buffer; + AVTRANS_LOGI("Push Data"); + return Status::OK; +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/dsoftbus_input_plugin.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/dsoftbus_input_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..9970d000025724c7e1046c1f3c367e0cb52d1b07 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input/dsoftbus_input_plugin.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DSOFTBUS_H +#define OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DSOFTBUS_H + +#include +#include +#include +#include +#include +#include +#include + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_input_plugin.h" +#include "nlohmann/json.hpp" +#include "foundation/osal/thread/task.h" +#include "plugin_types.h" +#include "plugin_manager.h" +#include "softbus_channel_adapter.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace Media::Plugin; + +using json = nlohmann::json; +using AVDataCallback = std::function)>; + +class DsoftbusInputPlugin : public AvTransInputPlugin, + public ISoftbusChannelListener, + public std::enable_shared_from_this { +public: + explicit DsoftbusInputPlugin(std::string name); + ~DsoftbusInputPlugin(); + + Status Init() override; + Status Deinit() override; + Status Prepare() override; + Status Reset() override; + Status Start() override; + Status Stop() override; + Status Pause() override; + Status Resume() override; + Status GetParameter(Tag tag, ValueType &value) override; + Status SetParameter(Tag tag, const ValueType &value) override; + Status PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) override; + Status SetCallback(Callback *cb) override; + Status SetDataCallback(AVDataCallback callback) override; + + // interface from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + +private: + void HandleData(); + void DataEnqueue(std::shared_ptr &buffer); + void DataQueueClear(std::queue> &queue); + std::shared_ptr CreateBuffer(uint32_t metaType, const StreamData *data, const json &resMsg); + +private: + std::string ownerName_; + std::string sessionName_; + std::string peerDevId_; + std::condition_variable dataCond_; + std::shared_ptr bufferPopTask_; + std::mutex dataQueueMtx_; + Media::OSAL::Mutex operationMutes_ {}; + std::queue> dataQueue_; + std::map paramsMap_; + State state_ {State::CREATED}; + Callback* eventsCb_ = nullptr; + AVDataCallback dataCb_; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSOFTBUS_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..60a75ea3e89694008d3aa67e452a52bd0327013e --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("plugin_AVTransDsoftbusInputAudio") { + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${dsoftbus_path}/interfaces/kits/transport", + "${dsoftbus_path}/interfaces/kits/bus_center", + "${dsoftbus_path}/interfaces/kits/common", + "//third_party/json/include", + ] + + sources = [ "dsoftbus_input_audio_plugin.cpp" ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_configs = [ "${plugin_path}/plugins:avtrans_cflags" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dsoftbus_input_audio_plugin\"", + "LOG_DOMAIN=0xD004100", + ] + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/dsoftbus_input_audio_plugin.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/dsoftbus_input_audio_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b117ba4e0a66bacfdb545467235c9f3318e8b58b --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/dsoftbus_input_audio_plugin.cpp @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dsoftbus_input_audio_plugin.h" + +#include "foundation/utils/constants.h" +#include "plugin/common/share_memory.h" +#include "plugin/common/plugin_caps_builder.h" +#include "plugin/factory/plugin_factory.h" +#include "plugin/interface/generic_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +GenericPluginDef CreateDsoftbusInputAudioPluginDef() +{ + GenericPluginDef definition; + definition.name = "AVTransDsoftbusInputAudioPlugin"; + definition.pkgName = "AVTransDsoftbusInputAudioPlugin"; + definition.description = "Audio transport from dsoftbus"; + definition.rank = PLUGIN_RANK; + definition.creator = [] (const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + + definition.pkgVersion = AVTRANS_INPUT_API_VERSION; + definition.license = LicenseType::APACHE_V2; + + CapabilityBuilder capBuilder; + capBuilder.SetMime(OHOS::Media::MEDIA_MIME_AUDIO_AAC); + DiscreteCapability values = {8000, 11025, 12000, 16000, + 22050, 24000, 32000, 44100, 48000, 64000, 96000}; + capBuilder.SetAudioSampleRateList(values); + definition.outCaps.push_back(capBuilder.Build()); + return definition; +} + +static AutoRegisterPlugin g_registerPluginHelper(CreateDsoftbusInputAudioPluginDef()); + +DsoftbusInputAudioPlugin::DsoftbusInputAudioPlugin(std::string name) + : AvTransInputPlugin(std::move(name)) +{ + AVTRANS_LOGI("ctor"); +} + +DsoftbusInputAudioPlugin::~DsoftbusInputAudioPlugin() +{ + AVTRANS_LOGI("dtor"); +} + +Status DsoftbusInputAudioPlugin::Init() +{ + AVTRANS_LOGI("Init"); + Media::OSAL::ScopedLock lock(operationMutes_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::Deinit() +{ + AVTRANS_LOGI("Deinit"); + return Reset(); +} + +Status DsoftbusInputAudioPlugin::Prepare() +{ + AVTRANS_LOGI("Prepare"); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::INITIALIZED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + + sessionName_ = ownerName_ + "_" + RECEIVER_DATA_SESSION_NAME_SUFFIX; + int32_t ret = SoftbusChannelAdapter::GetInstance().CreateChannelServer(TransName2PkgName(ownerName_), sessionName_); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Create Session Server failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, peerDevId_, this); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Register channel listener failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + + if (!bufferPopTask_) { + bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + bufferPopTask_->RegisterHandler([this] { HandleData(); }); + } + state_ = State::PREPARED; + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::Reset() +{ + AVTRANS_LOGI("Reset"); + Media::OSAL::ScopedLock lock(operationMutes_); + eventsCb_ = nullptr; + dataCb_ = nullptr; + paramsMap_.clear(); + if (bufferPopTask_) { + bufferPopTask_->Stop(); + bufferPopTask_.reset(); + } + DataQueueClear(dataQueue_); + SoftbusChannelAdapter::GetInstance().RemoveChannelServer(TransName2PkgName(ownerName_), sessionName_); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(sessionName_, peerDevId_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::Start() +{ + AVTRANS_LOGI("Start"); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::PREPARED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + DataQueueClear(dataQueue_); + bufferPopTask_->Start(); + state_ = State::RUNNING; + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::Stop() +{ + AVTRANS_LOGI("Stop"); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::RUNNING) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + state_ = State::PREPARED; + bufferPopTask_->Stop(); + DataQueueClear(dataQueue_); + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::Pause() +{ + AVTRANS_LOGD("Pause not supported."); + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::Resume() +{ + AVTRANS_LOGD("Resume not supported."); + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::GetParameter(Tag tag, ValueType &value) +{ + auto res = paramsMap_.find(tag); + if (res != paramsMap_.end()) { + value = res->second; + return Status::OK; + } + return Status::ERROR_NOT_EXISTED; +} + +Status DsoftbusInputAudioPlugin::SetParameter(Tag tag, const ValueType &value) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (tag == Tag::MEDIA_DESCRIPTION) { + ParseChannelDescription(Plugin::AnyCast(value), ownerName_, peerDevId_); + } + paramsMap_.insert(std::pair(tag, value)); + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::SetCallback(Callback *cb) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (cb == nullptr) { + AVTRANS_LOGE("SetCallBack failed, callback is nullptr."); + return Status::ERROR_NULL_POINTER; + } + eventsCb_ = cb; + AVTRANS_LOGI("SetCallBack success."); + return Status::OK; +} + +Status DsoftbusInputAudioPlugin::SetDataCallback(AVDataCallback callback) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + dataCb_ = callback; + AVTRANS_LOGI("SetDataCallback success."); + return Status::OK; +} + +void DsoftbusInputAudioPlugin::OnChannelEvent(const AVTransEvent &event) +{ + AVTRANS_LOGI("OnChannelEvent enter, event type: %d", event.type); + if (eventsCb_ == nullptr) { + AVTRANS_LOGE("OnChannelEvent failed, event callback is nullptr."); + return; + } + switch (event.type) { + case EventType::EVENT_CHANNEL_OPENED: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_OPENED}); + break; + } + case EventType::EVENT_CHANNEL_OPEN_FAIL: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_OPEN_FAIL}); + break; + } + case EventType::EVENT_CHANNEL_CLOSED: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_CLOSED}); + break; + } + default: + AVTRANS_LOGE("Unsupported event type."); + } +} + +void DsoftbusInputAudioPlugin::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + std::string message(reinterpret_cast(ext->buf), ext->bufLen); + AVTRANS_LOGI("Receive message : %s", message.c_str()); + + json resMsg = json::parse(message, nullptr, false); + TRUE_RETURN(resMsg.is_discarded(), "The resMsg parse failed"); + TRUE_RETURN(!IsUInt32(resMsg, AVT_DATA_META_TYPE), "invalid data type"); + uint32_t metaType = resMsg[AVT_DATA_META_TYPE]; + + auto buffer = CreateBuffer(metaType, data, resMsg); + DataEnqueue(buffer); +} + +std::shared_ptr DsoftbusInputAudioPlugin::CreateBuffer(uint32_t metaType, + const StreamData *data, const json &resMsg) +{ + auto buffer = Buffer::CreateDefaultBuffer(static_cast(metaType), data->bufLen); + auto bufData = buffer->GetMemory(); + + auto writeSize = bufData->Write(reinterpret_cast(data->buf), data->bufLen, 0); + if (static_cast(writeSize) != data->bufLen) { + AVTRANS_LOGE("write buffer data failed."); + return buffer; + } + + auto meta = std::make_shared(); + meta->UnmarshalAudioMeta(resMsg[AVT_DATA_PARAM]); + buffer->pts = meta->pts_; + buffer->GetBufferMeta()->SetMeta(Tag::USER_FRAME_PTS, meta->pts_); + buffer->GetBufferMeta()->SetMeta(Tag::USER_FRAME_NUMBER, meta->frameNum_); + AVTRANS_LOGI("buffer pts: %ld, bufferLen: %zu, frameNumber: %zu", buffer->pts, buffer->GetMemory()->GetSize(), + meta->frameNum_); + return buffer; +} + +void DsoftbusInputAudioPlugin::DataEnqueue(std::shared_ptr &buffer) +{ + while (dataQueue_.size() >= DATA_QUEUE_MAX_SIZE) { + AVTRANS_LOGE("Data queue overflow."); + dataQueue_.pop(); + } + dataQueue_.push(buffer); + dataCond_.notify_all(); +} + +void DsoftbusInputAudioPlugin::HandleData() +{ + while (state_ == State::RUNNING) { + std::shared_ptr buffer; + { + std::unique_lock lock(dataQueueMtx_); + dataCond_.wait_for(lock, std::chrono::milliseconds(PLUGIN_TASK_WAIT_TIME), + [this]() { return !dataQueue_.empty(); }); + if (state_ != State::RUNNING) { + return; + } + if (dataQueue_.empty()) { + continue; + } + buffer = dataQueue_.front(); + dataQueue_.pop(); + } + if (buffer == nullptr) { + AVTRANS_LOGE("Data is null"); + continue; + } + dataCb_(buffer); + } +} + +void DsoftbusInputAudioPlugin::DataQueueClear(std::queue> &queue) +{ + std::queue> empty; + swap(empty, queue); +} + +Status DsoftbusInputAudioPlugin::PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) +{ + (void) buffer; + AVTRANS_LOGI("Push Data"); + return Status::OK; +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/dsoftbus_input_audio_plugin.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/dsoftbus_input_audio_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..0828187e64d4de5c05b1a5ed6f7166cfea3e99f9 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_input/dsoftbus_input_audio/dsoftbus_input_audio_plugin.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DSOFTBUS_H +#define OHOS_AV_TRANS_ENGINE_PLUGINS_INPUT_DSOFTBUS_H + +#include +#include +#include +#include +#include +#include +#include + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_input_plugin.h" +#include "nlohmann/json.hpp" +#include "foundation/osal/thread/task.h" +#include "plugin_types.h" +#include "plugin_manager.h" +#include "softbus_channel_adapter.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace Media::Plugin; +using json = nlohmann::json; +using AVDataCallback = std::function)>; + +class DsoftbusInputAudioPlugin : public AvTransInputPlugin, + public ISoftbusChannelListener, + public std::enable_shared_from_this { +public: + explicit DsoftbusInputAudioPlugin(std::string name); + ~DsoftbusInputAudioPlugin(); + + Status Init() override; + Status Deinit() override; + Status Prepare() override; + Status Reset() override; + Status Start() override; + Status Stop() override; + Status Pause() override; + Status Resume() override; + Status GetParameter(Tag tag, ValueType &value) override; + Status SetParameter(Tag tag, const ValueType &value) override; + Status PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) override; + Status SetCallback(Callback *cb) override; + Status SetDataCallback(AVDataCallback callback) override; + + // interface from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + +private: + void HandleData(); + void DataEnqueue(std::shared_ptr &buffer); + void DataQueueClear(std::queue> &queue); + std::shared_ptr CreateBuffer(uint32_t metaType, const StreamData *data, const json &resMsg); + +private: + std::string ownerName_; + std::string sessionName_; + std::string peerDevId_; + std::condition_variable dataCond_; + std::shared_ptr bufferPopTask_; + std::mutex dataQueueMtx_; + Media::OSAL::Mutex operationMutes_ {}; + std::queue> dataQueue_; + std::map paramsMap_; + State state_ {State::CREATED}; + Callback* eventsCb_ = nullptr; + AVDataCallback dataCb_; +}; +} +} +#endif // OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSOFTBUS_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0866fbaf2e1679ed1dfe2aba2371256e7edd9061 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("plugin_AVTransDaudioOutput") { + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "//third_party/json/include", + "//third_party/ffmpeg", + ] + + sources = [ "daudio_output_plugin.cpp" ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_configs = [ "${plugin_path}/plugins:avtrans_cflags" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"daudio_output_plugin\"", + "LOG_DOMAIN=0xD004100", + ] + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/daudio_output_plugin.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/daudio_output_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d03d725ffed74c759d92dac623344ff01e5f823 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/daudio_output_plugin.cpp @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "daudio_output_plugin.h" + +#include "foundation/utils/constants.h" +#include "plugin/common/plugin_caps_builder.h" +#include "plugin/factory/plugin_factory.h" +#include "plugin/interface/generic_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +GenericPluginDef CreateDaudioOutputPluginDef() +{ + GenericPluginDef definition; + definition.name = "AVTransDaudioOutputPlugin"; + definition.pkgName = "AVTransDaudioOutputPlugin"; + definition.description = "Send audio playback and frame rate control."; + definition.rank = PLUGIN_RANK; + definition.creator = [] (const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + + definition.pkgVersion = AVTRANS_OUTPUT_API_VERSION; + definition.license = LicenseType::APACHE_V2; + + CapabilityBuilder capBuilder; + capBuilder.SetMime(OHOS::Media::MEDIA_MIME_AUDIO_RAW); + DiscreteCapability valuesSampleRate = {8000, 11025, 12000, 16000, + 22050, 24000, 32000, 44100, 48000, 64000, 96000}; + capBuilder.SetAudioSampleRateList(valuesSampleRate); + DiscreteCapability valuesSampleFormat = {AudioSampleFormat::F32P}; + capBuilder.SetAudioSampleFormatList(valuesSampleFormat); + definition.inCaps.push_back(capBuilder.Build()); + return definition; +} + +static AutoRegisterPlugin g_registerPluginHelper(CreateDaudioOutputPluginDef()); + +DaudioOutputPlugin::DaudioOutputPlugin(std::string name) + : AvTransOutputPlugin(std::move(name)) +{ + AVTRANS_LOGI("ctor."); +} + +DaudioOutputPlugin::~DaudioOutputPlugin() +{ + AVTRANS_LOGI("dtor."); +} + +Status DaudioOutputPlugin::Init() +{ + AVTRANS_LOGI("Init."); + OSAL::ScopedLock lock(operationMutes_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DaudioOutputPlugin::Deinit() +{ + AVTRANS_LOGI("Deinit."); + return Reset(); +} + +void DaudioOutputPlugin::RampleInit(uint32_t channels, uint32_t sampleRate, uint32_t channelLayout) +{ + resample_ = std::make_shared(); + Ffmpeg::ResamplePara resamplePara { + channels, // channels_ + sampleRate, // sampleRate_ + 0, // bitsPerSample_ + static_cast(channelLayout), // channelLayout_ + AV_SAMPLE_FMT_FLTP, + 2048, // samplePerFrame_ + AV_SAMPLE_FMT_S16, + }; + if (resample_->Init(resamplePara) != Status::OK) { + AVTRANS_LOGE("Resample init error"); + } +} + +Status DaudioOutputPlugin::Prepare() +{ + AVTRANS_LOGI("Prepare"); + OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::INITIALIZED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + if (sendPlayTask_ == nullptr) { + sendPlayTask_ = std::make_shared("sendPlayTask_"); + sendPlayTask_->RegisterHandler([this] { HandleData(); }); + } + + ValueType channelsValue; + TRUE_RETURN_V_MSG_E(GetParameter(Tag::AUDIO_CHANNELS, channelsValue) != Status::OK, + Status::ERROR_UNKNOWN, "Not found AUDIO_CHANNELS"); + uint32_t channels = static_cast(Plugin::AnyCast(channelsValue)); + + ValueType sampleRateValue; + TRUE_RETURN_V_MSG_E(GetParameter(Tag::AUDIO_SAMPLE_RATE, sampleRateValue) != Status::OK, + Status::ERROR_UNKNOWN, "Not found AUDIO_SAMPLE_RATE"); + uint32_t sampleRate = static_cast(Plugin::AnyCast(sampleRateValue)); + + ValueType channelsLayoutValue; + TRUE_RETURN_V_MSG_E(GetParameter(Tag::AUDIO_CHANNEL_LAYOUT, channelsLayoutValue) != Status::OK, + Status::ERROR_UNKNOWN, "Not found AUDIO_CHANNEL_LAYOUT"); + uint32_t channelsLayout = static_cast(Plugin::AnyCast(channelsLayoutValue)); + if (channelsLayout == AUDIO_CHANNEL_LAYOUT_MONO) { + channelsLayout = AV_CH_LAYOUT_MONO; + } else if (channelsLayout == AUDIO_CHANNEL_LAYOUT_STEREO) { + channelsLayout = AV_CH_LAYOUT_STEREO; + } + AVTRANS_LOGI("channels = %d, sampleRate = %d, channelLayout = %d.", channels, sampleRate, channelsLayout); + RampleInit(channels, sampleRate, channelsLayout); + state_ = State::PREPARED; + return Status::OK; +} + +Status DaudioOutputPlugin::Reset() +{ + AVTRANS_LOGI("Reset enter"); + OSAL::ScopedLock lock(operationMutes_); + eventcallback_ = nullptr; + if (sendPlayTask_) { + sendPlayTask_->Stop(); + sendPlayTask_.reset(); + } + if (resample_) { + resample_.reset(); + } + smIndex_ = 0; + paramsMap_.clear(); + DataQueueClear(outputBuffer_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DaudioOutputPlugin::GetParameter(Tag tag, ValueType &value) +{ + auto iter = paramsMap_.find(tag); + if (iter != paramsMap_.end()) { + value = iter->second; + return Status::OK; + } + return Status::ERROR_NOT_EXISTED; +} + +Status DaudioOutputPlugin::SetParameter(Tag tag, const ValueType &value) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + paramsMap_.insert(std::make_pair(tag, value)); + if (tag == Plugin::Tag::USER_SHARED_MEMORY_FD) { + std::unique_lock lock(sharedMemMtx_); + sharedMemory_ = UnmarshalSharedMemory(Media::Plugin::AnyCast(value)); + } + if (tag == Plugin::Tag::USER_AV_SYNC_GROUP_INFO) { + std::string groupInfo = Media::Plugin::AnyCast(value); + AVTRANS_LOGI("Set USER_AV_SYNC_GROUP_INFO parameter done, group info = %s.", GetAnonyString(groupInfo).c_str()); + } + return Status::OK; +} + +Status DaudioOutputPlugin::Start() +{ + AVTRANS_LOGI("Start enter"); + OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::PREPARED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + DataQueueClear(outputBuffer_); + sendPlayTask_->Start(); + state_ = State::RUNNING; + return Status::OK; +} + +Status DaudioOutputPlugin::Stop() +{ + AVTRANS_LOGI("Stop enter"); + OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::RUNNING) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + state_ = State::PREPARED; + sendPlayTask_->Stop(); + DataQueueClear(outputBuffer_); + return Status::OK; +} + +Status DaudioOutputPlugin::SetCallback(Callback *cb) +{ + OSAL::ScopedLock lock(operationMutes_); + if (cb == nullptr) { + AVTRANS_LOGE("SetCallBack failed, cb is nullptr."); + return Status::ERROR_NULL_POINTER; + } + eventcallback_ = cb; + AVTRANS_LOGI("SetCallback success."); + return Status::OK; +} + +Status DaudioOutputPlugin::SetDataCallback(AVDataCallback callback) +{ + OSAL::ScopedLock lock(operationMutes_); + if (callback == nullptr) { + AVTRANS_LOGE("SetCallBack failed, callback is nullptr."); + return Status::ERROR_NULL_POINTER; + } + datacallback_ = callback; + AVTRANS_LOGI("SetDataCallback success."); + return Status::OK; +} + +Status DaudioOutputPlugin::PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) +{ + if (buffer == nullptr || buffer->IsEmpty() || (buffer->GetBufferMeta() == nullptr)) { + AVTRANS_LOGE("input buffer is nullptr, push data failed."); + return Status::ERROR_NULL_POINTER; + } + + auto bufferMeta = buffer->GetBufferMeta(); + if (bufferMeta->IsExist(Tag::USER_FRAME_NUMBER) && bufferMeta->IsExist(Tag::USER_FRAME_PTS)) { + int64_t pts = Plugin::AnyCast(bufferMeta->GetMeta(Tag::USER_FRAME_PTS)); + uint32_t frameNum = Plugin::AnyCast(bufferMeta->GetMeta(Tag::USER_FRAME_NUMBER)); + AVTRANS_LOGI("Push audio buffer, bufferLen: %zu, frameNum: %d, pts: %ld", buffer->GetMemory()->GetSize(), + frameNum, pts); + } else { + AVTRANS_LOGI("Push audio buffer, bufferLen: %zu, not contains metadata.", buffer->GetMemory()->GetSize()); + } + + OSAL::ScopedLock lock(operationMutes_); + while (outputBuffer_.size() >= DATA_QUEUE_MAX_SIZE) { + AVTRANS_LOGE("outputBuffer_ queue overflow."); + outputBuffer_.pop(); + } + outputBuffer_.push(buffer); + dataCond_.notify_all(); + return Status::OK; +} + +void DaudioOutputPlugin::HandleData() +{ + while (state_ == State::RUNNING) { + std::shared_ptr buffer; + { + std::unique_lock lock(dataQueueMtx_); + dataCond_.wait_for(lock, std::chrono::milliseconds(PLUGIN_TASK_WAIT_TIME), + [this]() { return !outputBuffer_.empty(); }); + if (state_ != State::RUNNING) { + return; + } + if (outputBuffer_.empty()) { + continue; + } + buffer = outputBuffer_.front(); + outputBuffer_.pop(); + } + if (buffer == nullptr) { + AVTRANS_LOGE("Data is null"); + continue; + } + datacallback_(buffer); + WriteMasterClockToMemory(buffer); + } +} + +void DaudioOutputPlugin::WriteMasterClockToMemory(const std::shared_ptr &buffer) +{ + std::unique_lock lock(sharedMemMtx_); + if ((sharedMemory_.fd <= 0) || (sharedMemory_.size <= 0) || sharedMemory_.name.empty()) { + return; + } + + if ((buffer == nullptr) || (buffer->GetBufferMeta() == nullptr)) { + AVTRANS_LOGE("output buffer or buffer meta is nullptr."); + return; + } + + if (!buffer->GetBufferMeta()->IsExist(Tag::USER_FRAME_NUMBER)) { + AVTRANS_LOGE("the output buffer meta does not contains tag user_frame_number."); + return; + } + + if (!buffer->GetBufferMeta()->IsExist(Tag::USER_FRAME_PTS)) { + AVTRANS_LOGE("the output buffer meta does not contains tag USER_FRAME_PTS."); + return; + } + + uint32_t frameNum = Plugin::AnyCast(buffer->GetBufferMeta()->GetMeta(Tag::USER_FRAME_NUMBER)); + int64_t pts = Plugin::AnyCast(buffer->GetBufferMeta()->GetMeta(Tag::USER_FRAME_PTS)); + AVSyncClockUnit clockUnit = AVSyncClockUnit{ smIndex_, frameNum, pts }; + int32_t ret = WriteClockUnitToMemory(sharedMemory_, clockUnit); + if (ret == DH_AVT_SUCCESS) { + smIndex_ = clockUnit.index; + } +} + +void DaudioOutputPlugin::DataQueueClear(std::queue> &q) +{ + std::queue> empty; + swap(empty, q); +} + +Status DaudioOutputPlugin::StartOutputQueue() +{ + AVTRANS_LOGI("StartOutputQueue enter."); + return Status::OK; +} + +Status DaudioOutputPlugin::ControlFrameRate(const int64_t timestamp) +{ + AVTRANS_LOGI("ControlFrameRate enter."); + return Status::OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/daudio_output_plugin.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/daudio_output_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..38ba0e28c9ce07b13798dfd178591fab75f84c3a --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/daudio_output/daudio_output_plugin.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_AUDIO_H +#define OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_AUDIO_H + +#include +#include +#include +#include +#include + +#include "av_sync_utils.h" +#include "av_trans_errno.h" +#include "av_trans_buffer.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_output_plugin.h" +#include "foundation/osal/thread/mutex.h" +#include "foundation/osal/thread/scoped_lock.h" +#include "foundation/osal/thread/task.h" +#include "nlohmann/json.hpp" +#include "plugin_manager.h" +#include "plugin_types.h" +#include "plugin/convert/ffmpeg_convert.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; + +using json = nlohmann::json; +using AVDataCallback = std::function)>; + +class DaudioOutputPlugin : public AvTransOutputPlugin { +public: + explicit DaudioOutputPlugin(std::string name); + ~DaudioOutputPlugin(); + + Status Init() override; + Status Deinit() override; + Status Prepare() override; + Status Reset() override; + Status Start() override; + Status Stop() override; + Status SetParameter(Tag tag, const ValueType &value) override; + Status GetParameter(Tag tag, ValueType &value) override; + Status PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) override; + Status SetCallback(Callback *cb) override; + Status SetDataCallback(AVDataCallback callback) override; + +private: + Status StartOutputQueue(); + Status ControlFrameRate(const int64_t timestamp); + void HandleData(); + void DataQueueClear(std::queue> &q); + void RampleInit(uint32_t channels, uint32_t sampleRate, uint32_t channelLayout); + void WriteMasterClockToMemory(const std::shared_ptr &buffer); + +private: + std::condition_variable dataCond_; + std::map paramsMap_; + std::mutex dataQueueMtx_; + std::queue> outputBuffer_; + std::shared_ptr sendPlayTask_; + + Media::OSAL::Mutex operationMutes_ {}; + State state_ {State::CREATED}; + Callback *eventcallback_ = nullptr; + AVDataCallback datacallback_ = nullptr; + std::shared_ptr resample_ {nullptr}; + uint32_t smIndex_ = 0; + std::mutex sharedMemMtx_; + AVTransSharedMemory sharedMemory_ = AVTransSharedMemory{ 0, 0, "" }; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_AUDIO_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..628e47d5981e2ad5c8a84c4f3fd050f8dc2c66ec --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("plugin_AVTransDscreenOutput") { + include_dirs = [ + "${common_path}/include", + "${output_controller_path}/include", + "${plugin_path}/interface", + "//third_party/json/include", + ] + + sources = [ + "${output_controller_path}/src/output_controller.cpp", + "${output_controller_path}/src/output_controller_listener.cpp", + "${output_controller_path}/src/time_statistician.cpp", + "dscreen_output_controller.cpp", + "dscreen_output_plugin.cpp", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "eventhandler:libeventhandler", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_configs = [ "${plugin_path}/plugins:avtrans_cflags" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dscreen_output_plugin\"", + "LOG_DOMAIN=0xD004100", + ] + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_controller.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_controller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2dab1fe1fc8f9bd7ffff97a6efb86bdfa19c75fc --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_controller.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dscreen_output_controller.h" + +namespace OHOS { +namespace DistributedHardware { +void DScreenOutputController::PrepareSmooth() +{ + OutputController::PrepareSmooth(); + SetBufferTime(SMOOTH_BUFFER_TIME); + SetDynamicBalanceThre(DYNAMIC_BALANCE_THRE); + SetAverIntervalDiffThre(AVER_INTERVAL_DIFF_THRE); + SetPushOnceDiffThre(PUSH_ONCE_DIFF_THRE); + SetTimeStampOnceDiffThre(TIMESTAMP_ONCE_DIFF_THRE); + SetAdjustSleepFactor(ADJUST_SLEEP_FACTOR); + SetWaitClockFactor(WAIT_CLOCK_FACTOR); + SetTrackClockFactor(TRACK_CLOCK_FACTOR); + SetSleepThre(SLEEP_THRE); +} + +void DScreenOutputController::PrepareSync() +{ + OutputController::PrepareSync(); + SetAdjustSleepFactor(ADJUST_SLEEP_FACTOR); + SetWaitClockThre(WAIT_CLOCK_THRE); + SetTrackClockThre(TRACK_CLOCK_THRE); + SetSleepThre(SLEEP_THRE); + SetAudioBackTime(AUDIO_BACK_TIME); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_controller.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..85a24709acf0b4f2ecd99d295ff9d774569afe5b --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_controller.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DSCREEN_OUTPUT_CONTROLLER_H +#define OHOS_DSCREEN_OUTPUT_CONTROLLER_H + +#include "output_controller.h" +#include "av_trans_utils.h" +#include "av_sync_utils.h" + +namespace OHOS { +namespace DistributedHardware { +class DScreenOutputController : public OutputController { +public: + ~DScreenOutputController() override = default; + void PrepareSmooth() override; + void PrepareSync() override; + +private: + constexpr static float ADJUST_SLEEP_FACTOR = 0.1; + constexpr static float WAIT_CLOCK_FACTOR = 0.1; + constexpr static float TRACK_CLOCK_FACTOR = 0.2; + constexpr static uint8_t DYNAMIC_BALANCE_THRE = 3; + constexpr static int32_t SMOOTH_BUFFER_TIME = 0 * NS_ONE_MS; + constexpr static uint32_t AVER_INTERVAL_DIFF_THRE = 2 * NS_ONE_MS; + constexpr static uint32_t PUSH_ONCE_DIFF_THRE = 10 * NS_ONE_MS; + constexpr static uint32_t TIMESTAMP_ONCE_DIFF_THRE = 3 * NS_ONE_MS; + constexpr static uint32_t WAIT_CLOCK_THRE = 125 * NS_ONE_MS; + constexpr static uint32_t TRACK_CLOCK_THRE = 45 * NS_ONE_MS; + constexpr static int64_t SLEEP_THRE = 1000 * NS_ONE_MS; + constexpr static int64_t AUDIO_BACK_TIME = 320 * NS_ONE_MS; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DSCREEN_OUTPUT_CONTROLLER_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_plugin.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86b860b68e227ffe2408aa43bf652f58bd5c4bc6 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_plugin.cpp @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dscreen_output_plugin.h" + +#include "foundation/utils/constants.h" +#include "plugin/factory/plugin_factory.h" +#include "plugin/interface/generic_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +GenericPluginDef CreateDscreenOutputPluginDef() +{ + GenericPluginDef definition; + definition.name = "AVTransDscreenOutputPlugin"; + definition.pkgName = "AVTransDscreenOutputPlugin"; + definition.description = "Send video display and frame rate control."; + definition.rank = PLUGIN_RANK; + definition.creator = [] (const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + + definition.pkgVersion = AVTRANS_OUTPUT_API_VERSION; + definition.license = LicenseType::APACHE_V2; + + Capability inCap(Media::MEDIA_MIME_VIDEO_RAW); + inCap.AppendDiscreteKeys( + Capability::Key::VIDEO_PIXEL_FORMAT, {VideoPixelFormat::NV12}); + definition.inCaps.push_back(inCap); + return definition; +} + +static AutoRegisterPlugin g_registerPluginHelper(CreateDscreenOutputPluginDef()); + +DscreenOutputPlugin::DscreenOutputPlugin(std::string name) + : AvTransOutputPlugin(std::move(name)) +{ + AVTRANS_LOGI("ctor."); +} + +DscreenOutputPlugin::~DscreenOutputPlugin() +{ + AVTRANS_LOGI("dtor."); +} + +Status DscreenOutputPlugin::Init() +{ + AVTRANS_LOGI("Init."); + Media::OSAL::ScopedLock lock(operationMutes_); + InitOutputController(); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DscreenOutputPlugin::Deinit() +{ + AVTRANS_LOGI("Deinit."); + return Reset(); +} + +Status DscreenOutputPlugin::Prepare() +{ + AVTRANS_LOGI("Prepare"); + { + Media::OSAL::ScopedLock lock(operationMutes_); + TRUE_RETURN_V_MSG_E((state_ != State::INITIALIZED), Status::ERROR_WRONG_STATE, "The state is wrong."); + TRUE_RETURN_V_MSG_E((!controller_), Status::ERROR_NULL_POINTER, "Controller is nullptr."); + state_ = State::PREPARED; + } + controller_->PrepareControl(); + return Status::OK; +} + +Status DscreenOutputPlugin::Reset() +{ + AVTRANS_LOGI("Reset"); + { + Media::OSAL::ScopedLock lock(operationMutes_); + state_ = State::INITIALIZED; + eventsCb_ = nullptr; + dataCb_ = nullptr; + } + controllerListener_ = nullptr; + if (controller_) { + controller_->ReleaseControl(); + controller_ = nullptr; + } + return Status::OK; +} + +Status DscreenOutputPlugin::GetParameter(Tag tag, ValueType &value) +{ + { + Media::OSAL::ScopedLock lock(operationMutes_); + TRUE_RETURN_V_MSG_E((!controller_), Status::ERROR_NULL_POINTER, "Controller is nullptr."); + } + return controller_->GetParameter(tag, value); +} + +Status DscreenOutputPlugin::SetParameter(Tag tag, const ValueType &value) +{ + { + Media::OSAL::ScopedLock lock(operationMutes_); + TRUE_RETURN_V_MSG_E((!controller_), Status::ERROR_NULL_POINTER, "Controller is nullptr."); + } + return controller_->SetParameter(tag, value); +} + +Status DscreenOutputPlugin::Start() +{ + AVTRANS_LOGI("Start"); + { + Media::OSAL::ScopedLock lock(operationMutes_); + TRUE_RETURN_V_MSG_E((state_ != State::PREPARED), Status::ERROR_WRONG_STATE, "The state is wrong."); + TRUE_RETURN_V_MSG_E((!controller_), Status::ERROR_NULL_POINTER, "Controller is nullptr."); + state_ = State::RUNNING; + } + controller_->StartControl(); + return Status::OK; +} + +Status DscreenOutputPlugin::Stop() +{ + AVTRANS_LOGI("Stop"); + { + Media::OSAL::ScopedLock lock(operationMutes_); + TRUE_RETURN_V_MSG_E((state_ != State::RUNNING), Status::ERROR_WRONG_STATE, "The state is wrong."); + TRUE_RETURN_V_MSG_E((!controller_), Status::ERROR_NULL_POINTER, "Controller is nullptr."); + state_ = State::PREPARED; + } + controller_->StopControl(); + return Status::OK; +} + +Status DscreenOutputPlugin::SetCallback(Callback *cb) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + TRUE_RETURN_V_MSG_E((!cb), Status::ERROR_NULL_POINTER, "SetCallback failed, cb is nullptr."); + eventsCb_ = cb; + AVTRANS_LOGI("SetCallback success."); + return Status::OK; +} + +Status DscreenOutputPlugin::SetDataCallback(AVDataCallback callback) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + dataCb_ = callback; + AVTRANS_LOGI("SetDataCallback success."); + return Status::OK; +} + +Status DscreenOutputPlugin::PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) +{ + { + Media::OSAL::ScopedLock lock(operationMutes_); + TRUE_RETURN_V_MSG_E((buffer == nullptr || buffer->IsEmpty()), Status::ERROR_NULL_POINTER, + "AVBuffer is nullptr."); + TRUE_RETURN_V_MSG_E((!controller_), Status::ERROR_NULL_POINTER, "Controller is nullptr."); + } + controller_->PushData(buffer); + return Status::OK; +} + +void DscreenOutputPlugin::OnOutput(const std::shared_ptr& data) +{ + auto bufferMeta = data->GetBufferMeta(); + uint32_t vFrameNumber = DEFAULT_INVALID_FRAME_NUM; + if (bufferMeta->IsExist(Tag::USER_FRAME_NUMBER)) { + vFrameNumber = Plugin::AnyCast(bufferMeta->GetMeta(Tag::USER_FRAME_NUMBER)); + } + AVTRANS_LOGD("OnOutput vFrameNumber: %zu.", vFrameNumber); + dataCb_(data); +} + +void DscreenOutputPlugin::InitOutputController() +{ + if (!controller_) { + controller_ = std::make_unique(); + } + if (!controllerListener_) { + controllerListener_ = std::make_shared(shared_from_this()); + } + controller_->RegisterListener(controllerListener_); +} +} +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_plugin.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..7ff6534c78032e2357dea1a2260beb6092fa23ae --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dscreen_output/dscreen_output_plugin.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSCREEN_H +#define OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSCREEN_H + +#include +#include +#include +#include +#include + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_output_plugin.h" +#include "foundation/osal/thread/task.h" +#include "nlohmann/json.hpp" +#include "plugin_manager.h" +#include "plugin_types.h" +#include "dscreen_output_controller.h" +#include "output_controller_listener.h" +#include "controllable_output.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; + +using json = nlohmann::json; +using AVDataCallback = std::function)>; + +class DscreenOutputPlugin : public AvTransOutputPlugin, public ControllableOutput, + public std::enable_shared_from_this { +public: + explicit DscreenOutputPlugin(std::string name); + ~DscreenOutputPlugin(); + + Status Init() override; + Status Deinit() override; + Status Prepare() override; + Status Reset() override; + Status Start() override; + Status Stop() override; + Status SetParameter(Tag tag, const ValueType &value) override; + Status GetParameter(Tag tag, ValueType &value) override; + Status PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) override; + Status SetCallback(Callback *cb) override; + Status SetDataCallback(AVDataCallback callback) override; + void OnOutput(const std::shared_ptr& data) override; + +private: + void InitOutputController(); + +private: + Media::OSAL::Mutex operationMutes_ {}; + State state_ {State::CREATED}; + Callback *eventsCb_ = nullptr; + AVDataCallback dataCb_; + std::condition_variable dataCond_; + std::unique_ptr controller_ = nullptr; + std::shared_ptr controllerListener_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSCREEN_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fa96006a141165fb1894d6e1413ad161de7e67a7 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("plugin_AVTransDsoftbusOutput") { + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${dsoftbus_path}/interfaces/kits/transport", + "${dsoftbus_path}/interfaces/kits/bus_center", + "${dsoftbus_path}/interfaces/kits/common", + "//third_party/json/include", + ] + + sources = [ "dsoftbus_output_plugin.cpp" ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_configs = [ "${plugin_path}/plugins:avtrans_cflags" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dsoftbus_output_video_plugin\"", + "LOG_DOMAIN=0xD004100", + ] + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/dsoftbus_output_plugin.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/dsoftbus_output_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..abcd5dc4b820624ae1e58ac74131a510222ae1f8 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/dsoftbus_output_plugin.cpp @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dsoftbus_output_plugin.h" + +#include "foundation/utils/constants.h" +#include "plugin/common/plugin_caps_builder.h" +#include "plugin/factory/plugin_factory.h" +#include "plugin/interface/generic_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +std::vector CreateDsoftbusOutputPluginDef() +{ + int32_t capNum = 2; + std::vector definitionList; + for (int i = 0; i < capNum; i++) { + GenericPluginDef definition; + definition.name = "AVTransDsoftbusOutputPlugin_H264"; + definition.pkgName = "AVTransDsoftbusOutputPlugin"; + definition.description = "Video transport to dsoftbus"; + definition.rank = PLUGIN_RANK; + definition.creator = [] (const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + + definition.pkgVersion = AVTRANS_OUTPUT_API_VERSION; + definition.license = LicenseType::APACHE_V2; + + CapabilityBuilder capBuilder; + capBuilder.SetMime(Media::MEDIA_MIME_VIDEO_H264); + if (i == 1) { + definition.name = "AVTransDsoftbusOutputPlugin_H265"; + capBuilder.SetMime(Media::MEDIA_MIME_VIDEO_H265); + } + definition.inCaps.push_back(capBuilder.Build()); + definitionList.push_back(definition); + } + return definitionList; +} + +static AutoRegisterPlugin g_registerPluginHelper(CreateDsoftbusOutputPluginDef()); + +DsoftbusOutputPlugin::DsoftbusOutputPlugin(std::string name) + : AvTransOutputPlugin(std::move(name)) +{ + AVTRANS_LOGI("ctor."); +} + +DsoftbusOutputPlugin::~DsoftbusOutputPlugin() +{ + AVTRANS_LOGI("dtor."); +} + +Status DsoftbusOutputPlugin::Init() +{ + AVTRANS_LOGI("Init Dsoftbus Output Plugin."); + Media::OSAL::ScopedLock lock(operationMutes_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DsoftbusOutputPlugin::Deinit() +{ + AVTRANS_LOGI("Deinit Dsoftbus Output Plugin."); + return Reset(); +} + +Status DsoftbusOutputPlugin::Prepare() +{ + AVTRANS_LOGI("Prepare"); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::INITIALIZED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + + sessionName_ = ownerName_ + "_" + SENDER_DATA_SESSION_NAME_SUFFIX; + int32_t ret = SoftbusChannelAdapter::GetInstance().CreateChannelServer(TransName2PkgName(ownerName_), sessionName_); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Create Session Server failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + + if (!bufferPopTask_) { + bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + bufferPopTask_->RegisterHandler([this] { FeedChannelData(); }); + } + state_ = State::PREPARED; + return Status::OK; +} + +Status DsoftbusOutputPlugin::Reset() +{ + AVTRANS_LOGI("Reset"); + Media::OSAL::ScopedLock lock(operationMutes_); + paramsMap_.clear(); + if (bufferPopTask_) { + bufferPopTask_->Stop(); + bufferPopTask_.reset(); + } + DataQueueClear(dataQueue_); + eventsCb_ = nullptr; + SoftbusChannelAdapter::GetInstance().RemoveChannelServer(TransName2PkgName(ownerName_), sessionName_); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(sessionName_, peerDevId_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DsoftbusOutputPlugin::Start() +{ + AVTRANS_LOGI("Dsoftbus Output Plugin start."); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::PREPARED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + Status ret = OpenSoftbusChannel(); + if (ret != Status::OK) { + AVTRANS_LOGE("OpenSoftbusSession failed."); + return Status::ERROR_INVALID_OPERATION; + } + DataQueueClear(dataQueue_); + bufferPopTask_->Start(); + state_ = State::RUNNING; + return Status::OK; +} + +Status DsoftbusOutputPlugin::Stop() +{ + AVTRANS_LOGI("Dsoftbus Output Plugin stop."); + if (state_ != State::RUNNING) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + state_ = State::PREPARED; + bufferPopTask_->Stop(); + DataQueueClear(dataQueue_); + CloseSoftbusChannel(); + return Status::OK; +} + +Status DsoftbusOutputPlugin::GetParameter(Tag tag, ValueType &value) +{ + auto res = paramsMap_.find(tag); + if (res != paramsMap_.end()) { + value = res->second; + return Status::OK; + } + return Status::ERROR_NOT_EXISTED; +} + +Status DsoftbusOutputPlugin::SetParameter(Tag tag, const ValueType &value) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (tag == Tag::MEDIA_DESCRIPTION) { + ParseChannelDescription(Plugin::AnyCast(value), ownerName_, peerDevId_); + } + paramsMap_.insert(std::pair(tag, value)); + return Status::OK; +} + +Status DsoftbusOutputPlugin::SetCallback(Callback *cb) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (cb == nullptr) { + AVTRANS_LOGE("SetCallback failed, cb is nullptr."); + return Status::ERROR_INVALID_OPERATION; + } + eventsCb_ = cb; + AVTRANS_LOGI("SetCallback success"); + return Status::OK; +} + +Status DsoftbusOutputPlugin::OpenSoftbusChannel() +{ + int32_t ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, peerDevId_, this); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Register channel listener failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + std::string peerSessName_ = ownerName_ + "_" + RECEIVER_DATA_SESSION_NAME_SUFFIX; + ret = SoftbusChannelAdapter::GetInstance().OpenSoftbusChannel(sessionName_, peerSessName_, peerDevId_); + if ((ret != DH_AVT_SUCCESS) && (ret != ERR_DH_AVT_SESSION_HAS_OPENED)) { + AVTRANS_LOGE("Open softbus channel failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + return Status::OK; +} + +void DsoftbusOutputPlugin::CloseSoftbusChannel() +{ + int32_t ret = SoftbusChannelAdapter::GetInstance().CloseSoftbusChannel(sessionName_, peerDevId_); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Close softbus channle failed ret: %s.", ret); + } +} + +void DsoftbusOutputPlugin::OnChannelEvent(const AVTransEvent &event) +{ + AVTRANS_LOGI("OnChannelEvent enter, event type: %d", event.type); + if (eventsCb_ == nullptr) { + AVTRANS_LOGE("OnChannelEvent failed, event callback is nullptr."); + return; + } + switch (event.type) { + case EventType::EVENT_CHANNEL_OPENED: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_OPENED}); + break; + } + case EventType::EVENT_CHANNEL_OPEN_FAIL: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_OPEN_FAIL}); + break; + } + case EventType::EVENT_CHANNEL_CLOSED: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_CLOSED}); + break; + } + default: + AVTRANS_LOGE("Unsupported event type."); + } +} + +void DsoftbusOutputPlugin::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + (void)data; + (void)ext; +} + +Status DsoftbusOutputPlugin::PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (buffer == nullptr || buffer->IsEmpty()) { + AVTRANS_LOGE("Buffer is nullptr."); + return Status::ERROR_NULL_POINTER; + } + while (dataQueue_.size() >= DATA_QUEUE_MAX_SIZE) { + AVTRANS_LOGE("Data queue overflow."); + dataQueue_.pop(); + } + dataQueue_.push(buffer); + dataCond_.notify_all(); + return Status::OK; +} + +void DsoftbusOutputPlugin::FeedChannelData() +{ + while (state_ == State::RUNNING) { + std::shared_ptr buffer; + { + std::unique_lock lock(dataQueueMtx_); + dataCond_.wait_for(lock, std::chrono::milliseconds(PLUGIN_TASK_WAIT_TIME), + [this]() { return !dataQueue_.empty(); }); + if (state_ != State::RUNNING) { + return; + } + if (dataQueue_.empty()) { + continue; + } + buffer = dataQueue_.front(); + dataQueue_.pop(); + } + if (buffer == nullptr) { + AVTRANS_LOGE("Data is null"); + continue; + } + SendDataToSoftbus(buffer); + } +} + +void DsoftbusOutputPlugin::SendDataToSoftbus(std::shared_ptr &buffer) +{ + json jsonObj; + auto bufferMeta = buffer->GetBufferMeta(); + BufferMetaType metaType = bufferMeta->GetType(); + jsonObj[AVT_DATA_META_TYPE] = metaType; + if (metaType != BufferMetaType::VIDEO) { + AVTRANS_LOGE("metaType is wrong"); + return; + } + auto hisAMeta = std::make_shared(); + hisAMeta->frameNum_ = Plugin::AnyCast(buffer->GetBufferMeta()->GetMeta(Tag::USER_FRAME_NUMBER)); + hisAMeta->pts_ = buffer->pts; + AVTRANS_LOGI("buffer pts: %ld, bufferLen: %zu, frameNumber: %zu", hisAMeta->pts_, buffer->GetMemory()->GetSize(), + hisAMeta->frameNum_); + if (bufferMeta->IsExist(Tag::MEDIA_START_TIME)) { + hisAMeta->extPts_ = Plugin::AnyCast(bufferMeta->GetMeta(Tag::MEDIA_START_TIME)); + } + if (bufferMeta->IsExist(Tag::AUDIO_SAMPLE_PER_FRAME)) { + hisAMeta->extFrameNum_ = Plugin::AnyCast(bufferMeta->GetMeta(Tag::AUDIO_SAMPLE_PER_FRAME)); + } + jsonObj[AVT_DATA_PARAM] = hisAMeta->MarshalVideoMeta(); + + std::string jsonStr = jsonObj.dump(); + AVTRANS_LOGI("jsonStr->bufLen %zu, jsonStR: %s", jsonStr.length(), jsonStr.c_str()); + + auto bufferData = buffer->GetMemory(); + StreamData data = {reinterpret_cast(const_cast(bufferData->GetReadOnlyData())), + bufferData->GetSize()}; + StreamData ext = {const_cast(jsonStr.c_str()), jsonStr.length()}; + + int32_t ret = SoftbusChannelAdapter::GetInstance().SendStreamData(sessionName_, peerDevId_, &data, &ext); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Send data to softbus failed."); + } +} + +void DsoftbusOutputPlugin::DataQueueClear(std::queue> &queue) +{ + std::queue> empty; + swap(empty, queue); +} + +Status DsoftbusOutputPlugin::SetDataCallback(AVDataCallback callback) +{ + AVTRANS_LOGI("SetDataCallback"); + return Status::OK; +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/dsoftbus_output_plugin.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/dsoftbus_output_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..3ad6c4aa7fab39f7e7ca2eceb3feeccf169e3493 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output/dsoftbus_output_plugin.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSOFTBUS_H +#define OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSOFTBUS_H + +#include +#include +#include +#include +#include +#include +#include + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_output_plugin.h" +#include "nlohmann/json.hpp" +#include "foundation/osal/thread/task.h" +#include "plugin_types.h" +#include "plugin_manager.h" +#include "softbus_channel_adapter.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace Media::Plugin; + +using json = nlohmann::json; +using AVDataCallback = std::function)>; + +class DsoftbusOutputPlugin : public AvTransOutputPlugin, + public ISoftbusChannelListener, + public std::enable_shared_from_this { +public: + explicit DsoftbusOutputPlugin(std::string name); + ~DsoftbusOutputPlugin(); + + Status Init() override; + Status Deinit() override; + Status Prepare() override; + Status Reset() override; + Status Start() override; + Status Stop() override; + Status GetParameter(Tag tag, ValueType &value) override; + Status SetParameter(Tag tag, const ValueType &value) override; + Status PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) override; + Status SetCallback(Callback *cb) override; + Status SetDataCallback(AVDataCallback callback) override; + + // interface from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + +private: + Status OpenSoftbusChannel(); + void SendDataToSoftbus(std::shared_ptr &buffer); + void DataQueueClear(std::queue> &queue); + void CloseSoftbusChannel(); + void FeedChannelData(); + +private: + std::string ownerName_; + std::string sessionName_; + std::string peerDevId_; + std::condition_variable dataCond_; + std::mutex dataQueueMtx_; + Media::OSAL::Mutex operationMutes_ {}; + std::shared_ptr bufferPopTask_; + std::queue> dataQueue_; + std::map paramsMap_; + State state_ {State::CREATED}; + Callback* eventsCb_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSOFTBUS_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/BUILD.gn b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a24e478f4d7f5fa51c783a76cc76571a0f306034 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +ohos_source_set("plugin_AVTransDsoftbusOutputAudio") { + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${dsoftbus_path}/interfaces/kits/transport", + "${dsoftbus_path}/interfaces/kits/bus_center", + "${dsoftbus_path}/interfaces/kits/common", + "//third_party/json/include", + ] + + sources = [ "dsoftbus_output_audio_plugin.cpp" ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + public_configs = [ "${plugin_path}/plugins:avtrans_cflags" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dsoftbus_output_audio_plugin\"", + "LOG_DOMAIN=0xD004100", + ] + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/dsoftbus_output_audio_plugin.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/dsoftbus_output_audio_plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62d3da244e0b24a237baddd7ffa612bb4edf52ff --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/dsoftbus_output_audio_plugin.cpp @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dsoftbus_output_audio_plugin.h" + +#include "foundation/utils/constants.h" +#include "plugin/common/plugin_caps_builder.h" +#include "plugin/factory/plugin_factory.h" +#include "plugin/interface/generic_plugin.h" + +namespace OHOS { +namespace DistributedHardware { + +GenericPluginDef CreateDsoftbusOutputAudioPluginDef() +{ + GenericPluginDef definition; + definition.name = "AVTransDsoftbusOutputAudioPlugin"; + definition.pkgName = "AVTransDsoftbusOutputAudioPlugin"; + definition.description = "Audio transport to dsoftbus"; + definition.rank = PLUGIN_RANK; + definition.creator = [] (const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + + definition.pkgVersion = AVTRANS_OUTPUT_API_VERSION; + definition.license = LicenseType::APACHE_V2; + + CapabilityBuilder capBuilder; + capBuilder.SetMime(OHOS::Media::MEDIA_MIME_AUDIO_AAC); + DiscreteCapability valuesSampleRate = {8000, 11025, 12000, 16000, + 22050, 24000, 32000, 44100, 48000, 64000, 96000}; + capBuilder.SetAudioSampleRateList(valuesSampleRate); + DiscreteCapability valuesSampleFormat = {AudioSampleFormat::S16}; + capBuilder.SetAudioSampleFormatList(valuesSampleFormat); + definition.inCaps.push_back(capBuilder.Build()); + return definition; +} + +static AutoRegisterPlugin g_registerPluginHelper(CreateDsoftbusOutputAudioPluginDef()); + +DsoftbusOutputAudioPlugin::DsoftbusOutputAudioPlugin(std::string name) + : AvTransOutputPlugin(std::move(name)) +{ + AVTRANS_LOGI("ctor."); +} + +DsoftbusOutputAudioPlugin::~DsoftbusOutputAudioPlugin() +{ + AVTRANS_LOGI("dtor."); +} + +Status DsoftbusOutputAudioPlugin::Init() +{ + AVTRANS_LOGI("Init."); + Media::OSAL::ScopedLock lock(operationMutes_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DsoftbusOutputAudioPlugin::Deinit() +{ + AVTRANS_LOGI("Deinit."); + return Reset(); +} + +Status DsoftbusOutputAudioPlugin::Prepare() +{ + AVTRANS_LOGI("Prepare"); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::INITIALIZED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + + sessionName_ = ownerName_ + "_" + SENDER_DATA_SESSION_NAME_SUFFIX; + int32_t ret = SoftbusChannelAdapter::GetInstance().CreateChannelServer(TransName2PkgName(ownerName_), sessionName_); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Create Session Server failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + ret = SoftbusChannelAdapter::GetInstance().RegisterChannelListener(sessionName_, peerDevId_, this); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Register channel listener failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + + if (!bufferPopTask_) { + bufferPopTask_ = std::make_shared("audioBufferQueuePopThread"); + bufferPopTask_->RegisterHandler([this] { FeedChannelData(); }); + } + + ValueType channelsValue; + TRUE_RETURN_V_MSG_E(GetParameter(Tag::AUDIO_CHANNELS, channelsValue) != Status::OK, + Status::ERROR_UNKNOWN, "Not found AUDIO_CHANNELS"); + channels_ = static_cast(Plugin::AnyCast(channelsValue)); + + ValueType sampleRateValue; + TRUE_RETURN_V_MSG_E(GetParameter(Tag::AUDIO_SAMPLE_RATE, sampleRateValue) != Status::OK, + Status::ERROR_UNKNOWN, "Not found AUDIO_SAMPLE_RATE"); + sampleRate_ = static_cast(Plugin::AnyCast(sampleRateValue)); + AVTRANS_LOGI("channels_ = %d, sampleRate_ = %d.", channels_, sampleRate_); + + state_ = State::PREPARED; + return Status::OK; +} + +Status DsoftbusOutputAudioPlugin::Reset() +{ + AVTRANS_LOGI("Reset"); + Media::OSAL::ScopedLock lock(operationMutes_); + paramsMap_.clear(); + if (bufferPopTask_) { + bufferPopTask_->Stop(); + bufferPopTask_.reset(); + } + DataQueueClear(dataQueue_); + eventsCb_ = nullptr; + SoftbusChannelAdapter::GetInstance().RemoveChannelServer(TransName2PkgName(ownerName_), sessionName_); + SoftbusChannelAdapter::GetInstance().UnRegisterChannelListener(sessionName_, peerDevId_); + state_ = State::INITIALIZED; + return Status::OK; +} + +Status DsoftbusOutputAudioPlugin::Start() +{ + AVTRANS_LOGI("Dsoftbus Output Plugin start."); + Media::OSAL::ScopedLock lock(operationMutes_); + if (state_ != State::PREPARED) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + Status ret = OpenSoftbusChannel(); + if (ret != Status::OK) { + AVTRANS_LOGE("OpenSoftbusSession failed."); + return Status::ERROR_INVALID_OPERATION; + } + DataQueueClear(dataQueue_); + bufferPopTask_->Start(); + state_ = State::RUNNING; + return Status::OK; +} + +Status DsoftbusOutputAudioPlugin::Stop() +{ + AVTRANS_LOGI("Dsoftbus Output Plugin stop."); + if (state_ != State::RUNNING) { + AVTRANS_LOGE("The state is wrong."); + return Status::ERROR_WRONG_STATE; + } + state_ = State::PREPARED; + bufferPopTask_->Stop(); + DataQueueClear(dataQueue_); + CloseSoftbusChannel(); + return Status::OK; +} + +Status DsoftbusOutputAudioPlugin::GetParameter(Tag tag, ValueType &value) +{ + auto res = paramsMap_.find(tag); + if (res != paramsMap_.end()) { + value = res->second; + return Status::OK; + } + return Status::ERROR_NOT_EXISTED; +} + +Status DsoftbusOutputAudioPlugin::SetParameter(Tag tag, const ValueType &value) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (tag == Tag::MEDIA_DESCRIPTION) { + ParseChannelDescription(Plugin::AnyCast(value), ownerName_, peerDevId_); + } + paramsMap_.insert(std::pair(tag, value)); + return Status::OK; +} + +Status DsoftbusOutputAudioPlugin::SetCallback(Callback *cb) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (cb == nullptr) { + AVTRANS_LOGE("SetCallback failed, cb is nullptr."); + return Status::ERROR_INVALID_OPERATION; + } + eventsCb_ = cb; + AVTRANS_LOGI("SetCallback success"); + return Status::OK; +} + +Status DsoftbusOutputAudioPlugin::OpenSoftbusChannel() +{ + std::string peerSessName_ = ownerName_ + "_" + RECEIVER_DATA_SESSION_NAME_SUFFIX; + int32_t ret = SoftbusChannelAdapter::GetInstance().OpenSoftbusChannel(sessionName_, peerSessName_, peerDevId_); + if ((ret != DH_AVT_SUCCESS) && (ret != ERR_DH_AVT_SESSION_HAS_OPENED)) { + AVTRANS_LOGE("Open softbus channel failed ret: %d.", ret); + return Status::ERROR_INVALID_OPERATION; + } + return Status::OK; +} + +void DsoftbusOutputAudioPlugin::CloseSoftbusChannel() +{ + int32_t ret = SoftbusChannelAdapter::GetInstance().CloseSoftbusChannel(sessionName_, peerDevId_); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Close softbus channle failed ret: %s.", ret); + } +} + +void DsoftbusOutputAudioPlugin::OnChannelEvent(const AVTransEvent &event) +{ + AVTRANS_LOGI("OnChannelEvent enter, event type: %d", event.type); + if (eventsCb_ == nullptr) { + AVTRANS_LOGE("OnChannelEvent failed, event callback is nullptr."); + return; + } + switch (event.type) { + case EventType::EVENT_CHANNEL_OPENED: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_OPENED}); + break; + } + case EventType::EVENT_CHANNEL_OPEN_FAIL: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_OPEN_FAIL}); + break; + } + case EventType::EVENT_CHANNEL_CLOSED: { + eventsCb_->OnEvent({PluginEventType::EVENT_CHANNEL_CLOSED}); + break; + } + default: + AVTRANS_LOGE("Unsupported event type."); + } +} + +void DsoftbusOutputAudioPlugin::OnStreamReceived(const StreamData *data, const StreamData *ext) +{ + (void)data; + (void)ext; +} + +Status DsoftbusOutputAudioPlugin::PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) +{ + Media::OSAL::ScopedLock lock(operationMutes_); + if (buffer == nullptr || buffer->IsEmpty()) { + AVTRANS_LOGE("Buffer is nullptr."); + return Status::ERROR_NULL_POINTER; + } + while (dataQueue_.size() >= DATA_QUEUE_MAX_SIZE) { + AVTRANS_LOGE("Data queue overflow."); + dataQueue_.pop(); + } + + int32_t bufSize = buffer->GetMemory()->GetSize(); + auto tempBuffer = std::make_shared(BufferMetaType::AUDIO); + tempBuffer->pts = buffer->pts; + tempBuffer->AllocMemory(nullptr, bufSize); + tempBuffer->GetMemory()->Write(buffer->GetMemory()->GetReadOnlyData(), bufSize); + tempBuffer->UpdateBufferMeta(*(buffer->GetBufferMeta()->Clone())); + dataQueue_.push(tempBuffer); + dataCond_.notify_all(); + return Status::OK; +} + +void DsoftbusOutputAudioPlugin::FeedChannelData() +{ + while (state_ == State::RUNNING) { + std::shared_ptr buffer; + { + std::unique_lock lock(dataQueueMtx_); + dataCond_.wait_for(lock, std::chrono::milliseconds(PLUGIN_TASK_WAIT_TIME), + [this]() { return !dataQueue_.empty(); }); + if (state_ != State::RUNNING) { + return; + } + if (dataQueue_.empty()) { + continue; + } + buffer = dataQueue_.front(); + dataQueue_.pop(); + } + if (buffer == nullptr) { + AVTRANS_LOGE("Data is null"); + continue; + } + SendDataToSoftbus(buffer); + } +} + +void DsoftbusOutputAudioPlugin::SendDataToSoftbus(std::shared_ptr &buffer) +{ + json jsonObj; + auto bufferMeta = buffer->GetBufferMeta(); + BufferMetaType metaType = bufferMeta->GetType(); + jsonObj[AVT_DATA_META_TYPE] = metaType; + if (metaType != BufferMetaType::AUDIO) { + AVTRANS_LOGE("metaType is wrong"); + return; + } + auto hisAMeta = std::make_shared(); + if (!buffer->GetBufferMeta()->IsExist(Tag::USER_FRAME_NUMBER)) { + hisAMeta->frameNum_ = DEFAULT_FRAME_NUMBER; + } else { + hisAMeta->frameNum_ = Plugin::AnyCast(buffer->GetBufferMeta()->GetMeta(Tag::USER_FRAME_NUMBER)); + } + if (!buffer->GetBufferMeta()->IsExist(Tag::USER_FRAME_PTS)) { + hisAMeta->pts_ = DEFAULT_PTS; + } else { + hisAMeta->pts_ = Plugin::AnyCast(buffer->GetBufferMeta()->GetMeta(Tag::USER_FRAME_PTS)); + } + jsonObj[AVT_DATA_PARAM] = hisAMeta->MarshalAudioMeta(); + + auto bufferData = buffer->GetMemory(); + std::string jsonStr = jsonObj.dump(); + AVTRANS_LOGI("buffer data len = %zu, ext data len = %zu, ext data = %s", bufferData->GetSize(), + jsonStr.length(), jsonStr.c_str()); + + StreamData data = {reinterpret_cast(const_cast(bufferData->GetReadOnlyData())), + bufferData->GetSize()}; + StreamData ext = {const_cast(jsonStr.c_str()), jsonStr.length()}; + + int32_t ret = SoftbusChannelAdapter::GetInstance().SendStreamData(sessionName_, peerDevId_, &data, &ext); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Send data to softbus failed."); + } +} + +void DsoftbusOutputAudioPlugin::DataQueueClear(std::queue> &queue) +{ + std::queue> empty; + swap(empty, queue); +} + +Status DsoftbusOutputAudioPlugin::SetDataCallback(AVDataCallback callback) +{ + AVTRANS_LOGI("SetDataCallback"); + return Status::OK; +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/dsoftbus_output_audio_plugin.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/dsoftbus_output_audio_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..77ee34920b1566f78b52ddb91973d387efa22df6 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/dsoftbus_output_audio/dsoftbus_output_audio_plugin.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSOFTBUS_H +#define OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSOFTBUS_H + +#include +#include +#include +#include +#include +#include +#include + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_output_plugin.h" +#include "nlohmann/json.hpp" +#include "foundation/osal/thread/task.h" +#include "plugin_types.h" +#include "plugin_manager.h" +#include "softbus_channel_adapter.h" + +namespace OHOS { +namespace DistributedHardware { + +using namespace Media::Plugin; + +using json = nlohmann::json; +using AVDataCallback = std::function)>; + +class DsoftbusOutputAudioPlugin : public AvTransOutputPlugin, + public ISoftbusChannelListener, + public std::enable_shared_from_this { +public: + explicit DsoftbusOutputAudioPlugin(std::string name); + ~DsoftbusOutputAudioPlugin(); + + Status Init() override; + Status Deinit() override; + Status Prepare() override; + Status Reset() override; + Status Start() override; + Status Stop() override; + Status GetParameter(Tag tag, ValueType &value) override; + Status SetParameter(Tag tag, const ValueType &value) override; + Status PushData(const std::string &inPort, std::shared_ptr buffer, int32_t offset) override; + Status SetCallback(Callback *cb) override; + Status SetDataCallback(AVDataCallback callback) override; + + // interface from ISoftbusChannelListener + void OnChannelEvent(const AVTransEvent &event) override; + void OnStreamReceived(const StreamData *data, const StreamData *ext) override; + +private: + Status OpenSoftbusChannel(); + void SendDataToSoftbus(std::shared_ptr &buffer); + void DataQueueClear(std::queue> &queue); + void CloseSoftbusChannel(); + void FeedChannelData(); + +private: + std::string ownerName_; + std::string sessionName_; + std::string peerDevId_; + std::condition_variable dataCond_; + std::mutex dataQueueMtx_; + Media::OSAL::Mutex operationMutes_ {}; + std::shared_ptr bufferPopTask_; + std::queue> dataQueue_; + std::map paramsMap_; + State state_ {State::CREATED}; + Callback* eventsCb_ = nullptr; + uint32_t sampleRate_ {0}; + uint32_t channels_ {0}; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_AV_TRANS_ENGINE_PLUGINS_OUTPUT_DSOFTBUS_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/controllable_output.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/controllable_output.h new file mode 100644 index 0000000000000000000000000000000000000000..7a01e4f3a74e28f614e7ff85dce9d12823d35102 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/controllable_output.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_CONTROLLABLE_OUTPUT_H +#define OHOS_CONTROLLABLE_OUTPUT_H +#include +#include "plugin_buffer.h" +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +class ControllableOutput { +public: + virtual ~ControllableOutput() = default; + virtual void OnOutput(const std::shared_ptr& data) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_CONTROLLABLE_OUTPUT_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..06bba3a414d701b53f7b65df6e4e30d40143434f --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller.h @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_OUTPUT_CONTROLLER_H +#define OHOS_OUTPUT_CONTROLLER_H +#include +#include +#include +#include +#include +#include +#include "output_controller_listener.h" +#include "time_statistician.h" +#include "output_controller_constants.h" +#include "plugin_buffer.h" +#include "plugin_types.h" +#include "av_trans_log.h" +#include "av_trans_utils.h" +#include "av_sync_utils.h" +#include "event_handler.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +class OutputController { +public: + virtual ~OutputController(); + virtual void PrepareSmooth(); + virtual void PrepareSync(); + virtual void InitBaseline(const int64_t timeStampBaseline, const int64_t clockBaseline); + virtual void InitTimeStatistician(); + virtual int32_t NotifyOutput(const std::shared_ptr& data); + +public: + enum class ControlStatus { + START, + STOP, + RELEASE, + STARTED, + STOPPED, + RELEASED, + }; + enum class ControlMode { + SMOOTH, + SYNC, + }; + void PushData(std::shared_ptr& data); + ControlStatus StartControl(); + void PrepareControl(); + ControlStatus StopControl(); + ControlStatus ReleaseControl(); + void RegisterListener(const std::shared_ptr& listener); + void UnregisterListener(); + + void SetBufferTime(const uint32_t time); + void SetTimeInitState(const bool state); + void SetBaselineInitState(const bool state); + void SetProcessDynamicBalanceState(const bool state); + void SetAllowControlState(const bool state); + + uint32_t GetBufferTime(); + bool GetTimeInitState(); + bool GetBaselineInitState(); + bool GetProcessDynamicBalanceState(); + bool GetAllowControlState(); + + void SetClockBaseline(const int64_t clockBaseline); + void SetTimeStampBaseline(const int64_t timeStmapBaseline); + + void SetAverIntervalDiffThre(const uint32_t thre); + void SetDynamicBalanceThre(const uint8_t thre); + void SetPushOnceDiffThre(const uint32_t thre); + void SetTimeStampOnceDiffThre(const uint32_t thre); + void SetAdjustSleepFactor(const float factor); + void SetWaitClockFactor(const float factor); + void SetTrackClockFactor(const float factor); + void SetWaitClockThre(const int64_t thre); + void SetTrackClockThre(const int64_t thre); + void SetSleepThre(const int64_t thre); + void SetVideoFrontTime(const int64_t time); + void SetVideoBackTime(const int64_t time); + void SetAudioFrontTime(const int64_t time); + void SetAudioBackTime(const int64_t time); + + Status GetParameter(Tag tag, ValueType& value); + Status SetParameter(Tag tag, const ValueType& value); + +private: + ControlMode GetControlMode(); + ControlStatus GetControlStatus(); + void SetControlMode(ControlMode mode); + void SetControlStatus(ControlStatus status); + + void InitTime(const int64_t enterTime, const int64_t timeStamp); + void RecordTime(const int64_t enterTime, const int64_t timeStamp); + void CheckSyncInfo(const std::shared_ptr& data); + void CalProcessTime(const std::shared_ptr& data); + void SetClockTime(const int64_t clockTime); + int64_t GetClockTime(); + void SetDevClockDiff(int32_t diff); + int32_t GetDevClockDiff(); + int32_t AcquireSyncClockTime(const std::shared_ptr& data); + size_t GetQueueSize(); + + void ClearQueue(std::queue>& queue); + + bool CheckIsTimeInit(); + bool CheckIsBaselineInit(); + bool CheckIsAllowControl(); + bool CheckIsClockInvalid(const std::shared_ptr& data); + bool WaitRereadClockFailed(const std::shared_ptr& data); + bool CheckIsProcessInDynamicBalance(const std::shared_ptr& data); + bool CheckIsProcessInDynamicBalanceOnce(const std::shared_ptr& data); + + void LooperHandle(); + void LooperControl(); + int32_t ControlOutput(const std::shared_ptr& data); + int32_t PostOutputEvent(const std::shared_ptr& data); + void HandleControlResult(const std::shared_ptr& data, int32_t result); + void CalSleepTime(const int64_t timeStamp); + void SyncClock(const std::shared_ptr& data); + void HandleSmoothTime(const std::shared_ptr& data); + void HandleSyncTime(const std::shared_ptr& data); + +protected: + std::queue> dataQueue_; + std::map paramsMap_; + std::shared_ptr statistician_ = nullptr; + std::shared_ptr listener_ = nullptr; + +private: + std::atomic status_ {ControlStatus::RELEASE}; + std::atomic mode_ {ControlMode::SMOOTH}; + std::unique_ptr controlThread_ = nullptr; + std::unique_ptr handlerThread_ = nullptr; + std::shared_ptr handler_ = nullptr; + std::condition_variable controlCon_; + std::condition_variable sleepCon_; + std::condition_variable clockCon_; + std::condition_variable handlerCon_; + std::mutex handlerMutex_; + std::mutex queueMutex_; + std::mutex sleepMutex_; + std::mutex stateMutex_; + std::mutex modeMutex_; + std::mutex clockMutex_; + std::mutex paramMapMutex_; + std::atomic isInDynamicBalance_ = true; + std::atomic isBaselineInit_ = false; + std::atomic isTimeInit_ = false; + std::atomic isAllowControl_ = true; + + const uint32_t QUEUE_MAX_SIZE = 100; + const int64_t GREATER_HALF_REREAD_TIME = 5 * NS_ONE_MS; + const int64_t LESS_HALF_REREAD_TIME = 3 * GREATER_HALF_REREAD_TIME; + int64_t waitClockThre_ = 0; + int64_t trackClockThre_ = 0; + float adjustSleepFactor_ = 0; + float waitClockFactor_ = 0; + float trackClockFactor_ = 0; + uint8_t dynamicBalanceThre_ = 0; + uint8_t dynamicBalanceCount_ = 0; + uint32_t averIntervalDiffThre_ = 0; + uint32_t pushOnceDiffThre_ = 0; + uint32_t timeStampOnceDiffThre_ = 0; + uint32_t bufferTime_ = 0; + int64_t enterTime_ = 0; + int64_t lastEnterTime_ = 0; + int64_t lastTimeStamp_ = 0; + int64_t leaveTime_ = 0; + int64_t timeStampBaseline_ = 0; + std::atomic clockTime_ = 0; + int64_t clockBaseline_ = 0; + int64_t delta_ = 0; + int64_t sleep_ = 0; + int64_t sleepThre_ = 0; + AVTransSharedMemory sharedMem_ = { 0, 0, "" }; + AVSyncClockUnit clockUnit_ = { 0, 0, 0 }; + std::atomic devClockDiff_ = 0; + int64_t aFront_ = 0; + int64_t aBack_ = 0; + int64_t vFront_ = 0; + int64_t vBack_ = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_OUTPUT_CONTROLLER_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller_constants.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..cfe2d0e9e94acfd4cf1a3e92c75c204149486d1e --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller_constants.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_OUTPUT_CONTROLLER_CONSTANTS_H +#define OHOS_OUTPUT_CONTROLLER_CONSTANTS_H + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + NOTIFY_SUCCESS = 0, + NOTIFY_FAILED = 1, +} ControllerListenerState; + +typedef enum { + HANDLE_SUCCESS = 0, + HANDLE_FAILED = 1, +} ControllerHandlerState; + +typedef enum { + OUTPUT_FRAME = 0, + DROP_FRAME = 1, + REPEAT_FREAM = 2, +} ControllerControlResult; + +const std::string LOOPER_CONTROL_THREAD_NAME = "looperControl"; +const std::string OUTPUT_HANDLE_THREAD_NAME = "outputHandle"; + +const int64_t INVALID_TIMESTAMP = 0; +const int64_t INVALID_INTERVAL = 0; +const int64_t FACTOR_DOUBLE = 2; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_OUTPUT_CONTROLLER_CONSTANTS_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller_listener.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..babab49469309a5bd49865b25b320d9aa02368f5 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/output_controller_listener.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_OUTPUT_CONTROLLER_LISTENER_H +#define OHOS_OUTPUT_CONTROLLER_LISTENER_H +#include "controllable_output.h" +#include "plugin_buffer.h" +#include + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +class OutputControllerListener { +public: + OutputControllerListener(std::shared_ptr output) + : output_(output) {} + ~OutputControllerListener() = default; + +public: + int32_t OnOutput(const std::shared_ptr& data); + +private: + std::weak_ptr output_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_OUTPUT_CONTROLLER_LISTENER_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/time_statistician.h b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/time_statistician.h new file mode 100644 index 0000000000000000000000000000000000000000..b8715626271ab316564e054702c598fbd38f71ba --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/include/time_statistician.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_TIME_STATISTICIAN_H +#define OHOS_TIME_STATISTICIAN_H + +#include "plugin_buffer.h" +#include +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +class TimeStatistician { +public: + virtual ~TimeStatistician() = default; + virtual void CalProcessTime(const std::shared_ptr& data); + void CalAverPushInterval(const int64_t pushTime); + void CalAverTimeStampInterval(const int64_t timeStamp); + +public: + int64_t GetAverPushInterval(); + int64_t GetAverTimeStampInterval(); + int64_t GetPushInterval(); + int64_t GetTimeStampInterval(); + void ClearStatistics(); + +public: + int32_t pushIndex_ = 0; + int64_t averPushInterval_ = 0; + int64_t lastPushTime_ = 0; + int64_t pushTime_ = 0; + int64_t pushIntervalSum_ = 0; + int64_t pushInterval_ = 0; + + int32_t timeStampIndex_ = 0; + int64_t averTimeStampInterval_ = 0; + int64_t lastTimeStamp_ = 0; + int64_t timeStamp_ = 0; + int64_t timeStampIntervalSum_ = 0; + int64_t timeStampInterval_ = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_TIME_STATISTICIAN_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/output_controller.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/output_controller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d14e780cde105fbee2cc0fe2ab0b8c093d08bdb2 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/output_controller.cpp @@ -0,0 +1,787 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "output_controller.h" +#include "av_trans_constants.h" +#include "av_trans_errno.h" + +namespace OHOS { +namespace DistributedHardware { +OutputController::~OutputController() +{ + ReleaseControl(); +} + +void OutputController::PushData(std::shared_ptr& data) +{ + int64_t pushTime = GetCurrentTime(); + TRUE_RETURN((GetControlStatus() != ControlStatus::START), + "Control status wrong, push data failed."); + { + std::lock_guard lock(queueMutex_); + if (dataQueue_.size() > QUEUE_MAX_SIZE) { + AVTRANS_LOGE("DataQueue is greater than QUEUE_MAX_SIZE %zu.", QUEUE_MAX_SIZE); + dataQueue_.pop(); + } + CheckSyncInfo(data); + data->GetBufferMeta()->SetMeta(Tag::USER_PUSH_DATA_TIME, pushTime); + dataQueue_.push(data); + AVTRANS_LOGD("Push Data, dataQueue size is %zu.", dataQueue_.size()); + } + if (GetControlMode() == ControlMode::SYNC) { + clockCon_.notify_one(); + } + controlCon_.notify_one(); +} + +OutputController::ControlStatus OutputController::StartControl() +{ + TRUE_RETURN_V_MSG_D((GetControlStatus() == ControlStatus::START), ControlStatus::STARTED, + "Control status is started."); + SetControlStatus(ControlStatus::START); + if (!handlerThread_) { + AVTRANS_LOGD("Init handler thread."); + handlerThread_ = std::make_unique(&OutputController::LooperHandle, this); + std::unique_lock lock(handlerMutex_); + handlerCon_.wait(lock, [this] { + return handler_; + }); + } + if (!controlThread_) { + AVTRANS_LOGD("Init control thread."); + controlThread_ = std::make_unique(&OutputController::LooperControl, this); + } + AVTRANS_LOGI("Start control success."); + return ControlStatus::START; +} + +void OutputController::PrepareControl() +{ + if (GetControlMode() == ControlMode::SMOOTH) { + PrepareSmooth(); + } else { + PrepareSync(); + } + InitTimeStatistician(); + AVTRANS_LOGI("Prepare control success."); +} + +OutputController::ControlStatus OutputController::StopControl() +{ + TRUE_RETURN_V_MSG_D((GetControlStatus() == ControlStatus::STOP), ControlStatus::STOPPED, + "Control status is stopped."); + SetControlStatus(ControlStatus::STOP); + ClearQueue(dataQueue_); + AVTRANS_LOGI("Stop control success."); + return ControlStatus::STOP; +} + +OutputController::ControlStatus OutputController::ReleaseControl() +{ + TRUE_RETURN_V_MSG_D((GetControlStatus() == ControlStatus::RELEASE), ControlStatus::RELEASED, + "Control status is released."); + SetControlStatus(ControlStatus::RELEASE); + statistician_ = nullptr; + UnregisterListener(); + controlCon_.notify_one(); + sleepCon_.notify_one(); + clockCon_.notify_one(); + if (handler_) { + handler_->GetEventRunner()->Stop(); + } + if (handlerThread_) { + handlerThread_->join(); + handlerThread_ = nullptr; + } + if (controlThread_) { + controlThread_->join(); + controlThread_ = nullptr; + } + ClearQueue(dataQueue_); + paramsMap_.clear(); + AVTRANS_LOGI("Release control success."); + return ControlStatus::RELEASE; +} + +Status OutputController::GetParameter(Tag tag, ValueType& value) +{ + { + std::lock_guard lock(paramMapMutex_); + auto iter = paramsMap_.find(tag); + if (iter != paramsMap_.end()) { + value = iter->second; + return Status::OK; + } + return Status::ERROR_NOT_EXISTED; + } +} + +Status OutputController::SetParameter(Tag tag, const ValueType& value) +{ + { + std::lock_guard lock(paramMapMutex_); + switch (tag) { + case Tag::USER_AV_SYNC_GROUP_INFO: { + std::string jsonStr = Plugin::AnyCast(value); + AVTRANS_LOGD("Set parameter USER_AV_SYNC_GROUP_INFO: %s", jsonStr.c_str()); + break; + } + case Tag::USER_SHARED_MEMORY_FD: { + std::string jsonStr = Plugin::AnyCast(value); + sharedMem_ = UnmarshalSharedMemory(jsonStr); + AVTRANS_LOGD("Set parameter USER_SHARED_MEMORY_FD: %s, unmarshal sharedMem fd: %d, " + + "size: %d, name: %s", jsonStr.c_str(), sharedMem_.fd, sharedMem_.size, + sharedMem_.name.c_str()); + break; + } + case Tag::USER_TIME_SYNC_RESULT: { + std::string jsonStr = Plugin::AnyCast(value); + int32_t devClockDiff = atoi(jsonStr.c_str()); + SetDevClockDiff(devClockDiff); + AVTRANS_LOGD("Set parameter USER_TIME_SYNC_RESULT: %s, devClockDiff is %d.", + jsonStr.c_str(), devClockDiff); + break; + } + default: + AVTRANS_LOGE("Invalid tag."); + } + paramsMap_.insert(std::make_pair(tag, value)); + return Status::OK; + } +} + +void OutputController::PrepareSync() +{ + AVTRANS_LOGI("Prepare sync."); + SetProcessDynamicBalanceState(true); + SetTimeInitState(false); + SetBaselineInitState(false); + SetAllowControlState(true); + SetBufferTime(0); + SetAdjustSleepFactor(0); + SetWaitClockThre(0); + SetTrackClockThre(0); + SetSleepThre(0); + SetAudioFrontTime(0); + SetAudioBackTime(0); + SetVideoFrontTime(0); + SetVideoBackTime(0); +} + +void OutputController::PrepareSmooth() +{ + AVTRANS_LOGI("Prepare smooth."); + SetProcessDynamicBalanceState(false); + SetTimeInitState(false); + SetBaselineInitState(false); + SetAllowControlState(true); + SetBufferTime(0); + SetAdjustSleepFactor(0); + SetWaitClockFactor(0); + SetTrackClockFactor(0); + SetSleepThre(0); + SetDynamicBalanceThre(0); + SetAverIntervalDiffThre(0); + SetPushOnceDiffThre(0); + SetTimeStampOnceDiffThre(0); +} + +void OutputController::LooperHandle() +{ + prctl(PR_SET_NAME, OUTPUT_HANDLE_THREAD_NAME.c_str()); + auto runner = AppExecFwk::EventRunner::Create(false); + { + std::lock_guard lock(handlerMutex_); + handler_ = std::make_shared(runner); + } + handlerCon_.notify_one(); + runner->Run(); +} + +void OutputController::LooperControl() +{ + prctl(PR_SET_NAME, LOOPER_CONTROL_THREAD_NAME.c_str()); + while (GetControlStatus() != ControlStatus::RELEASE) { + std::shared_ptr data = nullptr; + { + std::unique_lock lock(queueMutex_); + controlCon_.wait(lock, [this] { + return ((!dataQueue_.empty() && GetControlStatus() == ControlStatus::START) + || (GetControlStatus() == ControlStatus::RELEASE)); + }); + if (GetControlStatus() == ControlStatus::RELEASE) { + continue; + } + data = dataQueue_.front(); + } + HandleControlResult(data, ControlOutput(data)); + } +} + +int32_t OutputController::ControlOutput(const std::shared_ptr& data) +{ + enterTime_ = GetCurrentTime(); + int64_t timeStamp = data->pts; + TRUE_RETURN_V_MSG_D((timeStamp == INVALID_TIMESTAMP || !CheckIsAllowControl()), OUTPUT_FRAME, + "Direct output."); + if (CheckIsClockInvalid(data) || !CheckIsProcessInDynamicBalance(data)) { + CalProcessTime(data); + RecordTime(enterTime_, timeStamp); + return OUTPUT_FRAME; + } + CalProcessTime(data); + if (!CheckIsTimeInit()) { + InitTime(enterTime_, timeStamp); + } + if (!CheckIsBaselineInit()) { + InitBaseline(timeStamp, GetClockTime()); + } + CalSleepTime(timeStamp); + SyncClock(data); + RecordTime(enterTime_, timeStamp); + return OUTPUT_FRAME; +} + +void OutputController::CheckSyncInfo(const std::shared_ptr& data) +{ + auto bufferMeta = data->GetBufferMeta(); + bool isAFrameNumberExist = bufferMeta->IsExist(Tag::AUDIO_SAMPLE_PER_FRAME); + bool isAPtsExist = bufferMeta->IsExist(Tag::MEDIA_START_TIME); + if (GetControlMode() == ControlMode::SYNC && (!isAFrameNumberExist || !isAPtsExist)) { + ClearQueue(dataQueue_); + sleepCon_.notify_one(); + clockCon_.notify_one(); + SetControlMode(ControlMode::SMOOTH); + AVTRANS_LOGI("Stop sync and start smooth, aFrameNumberExist: %d, aPtsExist: %d.", + isAFrameNumberExist, isAPtsExist); + return; + } + if (GetControlMode() == ControlMode::SMOOTH && isAFrameNumberExist && isAPtsExist) { + ClearQueue(dataQueue_); + sleepCon_.notify_one(); + clockCon_.notify_one(); + SetControlMode(ControlMode::SYNC); + AVTRANS_LOGI("Stop smooth and start sync, aFrameNumberExist: %d, aPtsExist: %d.", + isAFrameNumberExist, isAPtsExist); + } +} + +void OutputController::CalProcessTime(const std::shared_ptr& data) +{ + if (statistician_) { + statistician_->CalProcessTime(data); + } +} + +void OutputController::InitTimeStatistician() +{ + if (!statistician_) { + AVTRANS_LOGD("Init time statistician."); + statistician_ = std::make_shared(); + } + statistician_->ClearStatistics(); + AVTRANS_LOGI("Start time statistics."); +} + +void OutputController::RecordTime(const int64_t enterTime, const int64_t timeStamp) +{ + lastEnterTime_ = enterTime; + lastTimeStamp_ = timeStamp; + leaveTime_ = GetCurrentTime(); + SetTimeInitState(true); +} + +void OutputController::InitTime(const int64_t enterTime, const int64_t timeStamp) +{ + delta_ = 0; + sleep_ = 0; + lastEnterTime_ = enterTime; + lastTimeStamp_ = timeStamp; + leaveTime_ = enterTime; + SetTimeInitState(true); +} + +bool OutputController::CheckIsClockInvalid(const std::shared_ptr& data) +{ + if (GetControlMode() == ControlMode::SMOOTH) { + SetClockTime(enterTime_); + AVTRANS_LOGD("Control mode is smooth, clock is valid."); + return false; + } + int32_t ret = AcquireSyncClockTime(data); + if (ret == ERR_DH_AVT_MASTER_NOT_READY) { + AVTRANS_LOGD("Master clock not ready, wait reread clock."); + return WaitRereadClockFailed(data); + } + TRUE_RETURN_V_MSG_E((ret != DH_AVT_SUCCESS), true, "Read unit clock is invalid."); + return false; +} + +int32_t OutputController::AcquireSyncClockTime(const std::shared_ptr& data) +{ + TRUE_RETURN_V_MSG_E(((sharedMem_.fd <= 0) || (sharedMem_.size <= 0) || sharedMem_.name.empty()), + ERR_DH_AVT_SHARED_MEMORY_FAILED, "Parameter USER_SHARED_MEMORY_FD info error."); + AVTransSharedMemory sharedMem; + sharedMem.fd = sharedMem_.fd; + sharedMem.size = sharedMem_.size; + sharedMem.name = sharedMem_.name; + AVSyncClockUnit clockUnit; + clockUnit.pts = INVALID_TIMESTAMP; + auto bufferMeta = data->GetBufferMeta(); + clockUnit.frameNum = Plugin::AnyCast(bufferMeta->GetMeta(Tag::AUDIO_SAMPLE_PER_FRAME)); + int32_t ret = ReadClockUnitFromMemory(sharedMem, clockUnit); + if (ret == DH_AVT_SUCCESS) { + TRUE_RETURN_V_MSG_D((clockUnit.pts == INVALID_TIMESTAMP), ERR_DH_AVT_SHARED_MEMORY_FAILED, + "Read invalid clock."); + clockUnit_.pts = clockUnit.pts; + clockUnit_.frameNum = clockUnit.frameNum; + SetClockTime(clockUnit_.pts); + AVTRANS_LOGD("Acquire sync clock success, pts: %lld.", clockUnit_.pts); + } + return ret; +} + +bool OutputController::WaitRereadClockFailed(const std::shared_ptr& data) +{ + const uint32_t halfQueueSize = QUEUE_MAX_SIZE / 2; + while (GetQueueSize() < QUEUE_MAX_SIZE) { + if (GetQueueSize() < halfQueueSize) { + { + AVTRANS_LOGD("Dataqueue size is less than half size, wait notify."); + std::unique_lock lock(clockMutex_); + int64_t rereadTime = LESS_HALF_REREAD_TIME; + if (statistician_) { + rereadTime = statistician_->GetAverPushInterval() * FACTOR_DOUBLE; + } + clockCon_.wait_for(lock, std::chrono::nanoseconds(rereadTime), + [this] { return (GetControlStatus() != ControlStatus::START); }); + } + } else if (GetQueueSize() >= halfQueueSize) { + { + AVTRANS_LOGD("Dataqueue size is greater than half size, scheduled %lld query.", + GREATER_HALF_REREAD_TIME); + std::unique_lock lock(clockMutex_); + clockCon_.wait_for(lock, std::chrono::nanoseconds(GREATER_HALF_REREAD_TIME), + [this] { return (GetControlStatus() != ControlStatus::START); }); + } + } + int32_t ret = AcquireSyncClockTime(data); + TRUE_RETURN_V_MSG_D((ret == DH_AVT_SUCCESS || GetControlMode() == ControlMode::SMOOTH), false, + "Wait reread clock success."); + } + return true; +} + +bool OutputController::CheckIsProcessInDynamicBalance(const std::shared_ptr& data) +{ + TRUE_RETURN_V_MSG_D((GetControlMode() == ControlMode::SYNC || GetProcessDynamicBalanceState()), true, + "Process in dynamic balance."); + if (CheckIsProcessInDynamicBalanceOnce(data)) { + dynamicBalanceCount_++; + } else { + dynamicBalanceCount_ = 0; + } + if (dynamicBalanceCount_ >= dynamicBalanceThre_) { + AVTRANS_LOGD("Process meet dynamic balance condition."); + { + std::lock_guard lock(queueMutex_); + ClearQueue(dataQueue_); + } + SetProcessDynamicBalanceState(true); + return true; + } + return false; +} + +bool OutputController::CheckIsProcessInDynamicBalanceOnce(const std::shared_ptr& data) +{ + TRUE_RETURN_V_MSG_E((!statistician_), false, "Statistician is nullptr."); + int64_t pushInterval = statistician_->GetPushInterval(); + int64_t timeStampInterval = statistician_->GetTimeStampInterval(); + int64_t averPushInterval = statistician_->GetAverPushInterval(); + int64_t averTimeStamapInterval = statistician_->GetAverTimeStampInterval(); + int64_t averIntervalDiff = averPushInterval - averTimeStamapInterval; + int64_t pushOnceDiff = pushInterval - averPushInterval; + int64_t timeStampOnceDiff = timeStampInterval - averTimeStamapInterval; + return (averPushInterval != 0) && (averTimeStamapInterval != 0) && + (llabs(averIntervalDiff) < averIntervalDiffThre_) && (llabs(pushOnceDiff) < pushOnceDiffThre_) + && (llabs(timeStampOnceDiff) < timeStampOnceDiffThre_); +} + +void OutputController::InitBaseline(const int64_t timeStampBaseline, const int64_t clockBaseline) +{ + SetTimeStampBaseline(timeStampBaseline); + SetClockBaseline(clockBaseline + bufferTime_); + SetBaselineInitState(true); +} + +void OutputController::CalSleepTime(const int64_t timeStamp) +{ + int64_t interval = timeStamp - lastTimeStamp_; + int64_t elapse = enterTime_ - leaveTime_; + int64_t render = enterTime_ - lastEnterTime_; + int64_t delta = render - sleep_ - elapse; + delta_ += delta; + sleep_ = interval - elapse; + AVTRANS_LOGD("Control frame pts: %lld, interval: %lld, elapse: %lld, render: %lld, delta: %lld," + + " delat count: %lld, sleep: %lld.", timeStamp, interval, elapse, render, delta, delta_, sleep_); + TRUE_RETURN((interval == INVALID_INTERVAL), "Interverl is Invalid."); + const int64_t adjustThre = interval * adjustSleepFactor_; + if (delta_ > adjustThre && sleep_ > 0) { + int64_t sleep = sleep_ - adjustThre; + delta_ -= (sleep < 0) ? sleep_ : adjustThre; + sleep_ = sleep; + AVTRANS_LOGD("Delta greater than thre, adjust sleep to %lld.", sleep_); + } else if (delta_ < -adjustThre) { + sleep_ += delta_; + delta_ = 0; + AVTRANS_LOGD("Delta less than negative thre, adjust sleep to %lld.", sleep_); + } +} + +void OutputController::SyncClock(const std::shared_ptr& data) +{ + if (GetControlMode() == ControlMode::SMOOTH) { + HandleSmoothTime(data); + } else { + HandleSyncTime(data); + } + if (sleep_ > sleepThre_) { + sleep_ = sleepThre_; + AVTRANS_LOGD("Sleep is more than sleepThre %lld, adjust sleep to %lld", sleepThre_, sleep_); + } + if (sleep_ < 0) { + sleep_ = 0; + AVTRANS_LOGD("Sleep less than zero, adjust sleep to zero."); + } + AVTRANS_LOGD("After sync clock, sleep is %lld.", sleep_); + { + std::unique_lock lock(sleepMutex_); + sleepCon_.wait_for(lock, std::chrono::nanoseconds(sleep_), + [this] { return (GetControlStatus() != ControlStatus::START); }); + } +} + +void OutputController::HandleSmoothTime(const std::shared_ptr& data) +{ + TRUE_RETURN(!statistician_, "Statistician is nullptr."); + int64_t interval = statistician_->GetTimeStampInterval(); + TRUE_RETURN((interval == INVALID_INTERVAL), "Interval is Invalid."); + int64_t averTimeStampInterval = statistician_->GetAverTimeStampInterval(); + TRUE_RETURN((averTimeStampInterval == INVALID_INTERVAL), "AverTimeStampInterval is Invalid."); + int64_t waitClockThre = averTimeStampInterval * waitClockFactor_; + int64_t trackClockThre = averTimeStampInterval * trackClockFactor_; + int64_t vTimeStamp = data->pts; + int64_t vcts = (sleep_ > 0) ? (vTimeStamp - sleep_) : vTimeStamp; + int64_t offset = vcts - timeStampBaseline_ - (GetClockTime() - clockBaseline_); + AVTRANS_LOGD("Smooth vTimeStamp: %lld, offset: %lld, waitClockThre: %lld, trackClockThre: %lld.", + vTimeStamp, offset, averTimeStampInterval, waitClockThre, trackClockThre); + if (offset > waitClockThre || offset < -trackClockThre) { + sleep_ += offset; + AVTRANS_LOGD("Smooth offset %lld is over than thre, adjust sleep to %lld.", + offset, sleep_); + } +} + +void OutputController::HandleSyncTime(const std::shared_ptr& data) +{ + auto bufferMeta = data->GetBufferMeta(); + int64_t vTimeStamp = data->pts; + uint32_t vFrameNumber = Plugin::AnyCast(bufferMeta->GetMeta(Tag::USER_FRAME_NUMBER)); + int64_t vcts = (sleep_ > 0) ? (vTimeStamp - sleep_) : vTimeStamp; + int64_t aTimeStamp = clockUnit_.pts; + uint32_t aFrameNumber = clockUnit_.frameNum; + int64_t acts = GetClockTime(); + int64_t ctsDiff = vcts - acts; + int64_t offset = (vcts - vFront_ - vBack_) - (acts - aFront_ - aBack_) - GetDevClockDiff(); + AVTRANS_LOGD("Sync vTimeStamp: %lld, vFrameNumber: %" PRIu32 " vcts: %lld, aTimeStamp: %lld, " + + "aFrameNumber: %" PRIu32 " acts: %lld, ctsDiff: %lld, offset: %lld", vTimeStamp, vFrameNumber, + vcts, aTimeStamp, aFrameNumber, acts, ctsDiff, offset); + const int64_t append = (trackClockThre_ + waitClockThre_) / 2; + if (offset > waitClockThre_) { + sleep_ += offset - waitClockThre_ + append; + AVTRANS_LOGD("Sync offset %lld is over than wait thre %lld, adjust sleep to %lld.", + offset, waitClockThre_, sleep_); + } else if (offset < -trackClockThre_) { + sleep_ += offset - trackClockThre_ - append; + AVTRANS_LOGD("Sync offset %lld is over than track thre %lld, adjust sleep to %lld.", + offset, -trackClockThre_, sleep_); + } +} + +void OutputController::HandleControlResult(const std::shared_ptr& data, int32_t result) +{ + switch (result) { + case OUTPUT_FRAME: { + int32_t ret = PostOutputEvent(data); + TRUE_RETURN((ret == HANDLE_FAILED), "Handle result OUTPUT_FRAME failed."); + { + std::lock_guard lock(queueMutex_); + if (!dataQueue_.empty() && data == dataQueue_.front()) { + dataQueue_.pop(); + } + } + break; + } + case DROP_FRAME: { + { + std::lock_guard lock(queueMutex_); + if (!dataQueue_.empty() && data == dataQueue_.front()) { + dataQueue_.pop(); + } + } + break; + } + case REPEAT_FREAM: { + int32_t ret = PostOutputEvent(data); + TRUE_RETURN((ret == HANDLE_FAILED), "Handle result REPEAT_FREAM failed."); + break; + } + default: + AVTRANS_LOGE("Invalid result."); + } +} + +int32_t OutputController::PostOutputEvent(const std::shared_ptr& data) +{ + TRUE_RETURN_V_MSG_E((!handler_), HANDLE_FAILED, "Handler is nullptr."); + auto outputFunc = [this, data]() { + int32_t ret = NotifyOutput(data); + TRUE_RETURN_V_MSG_E((ret == NOTIFY_FAILED), HANDLE_FAILED, "Notify failed."); + return HANDLE_SUCCESS; + }; + TRUE_RETURN_V_MSG_E((!handler_->PostTask(outputFunc)), HANDLE_FAILED, "Handler post task failed."); + return HANDLE_SUCCESS; +} + +int32_t OutputController::NotifyOutput(const std::shared_ptr& data) +{ + TRUE_RETURN_V_MSG_E((!listener_), NOTIFY_FAILED, "Listener is nullptr."); + return listener_->OnOutput(data); +} + +bool OutputController::CheckIsBaselineInit() +{ + return GetBaselineInitState(); +} + +bool OutputController::CheckIsTimeInit() +{ + return GetTimeInitState(); +} + +bool OutputController::CheckIsAllowControl() +{ + return GetAllowControlState(); +} + +void OutputController::RegisterListener(const std::shared_ptr& listener) +{ + listener_ = listener; +} + +void OutputController::UnregisterListener() +{ + listener_ = nullptr; +} + +void OutputController::SetBufferTime(const uint32_t time) +{ + bufferTime_ = time; +} + +uint32_t OutputController::GetBufferTime() +{ + return bufferTime_; +} + +void OutputController::SetTimeInitState(const bool state) +{ + isTimeInit_.store(state); +} + +bool OutputController::GetTimeInitState() +{ + return isTimeInit_.load(); +} + +void OutputController::SetBaselineInitState(const bool state) +{ + isBaselineInit_.store(state); +} + +bool OutputController::GetBaselineInitState() +{ + return isBaselineInit_.load(); +} + +void OutputController::SetProcessDynamicBalanceState(const bool state) +{ + isInDynamicBalance_.store(state); +} + +bool OutputController::GetProcessDynamicBalanceState() +{ + return isInDynamicBalance_.load(); +} + +void OutputController::SetAllowControlState(const bool state) +{ + isAllowControl_.store(state); +} + +bool OutputController::GetAllowControlState() +{ + return isAllowControl_.load(); +} + +void OutputController::SetClockBaseline(const int64_t clockBaseline) +{ + clockBaseline_ = clockBaseline; +} + +void OutputController::SetTimeStampBaseline(const int64_t timeStmapBaseline) +{ + timeStampBaseline_ = timeStmapBaseline; +} + +void OutputController::SetAverIntervalDiffThre(const uint32_t thre) +{ + averIntervalDiffThre_ = thre; +} + +void OutputController::SetDynamicBalanceThre(const uint8_t thre) +{ + dynamicBalanceThre_ = thre; +} + +void OutputController::SetPushOnceDiffThre(const uint32_t thre) +{ + pushOnceDiffThre_ = thre; +} + +void OutputController::SetTimeStampOnceDiffThre(const uint32_t thre) +{ + timeStampOnceDiffThre_ = thre; +} + +void OutputController::SetAdjustSleepFactor(const float factor) +{ + adjustSleepFactor_ = factor; +} + +void OutputController::SetWaitClockFactor(const float factor) +{ + waitClockFactor_ = factor; +} + +void OutputController::SetTrackClockFactor(const float factor) +{ + trackClockFactor_ = factor; +} + +void OutputController::SetWaitClockThre(const int64_t thre) +{ + waitClockThre_ = thre; +} + +void OutputController::SetTrackClockThre(const int64_t thre) +{ + trackClockThre_ = thre; +} + +void OutputController::SetSleepThre(const int64_t thre) +{ + sleepThre_ = thre; +} + +void OutputController::SetVideoFrontTime(const int64_t time) +{ + vFront_ = time; +} + +void OutputController::SetVideoBackTime(const int64_t time) +{ + vBack_ = time; +} + +void OutputController::SetAudioFrontTime(const int64_t time) +{ + aFront_ = time; +} + +void OutputController::SetAudioBackTime(const int64_t time) +{ + aBack_ = time; +} + +void OutputController::SetClockTime(const int64_t clockTime) +{ + clockTime_.store(clockTime); +} + +int64_t OutputController::GetClockTime() +{ + return clockTime_.load(); +} + +void OutputController::SetDevClockDiff(int32_t diff) +{ + devClockDiff_.store(diff); +} + +int32_t OutputController::GetDevClockDiff() +{ + return devClockDiff_.load(); +} + +OutputController::ControlMode OutputController::GetControlMode() +{ + return mode_.load(); +} + +OutputController::ControlStatus OutputController::GetControlStatus() +{ + return status_.load(); +} + +void OutputController::SetControlMode(ControlMode mode) +{ + mode_.store(mode); + PrepareControl(); +} + +void OutputController::SetControlStatus(ControlStatus status) +{ + status_.store(status); +} + +size_t OutputController::GetQueueSize() +{ + { + std::lock_guard lock(queueMutex_); + return dataQueue_.size(); + } +} + +void OutputController::ClearQueue(std::queue>& queue) +{ + std::queue> empty; + swap(empty, queue); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/output_controller_listener.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/output_controller_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..348b5116dc44e19f13d17d9ab6f981ff090fdcdd --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/output_controller_listener.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "av_trans_log.h" +#include "output_controller_listener.h" +#include "output_controller_constants.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t OutputControllerListener::OnOutput(const std::shared_ptr& data) +{ + std::shared_ptr output = output_.lock(); + TRUE_RETURN_V_MSG_E((!output), NOTIFY_FAILED, "Output is nullptr, notify failed."); + output->OnOutput(data); + return NOTIFY_SUCCESS; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/time_statistician.cpp b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/time_statistician.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c48783eb34946f58d3e78a4fa6f81d7bfcb0c371 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/plugins/av_trans_output/output_control/src/time_statistician.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "time_statistician.h" +#include "av_trans_log.h" + +namespace OHOS { +namespace DistributedHardware { +void TimeStatistician::CalProcessTime(const std::shared_ptr& data) +{ + auto bufferMeta = data->GetBufferMeta(); + if (!bufferMeta->IsExist(Tag::USER_PUSH_DATA_TIME)) { + ClearStatistics(); + return; + } + int64_t pushTime = Plugin::AnyCast(bufferMeta->GetMeta(Tag::USER_PUSH_DATA_TIME)); + int64_t timeStamp = data->pts; + CalAverPushInterval(pushTime); + CalAverTimeStampInterval(timeStamp); +} +void TimeStatistician::ClearStatistics() +{ + pushIndex_ = 0; + averPushInterval_ = 0; + lastPushTime_ = 0; + pushTime_ = 0; + pushIntervalSum_ = 0; + pushInterval_ = 0; + timeStampIndex_ = 0; + averTimeStampInterval_ = 0; + lastTimeStamp_ = 0; + timeStamp_ = 0; + timeStampIntervalSum_ = 0; + timeStampInterval_ = 0; +} + +void TimeStatistician::CalAverPushInterval(const int64_t pushTime) +{ + pushTime_ = pushTime; + pushInterval_ = pushTime_ - lastPushTime_; + if (lastPushTime_ == 0) { + lastPushTime_ = pushTime_; + return; + } + pushIndex_++; + pushIntervalSum_ += pushInterval_; + averPushInterval_ = pushIntervalSum_ / pushIndex_; + lastPushTime_ = pushTime_; + AVTRANS_LOGD("Statistic pushInterval: %lld, pushIndex: %" PRIu32 ", averPushInterval: %lld", + pushInterval_, pushIndex_, averPushInterval_); +} + +void TimeStatistician::CalAverTimeStampInterval(const int64_t timeStamp) +{ + timeStamp_ = timeStamp; + timeStampInterval_ = timeStamp_ - lastTimeStamp_; + if (lastTimeStamp_ == 0) { + lastTimeStamp_ = timeStamp_; + return; + } + timeStampIndex_++; + timeStampIntervalSum_ += timeStampInterval_; + averTimeStampInterval_ = timeStampIntervalSum_ / timeStampIndex_; + lastTimeStamp_ = timeStamp_; + AVTRANS_LOGD("Statistic timeStampInterval: %lld, timeStampIndex: %" PRIu32 ", averTimeStampInterval: %lld", + timeStampInterval_, timeStampIndex_, averTimeStampInterval_); +} + +int64_t TimeStatistician::GetAverPushInterval() +{ + return averPushInterval_; +} + +int64_t TimeStatistician::GetAverTimeStampInterval() +{ + return averTimeStampInterval_; +} + +int64_t TimeStatistician::GetPushInterval() +{ + return pushInterval_; +} + +int64_t TimeStatistician::GetTimeStampInterval() +{ + return timeStampInterval_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0f3fc96faebdffdea142eb70710663b87e683c22 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/BUILD.gn @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +group("plugin_test") { + testonly = true + + deps = [ + "av_trans_input/daudio_input_test:daudio_input_unittest", + "av_trans_input/dscreen_input_test:dscreen_input_unittest", + "av_trans_input/dsoftbus_input_audio_test:dsoftbus_input_audio_unittest", + "av_trans_input/dsoftbus_input_test:dsoftbus_input_unittest", + "av_trans_output/daudio_output_test:daudio_output_unittest", + "av_trans_output/dscreen_output_test:dscreen_output_unittest", + "av_trans_output/dsoftbus_output_audio_test:dsoftbus_output_audio_unittest", + "av_trans_output/dsoftbus_output_test:dsoftbus_output_unittest", + ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5659a819c0e32cb3d721dd7861f5a573759aa1ac --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/daudio_input_test" + +ohos_unittest("DaudioInputPluginTest") { + module_out_path = module_out_path + + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${plugin_path}/plugins/av_trans_input/daudio_input", + "//third_party/ffmpeg", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_sync_utils.cpp", + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_message.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "daudio_input_test.cpp", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + ] + cflags_cc = cflags + + deps = [ + "${plugin_path}/plugins/av_trans_input/daudio_input:plugin_AVTransDaudioInput", + "//third_party/googletest:gtest_rtti", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "eventhandler:libeventhandler", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_plugin_base", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"daudio_input_plugin_test\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("daudio_input_unittest") { + testonly = true + deps = [ ":DaudioInputPluginTest" ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/daudio_input_test.cpp b/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/daudio_input_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59030e7ebba57285f76feb5048340f362d0e192d --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/daudio_input_test.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "daudio_input_test.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string PLUGINNAME = "daudio_input"; + +void DaudioInputTest::SetUpTestCase() {} + +void DaudioInputTest::TearDownTestCase() {} + +void DaudioInputTest::SetUp() {} + +void DaudioInputTest::TearDown() {} + +HWTEST_F(DaudioInputTest, Pause_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + AVTransSharedMemory sharedMemory1 {1, 0, ""}; + plugin->sharedMemory_ = sharedMemory1; + Status ret = plugin->Pause(); + EXPECT_EQ(Status::OK, ret); + + AVTransSharedMemory sharedMemory2 { 1, 1, "" }; + plugin->sharedMemory_ = sharedMemory2; + ret = plugin->Pause(); + EXPECT_EQ(Status::OK, ret); + + AVTransSharedMemory sharedMemory3 { 1, 1, "name" }; + plugin->sharedMemory_ = sharedMemory3; + ret = plugin->Pause(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DaudioInputTest, SetParameter_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_input_test"; + Status ret = plugin->SetParameter(Tag::USER_SHARED_MEMORY_FD, value); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DaudioInputTest, GetParameter_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_input_test"; + plugin->SetParameter(Tag::USER_SHARED_MEMORY_FD, value); + + ValueType val; + Status ret = plugin->GetParameter(Tag::USER_SHARED_MEMORY_FD, val); + EXPECT_EQ(Status::OK, ret); + + plugin->tagMap_.clear(); + ret = plugin->GetParameter(Tag::USER_SHARED_MEMORY_FD, val); + EXPECT_EQ(Status::ERROR_NOT_EXISTED, ret); +} + +HWTEST_F(DaudioInputTest, PushData_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::shared_ptr buffer = nullptr; + Status ret = plugin->PushData("", buffer, 0); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); + + buffer = std::make_shared(); + ret = plugin->PushData("", buffer, 0); + EXPECT_EQ(Status::ERROR_INVALID_PARAMETER, ret); + + buffer->AllocMemory(nullptr, 10); + buffer->GetMemory()->Write((uint8_t*)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 10); + ret = plugin->PushData("", buffer, 0); + EXPECT_EQ(Status::OK, ret); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/daudio_input_test.h b/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/daudio_input_test.h new file mode 100644 index 0000000000000000000000000000000000000000..823cc9d77700ff3d8fbb52fd56eabf8c8faf7e69 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/daudio_input_test/daudio_input_test.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DAUDIO_INPUT_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_DAUDIO_INPUT_TEST_H + +#include "gtest/gtest.h" + +#include "daudio_input_plugin.h" + +#include "av_sync_utils.h" +#include "av_trans_buffer.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_input_plugin.h" +#include "foundation/osal/thread/mutex.h" +#include "foundation/osal/thread/scoped_lock.h" +#include "foundation/osal/thread/task.h" +#include "nlohmann/json.hpp" +#include "plugin_manager.h" +#include "plugin_types.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace testing::ext; +using namespace std; +class DaudioInputTest : public testing::Test { +public: + DaudioInputTest() {} + ~DaudioInputTest() {} + + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_DAUDIO_INPUT_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..089c40f98050e4f77ba273501cf8ff19e4228855 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/dscreen_input_test" + +ohos_unittest("DscreenInputTest") { + module_out_path = module_out_path + + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${plugin_path}/plugins/av_trans_input/dscreen_input", + "//third_party/ffmpeg", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_sync_utils.cpp", + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_message.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "dscreen_input_test.cpp", + ] + + deps = [ + "${plugin_path}/plugins/av_trans_input/dscreen_input:plugin_AVTransDscreenInput", + "//third_party/googletest:gtest_rtti", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "eventhandler:libeventhandler", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_plugin_base", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + ] + + cflags_cc = cflags + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dscreen_input_plugin_test\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dscreen_input_unittest") { + testonly = true + deps = [ ":DscreenInputTest" ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/dscreen_input_test.cpp b/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/dscreen_input_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..631055869ab817d66ef6300c48ccb406ac47e97f --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/dscreen_input_test.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dscreen_input_test.h" + +#include "dscreen_input_plugin.h" +#include "plugin_types.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string PLUGINNAME = "dscreen_input"; + +void DscreenInputTest::SetUpTestCase(void) {} + +void DscreenInputTest::TearDownTestCase(void) {} + +void DscreenInputTest::SetUp(void) {} + +void DscreenInputTest::TearDown(void) {} + +HWTEST_F(DscreenInputTest, SetParameter_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dscreen_input_test"; + Status ret = plugin->SetParameter(Tag::USER_SHARED_MEMORY_FD, value); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DscreenInputTest, GetParameter_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dscreen_input_test"; + plugin->SetParameter(Tag::USER_SHARED_MEMORY_FD, value); + + ValueType val; + Status ret = plugin->GetParameter(Tag::USER_SHARED_MEMORY_FD, val); + EXPECT_EQ(Status::OK, ret); + + plugin->paramsMap_.clear(); + ret = plugin->GetParameter(Tag::USER_SHARED_MEMORY_FD, val); + EXPECT_EQ(Status::ERROR_NOT_EXISTED, ret); +} + +HWTEST_F(DscreenInputTest, PushData_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::shared_ptr buffer = nullptr; + Status ret = plugin->PushData("", buffer, 0); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); + + buffer = std::make_shared(); + buffer->AllocMemory(nullptr, 10); + buffer->ChangeBufferMetaType(BufferMetaType::VIDEO); + buffer->GetMemory()->Write((uint8_t*)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 10); + ret = plugin->PushData("", buffer, 0); + EXPECT_EQ(Status::OK, ret); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/dscreen_input_test.h b/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/dscreen_input_test.h new file mode 100644 index 0000000000000000000000000000000000000000..7a784a2563d7f04da23a837333785362cbdd73b3 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dscreen_input_test/dscreen_input_test.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DSCREEN_INPUT_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_DSCREEN_INPUT_TEST_H + +#include + +#include "av_sync_utils.h" +#include "av_trans_buffer.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_input_plugin.h" +#include "foundation/osal/thread/mutex.h" +#include "foundation/osal/thread/scoped_lock.h" +#include "foundation/osal/thread/task.h" +#include "nlohmann/json.hpp" +#include "plugin_manager.h" +#include "plugin_types.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace testing::ext; +using namespace std; +class DscreenInputTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_DSCREEN_INPUT_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c2fcb3009dfd5bceba61692de46eb7d9abbc6a36 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/dsoftbus_input_audio_plugin_test" + +ohos_unittest("DsoftbusInputAudioPluginTest") { + module_out_path = module_out_path + + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${plugin_path}/plugins/av_trans_input/dsoftbus_input_audio", + "//third_party/ffmpeg", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "${common_path}/src/softbus_channel_adapter.cpp", + "dsoftbus_input_audio_plugin_test.cpp", + ] + + deps = [ + "${plugin_path}/plugins/av_trans_input/dsoftbus_input_audio:plugin_AVTransDsoftbusInputAudio", + "//third_party/googletest:gtest_rtti", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + ] + + cflags_cc = cflags + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dsoftbus_input_audio_plugin_test\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dsoftbus_input_audio_unittest") { + testonly = true + deps = [ ":DsoftbusInputAudioPluginTest" ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/dsoftbus_input_audio_plugin_test.cpp b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/dsoftbus_input_audio_plugin_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e8baf81e2a3f23ab072ae93f0933020c08cec63 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/dsoftbus_input_audio_plugin_test.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dsoftbus_input_audio_plugin_test.h" + +#include "dsoftbus_input_audio_plugin.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string PLUGINNAME = "dsoftbus_input_audio_plugin"; + +void DsoftbusInputAudioPluginTest::SetUpTestCase(void) {} + +void DsoftbusInputAudioPluginTest::TearDownTestCase(void) {} + +void DsoftbusInputAudioPluginTest::SetUp(void) {} + +void DsoftbusInputAudioPluginTest::TearDown(void) {} + +class DsoftbusInputAudioPluginCallback : public Callback { +public: + void OnEvent(const PluginEvent &event) + { + (void)event; + } +}; + +HWTEST_F(DsoftbusInputAudioPluginTest, Prepare_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Prepare_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::INITIALIZED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); + + plugin->ownerName_ = "ohos.dhardware.dcamera"; + ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Start_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Start_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + plugin->state_ = State::PREPARED; + Status ret = plugin->Start(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Stop_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Stop(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Stop_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + plugin->state_ = State::RUNNING; + Status ret = plugin->Stop(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, SetParameter_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->Init(); + std::string value = "dsoftbus_input_test"; + Status ret = plugin->SetParameter(Tag::MEDIA_DESCRIPTION, value); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, GetParameter_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_input_test"; + plugin->SetParameter(Tag::MEDIA_DESCRIPTION, value); + ValueType val; + Status ret = plugin->GetParameter(Tag::MEDIA_DESCRIPTION, val); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, GetParameter_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->paramsMap_.clear(); + ValueType val; + Status ret = plugin->GetParameter(Tag::MEDIA_DESCRIPTION, val); + EXPECT_EQ(Status::ERROR_NOT_EXISTED, ret); + + AVTransEvent event; + plugin->OnChannelEvent(event); + + std::shared_ptr buffer = std::make_shared(); + plugin->DataEnqueue(buffer); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Reset_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Reset_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + Status ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Pause_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Pause(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, Resume_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Resume(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, SetCallback_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->SetCallback(nullptr); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, SetDataCallback_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->SetDataCallback(nullptr); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputAudioPluginTest, SetDataCallback_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + DsoftbusInputAudioPluginCallback cb {}; + Status ret = plugin->SetCallback(&cb); + AVTransEvent event {EventType::EVENT_CHANNEL_OPENED, "", ""}; + plugin->OnChannelEvent(event); + + AVTransEvent event1 {EventType::EVENT_CHANNEL_OPEN_FAIL, "", ""}; + plugin->OnChannelEvent(event1); + + AVTransEvent event2 {EventType::EVENT_CHANNEL_CLOSED, "", ""}; + plugin->OnChannelEvent(event2); + + AVTransEvent event3 {EventType::EVENT_DATA_RECEIVED, "", ""}; + plugin->OnChannelEvent(event3); + EXPECT_EQ(Status::OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/dsoftbus_input_audio_plugin_test.h b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/dsoftbus_input_audio_plugin_test.h new file mode 100644 index 0000000000000000000000000000000000000000..6a144ed37f5f7ef15ab757a9999897e9c8efeeff --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_audio_test/dsoftbus_input_audio_plugin_test.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_INPUT_AUDIO_PLUGIN_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_INPUT_AUDIO_PLUGIN_TEST_H + +#include + +#include "av_sync_utils.h" +#include "av_trans_buffer.h" +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" +#include "av_trans_types.h" +#include "av_trans_utils.h" +#include "avtrans_input_plugin.h" +#include "foundation/osal/thread/mutex.h" +#include "foundation/osal/thread/scoped_lock.h" +#include "foundation/osal/thread/task.h" +#include "nlohmann/json.hpp" +#include "plugin_manager.h" +#include "plugin_types.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace testing::ext; +using namespace std; +class DsoftbusInputAudioPluginTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_INPUT_AUDIO_PLUGIN_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f2b068a8c10b0f6b03e1163f7030deb10d6b8d98 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/dsoftbus_input_test" + +ohos_unittest("DsoftbusInputPluginTest") { + module_out_path = module_out_path + + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${plugin_path}/plugins/av_trans_input/dsoftbus_input", + "//third_party/ffmpeg", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "${common_path}/src/softbus_channel_adapter.cpp", + "dsoftbus_input_plugin_test.cpp", + ] + + deps = [ + "${plugin_path}/plugins/av_trans_input/dsoftbus_input:plugin_AVTransDsoftbusInput", + "//third_party/googletest:gtest_rtti", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + ] + + cflags_cc = cflags + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dsoftbus_input_plugin_test\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dsoftbus_input_unittest") { + testonly = true + deps = [ ":DsoftbusInputPluginTest" ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/dsoftbus_input_plugin_test.cpp b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/dsoftbus_input_plugin_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b94955fd0aa0a1340a003993be597c1d3433e2cc --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/dsoftbus_input_plugin_test.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dsoftbus_input_plugin_test.h" + +#include "dsoftbus_input_plugin.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string PLUGINNAME = "dsoftbus_input_plugin"; + +void DsoftbusInputPluginTest::SetUpTestCase(void) {} + +void DsoftbusInputPluginTest::TearDownTestCase(void) {} + +void DsoftbusInputPluginTest::SetUp(void) {} + +void DsoftbusInputPluginTest::TearDown(void) {} + +HWTEST_F(DsoftbusInputPluginTest, Prepare_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, Prepare_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::INITIALIZED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); + + plugin->ownerName_ = "ohos.dhardware.dcamera"; + ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, Start_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, Start_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + plugin->state_ = State::PREPARED; + Status ret = plugin->Start(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, Stop_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Stop(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, Stop_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + plugin->state_ = State::RUNNING; + Status ret = plugin->Stop(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, SetParameter_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->Init(); + std::string value = "dsoftbus_input_test"; + Status ret = plugin->SetParameter(Tag::MEDIA_DESCRIPTION, value); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, GetParameter_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_input_test"; + plugin->SetParameter(Tag::MEDIA_DESCRIPTION, value); + ValueType val; + Status ret = plugin->GetParameter(Tag::MEDIA_DESCRIPTION, val); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, GetParameter_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->paramsMap_.clear(); + ValueType val; + Status ret = plugin->GetParameter(Tag::MEDIA_DESCRIPTION, val); + EXPECT_EQ(Status::ERROR_NOT_EXISTED, ret); + + AVTransEvent event; + plugin->OnChannelEvent(event); + + std::shared_ptr buffer = std::make_shared(); + plugin->DataEnqueue(buffer); +} + +HWTEST_F(DsoftbusInputPluginTest, Pause_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Pause(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, SetCallback_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->SetCallback(nullptr); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, Resume_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Resume(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusInputPluginTest, SetDataCallback_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + AVDataCallback dataCb; + Status ret = plugin->SetDataCallback(dataCb); + EXPECT_EQ(Status::OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/dsoftbus_input_plugin_test.h b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/dsoftbus_input_plugin_test.h new file mode 100644 index 0000000000000000000000000000000000000000..8b5a27988956c0518845a68134f0d8917d8e0f79 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_input/dsoftbus_input_test/dsoftbus_input_plugin_test.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_INPUT_PLUGIN_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_INPUT_PLUGIN_TEST_H + +#include + +namespace OHOS { +namespace DistributedHardware { +using namespace testing::ext; +using namespace std; +class DsoftbusInputPluginTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_INPUT_PLUGIN_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..93b05a64228788bf504e5e4eb9fb59a174c5c95f --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/daudio_output_test" + +ohos_unittest("DaudioOutputPluginTest") { + module_out_path = module_out_path + + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${plugin_path}/plugins/av_trans_output/daudio_output", + "//third_party/ffmpeg", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_sync_utils.cpp", + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_message.cpp", + "${common_path}/src/av_trans_utils.cpp", + "daudio_output_test.cpp", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + ] + cflags_cc = cflags + + deps = [ + "${plugin_path}/plugins/av_trans_output/daudio_output:plugin_AVTransDaudioOutput", + "//third_party/googletest:gtest_rtti", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "eventhandler:libeventhandler", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"daudio_output_plugin_test\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("daudio_output_unittest") { + testonly = true + deps = [ ":DaudioOutputPluginTest" ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/daudio_output_test.cpp b/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/daudio_output_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22331f0b8c34a66c7b7cbe305e761a4d9c7bb1ad --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/daudio_output_test.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "daudio_output_test.h" + +#include "daudio_output_plugin.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string PLUGINNAME = "daudio_output"; + +void DaudioOutputTest::SetUpTestCase() {} + +void DaudioOutputTest::TearDownTestCase() {} + +void DaudioOutputTest::SetUp() {} + +void DaudioOutputTest::TearDown() {} + +HWTEST_F(DaudioOutputTest, Reset_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); + + plugin->sendPlayTask_ = std::make_shared("sendPlayTask_"); + plugin->resample_ = std::make_shared(); + ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DaudioOutputTest, Prepare_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DaudioOutputTest, Prepare_002, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::INITIALIZED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_UNKNOWN, ret); + + int value = 1; + plugin->SetParameter(Tag::AUDIO_SAMPLE_RATE, value); + ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_UNKNOWN, ret); + + plugin->paramsMap_.clear(); + plugin->SetParameter(Tag::AUDIO_CHANNELS, value); + ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_UNKNOWN, ret); + + plugin->SetParameter(Tag::AUDIO_SAMPLE_RATE, value); + ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_UNKNOWN, ret); + + plugin->SetParameter(Tag::AUDIO_CHANNEL_LAYOUT, value); + ret = plugin->Prepare(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DaudioOutputTest, SetParameter_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_output_test"; + Status ret = plugin->SetParameter(Tag::USER_AV_SYNC_GROUP_INFO, value); + EXPECT_EQ(Status::OK, ret); + + ret = plugin->SetParameter(Tag::USER_SHARED_MEMORY_FD, value); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DaudioOutputTest, GetParameter_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_output_test"; + plugin->SetParameter(Tag::USER_AV_SYNC_GROUP_INFO, value); + ValueType val; + Status ret = plugin->GetParameter(Tag::USER_AV_SYNC_GROUP_INFO, val); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DaudioOutputTest, GetParameter_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->paramsMap_.clear(); + ValueType val; + Status ret = plugin->GetParameter(Tag::USER_AV_SYNC_GROUP_INFO, val); + EXPECT_EQ(Status::ERROR_NOT_EXISTED, ret); +} + +HWTEST_F(DaudioOutputTest, Start_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DaudioOutputTest, Start_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->sendPlayTask_ = std::make_shared("sendPlayTask_"); + plugin->state_ = State::PREPARED; + Status ret = plugin->Start(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DaudioOutputTest, Stop_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Stop(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DaudioOutputTest, Stop_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->sendPlayTask_ = std::make_shared("sendPlayTask_"); + plugin->state_ = State::RUNNING; + Status ret = plugin->Stop(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DaudioOutputTest, PushData_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string inPort = "inPort_test"; + std::shared_ptr buffer = nullptr; + int64_t offset = 1; + Status ret = plugin->PushData(inPort, buffer, offset); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(DaudioOutputTest, SetDataCallback_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + AVDataCallback callback = nullptr; + Status ret = plugin->SetDataCallback(callback); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(DaudioOutputTest, WriteMasterClockToMemory_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_output_test"; + Status ret = plugin->SetParameter(Tag::USER_AV_SYNC_GROUP_INFO, value); + std::shared_ptr buffer = std::make_shared(); + plugin->WriteMasterClockToMemory(buffer); + EXPECT_EQ(Status::OK, ret); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/daudio_output_test.h b/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/daudio_output_test.h new file mode 100644 index 0000000000000000000000000000000000000000..0f2755889c1cd57f516aaf227699027fc35d1055 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/daudio_output_test/daudio_output_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DAUDIO_OUTPUT_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_DAUDIO_OUTPUT_TEST_H + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace testing::ext; +using namespace std; +class DaudioOutputTest : public testing::Test { +public: + DaudioOutputTest() {} + ~DaudioOutputTest() {} + + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_DAUDIO_OUTPUT_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c60f56b98f9260b90f78f7cc26217e60478d6daf --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/dscreen_output_test" + +ohos_unittest("DscreenOutputPluginTest") { + module_out_path = module_out_path + + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${plugin_path}/plugins/av_trans_output/dscreen_output", + "${output_controller_path}/include", + "//third_party/ffmpeg", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_sync_utils.cpp", + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_message.cpp", + "${common_path}/src/av_trans_utils.cpp", + "dscreen_output_test.cpp", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + ] + cflags_cc = cflags + + deps = [ + "${plugin_path}/plugins/av_trans_output/dscreen_output:plugin_AVTransDscreenOutput", + "//third_party/googletest:gtest_rtti", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "eventhandler:libeventhandler", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dscreen_output_plugin_test\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dscreen_output_unittest") { + testonly = true + deps = [ ":DscreenOutputPluginTest" ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/dscreen_output_test.cpp b/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/dscreen_output_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9b1e014f3c76e1daed628a3c2f7706335b0500f --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/dscreen_output_test.cpp @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dscreen_output_test.h" + +#include "dscreen_output_plugin.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string PLUGINNAME = "dscreen_output"; + +void DscreenOutputTest::SetUpTestCase(void) {} + +void DscreenOutputTest::TearDownTestCase(void) {} + +void DscreenOutputTest::SetUp(void) {} + +void DscreenOutputTest::TearDown(void) {} + +HWTEST_F(DscreenOutputTest, Reset_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); + plugin->InitOutputController(); + ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DscreenOutputTest, Prepare_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DscreenOutputTest, Prepare_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::INITIALIZED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(DscreenOutputTest, Prepare_003, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + plugin->state_ = State::INITIALIZED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DscreenOutputTest, SetParameter_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dscreen_output_test"; + Status ret = plugin->SetParameter(Tag::USER_FRAME_NUMBER, value); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); + + plugin->InitOutputController(); + ret = plugin->SetParameter(Tag::USER_FRAME_NUMBER, value); + EXPECT_EQ(Status::OK, ret); +} + + +HWTEST_F(DscreenOutputTest, GetParameter_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dscreen_output_test"; + ValueType val; + Status ret = plugin->GetParameter(Tag::USER_FRAME_NUMBER, val); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(DscreenOutputTest, GetParameter_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + ValueType val; + Status ret = plugin->GetParameter(Tag::USER_FRAME_NUMBER, val); + EXPECT_EQ(Status::ERROR_NOT_EXISTED, ret); +} + +HWTEST_F(DscreenOutputTest, GetParameter_003, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::string value = "dscreen_output_test"; + plugin->SetParameter(Tag::USER_FRAME_NUMBER, value); + plugin->InitOutputController(); + ValueType val; + Status ret = plugin->GetParameter(Tag::USER_FRAME_NUMBER, val); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DscreenOutputTest, Start_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::INITIALIZED; + Status ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); + + plugin->state_ = State::PREPARED; + ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); + + plugin->InitOutputController(); + ret = plugin->Start(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DscreenOutputTest, Stop_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::INITIALIZED; + Status ret = plugin->Stop(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); + + plugin->state_ = State::RUNNING; + ret = plugin->Stop(); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); + + plugin->InitOutputController(); + ret = plugin->Stop(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DscreenOutputTest, PushData_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string inPort = "inPort_test"; + std::shared_ptr buffer = nullptr; + int64_t offset = 1; + Status ret = plugin->PushData(inPort, buffer, offset); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); + + plugin->InitOutputController(); + std::shared_ptr data = std::make_shared(); + plugin->controller_->PushData(data); + + plugin->controller_->SetControlStatus(DScreenOutputController::ControlStatus::START); + plugin->controller_->PushData(data); + + plugin->controller_->SetControlMode(DScreenOutputController::ControlMode::SYNC); + plugin->controller_->PushData(data); +} + +HWTEST_F(DscreenOutputTest, StartControl_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + OutputController::ControlStatus ret = plugin->controller_->StartControl(); + EXPECT_EQ(OutputController::ControlStatus::START, ret); + + plugin->controller_->SetControlStatus(OutputController::ControlStatus::START); + ret = plugin->controller_->StartControl(); + EXPECT_EQ(OutputController::ControlStatus::STARTED, ret); +} + +HWTEST_F(DscreenOutputTest, StopControl_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + OutputController::ControlStatus ret = plugin->controller_->StopControl(); + EXPECT_EQ(OutputController::ControlStatus::STOP, ret); + + plugin->controller_->SetControlStatus(OutputController::ControlStatus::STOP); + ret = plugin->controller_->StopControl(); + EXPECT_EQ(OutputController::ControlStatus::STOPPED, ret); +} + +HWTEST_F(DscreenOutputTest, ReleaseControl_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + + OutputController::ControlStatus ret = plugin->controller_->ReleaseControl(); + EXPECT_EQ(OutputController::ControlStatus::RELEASED, ret); +} + +HWTEST_F(DscreenOutputTest, SetParameter_002, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::string value = "dscreen_output_test"; + Status ret = plugin->controller_->SetParameter(Tag::USER_AV_SYNC_GROUP_INFO, value); + EXPECT_EQ(Status::OK, ret); + + ret = plugin->controller_->SetParameter(Tag::USER_SHARED_MEMORY_FD, value); + EXPECT_EQ(Status::OK, ret); + + ret = plugin->controller_->SetParameter(Tag::USER_TIME_SYNC_RESULT, value); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DscreenOutputTest, ControlOutput_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::shared_ptr data = std::make_shared(); + plugin->controller_->SetAllowControlState(false); + int32_t ret = plugin->controller_->ControlOutput(data); + EXPECT_EQ(OUTPUT_FRAME, ret); + + plugin->controller_->SetAllowControlState(true); + data->pts = 100; + ret = plugin->controller_->ControlOutput(data); + EXPECT_EQ(OUTPUT_FRAME, ret); + + plugin->controller_->CheckSyncInfo(data); + plugin->controller_->PrepareControl(); + plugin->controller_->SetControlMode(OutputController::ControlMode::SYNC); + plugin->controller_->CalProcessTime(data); +} + +HWTEST_F(DscreenOutputTest, CheckIsClockInvalid_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::shared_ptr data; + bool ret = plugin->controller_->CheckIsClockInvalid(data); + EXPECT_EQ(false, ret); + + plugin->controller_->SetControlMode(OutputController::ControlMode::SYNC); + ret = plugin->controller_->CheckIsClockInvalid(data); + EXPECT_EQ(true, ret); +} + +HWTEST_F(DscreenOutputTest, AcquireSyncClockTime_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::shared_ptr data; + int32_t ret = plugin->controller_->AcquireSyncClockTime(data); + EXPECT_EQ(ERR_DH_AVT_SHARED_MEMORY_FAILED, ret); +} + +HWTEST_F(DscreenOutputTest, WaitRereadClockFailed_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::shared_ptr data; + bool ret = plugin->controller_->WaitRereadClockFailed(data); + EXPECT_EQ(false, ret); +} + +HWTEST_F(DscreenOutputTest, CheckIsProcessInDynamicBalance_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::shared_ptr data; + plugin->controller_->SetControlMode(OutputController::ControlMode::SYNC); + bool ret = plugin->controller_->CheckIsProcessInDynamicBalance(data); + EXPECT_EQ(true, ret); + + plugin->controller_->SetControlMode(OutputController::ControlMode::SMOOTH); + plugin->controller_->SetProcessDynamicBalanceState(false); + ret = plugin->controller_->CheckIsProcessInDynamicBalance(data); + EXPECT_EQ(false, ret); +} + +HWTEST_F(DscreenOutputTest, CheckIsProcessInDynamicBalanceOnce_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::shared_ptr data; + bool ret = plugin->controller_->CheckIsProcessInDynamicBalanceOnce(data); + EXPECT_EQ(false, ret); +} + +HWTEST_F(DscreenOutputTest, PostOutputEvent_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::shared_ptr data; + int32_t ret = plugin->controller_->PostOutputEvent(data); + EXPECT_EQ(HANDLE_FAILED, ret); + + data = std::make_shared(); + plugin->controller_->SyncClock(data); +} + +HWTEST_F(DscreenOutputTest, NotifyOutput_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->InitOutputController(); + std::shared_ptr data; + plugin->controller_->UnregisterListener(); + int32_t ret = plugin->controller_->NotifyOutput(data); + EXPECT_EQ(NOTIFY_FAILED, ret); + + int32_t result = 0; + plugin->controller_->HandleControlResult(data, result); + + result = 1; + plugin->controller_->HandleControlResult(data, result); + + result = 2; + plugin->controller_->HandleControlResult(data, result); + + result = 3; + plugin->controller_->HandleControlResult(data, result); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/dscreen_output_test.h b/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/dscreen_output_test.h new file mode 100644 index 0000000000000000000000000000000000000000..18fcbd22db8f052b2e3d707579c3cbb33fb637f7 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dscreen_output_test/dscreen_output_test.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DSCREEN_OUTPUT_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_DSCREEN_OUTPUT_TEST_H + +#include + +namespace OHOS { +namespace DistributedHardware { +using namespace testing::ext; +using namespace std; +class DscreenOutputTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_DSCREEN_OUTPUT_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..63910712e509584de1d42ff9b04e3ed05234c8ad --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/dsoftbus_output_audio_test" + +ohos_unittest("DsoftbusOutputAudioPluginTest") { + module_out_path = module_out_path + + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${plugin_path}/plugins/av_trans_output/dsoftbus_output_audio", + "//third_party/ffmpeg", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "${common_path}/src/softbus_channel_adapter.cpp", + "dsoftbus_output_audio_plugin_test.cpp", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + ] + cflags_cc = cflags + + deps = [ + "${plugin_path}/plugins/av_trans_output/dsoftbus_output_audio:plugin_AVTransDsoftbusOutputAudio", + "//third_party/googletest:gtest_rtti", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dsoftbus_output_audio_plugin_test\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dsoftbus_output_audio_unittest") { + testonly = true + deps = [ ":DsoftbusOutputAudioPluginTest" ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/dsoftbus_output_audio_plugin_test.cpp b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/dsoftbus_output_audio_plugin_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a19785c2806e614867bf3475574d9baacf2878e6 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/dsoftbus_output_audio_plugin_test.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dsoftbus_output_audio_plugin_test.h" + +#include "dsoftbus_output_audio_plugin.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string PLUGINNAME = "dsoftbus_output_audio_plugin"; + +void DsoftbusOutputAudioPluginTest::SetUpTestCase(void) {} + +void DsoftbusOutputAudioPluginTest::TearDownTestCase(void) {} + +void DsoftbusOutputAudioPluginTest::SetUp(void) {} + +void DsoftbusOutputAudioPluginTest::TearDown(void) {} + +HWTEST_F(DsoftbusOutputAudioPluginTest, Reset_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); + plugin->bufferPopTask_ = std::make_shared("audioBufferQueuePopThread"); + ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, Prepare_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); + + plugin->state_ = State::INITIALIZED; + ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, GetParameter_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_output_audio_plugin_test"; + plugin->SetParameter(Tag::MEDIA_DESCRIPTION, value); + ValueType val; + Status ret = plugin->GetParameter(Tag::MEDIA_DESCRIPTION, val); + EXPECT_EQ(Status::OK, ret); + + plugin->paramsMap_.clear(); + ret = plugin->GetParameter(Tag::USER_FRAME_NUMBER, val); + EXPECT_EQ(Status::ERROR_NOT_EXISTED, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, Start_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); + + plugin->state_ = State::PREPARED; + ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, Stop_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Stop(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, PushData_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string inPort = "inPort_test"; + std::shared_ptr buffer = nullptr; + int64_t offset = 1; + Status ret = plugin->PushData(inPort, buffer, offset); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, SetParameter_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_output_audio_plugin_test"; + Status ret = plugin->SetParameter(Tag::MEDIA_DESCRIPTION, value); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, SetCallback_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->SetCallback(nullptr); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, OpenSoftbusChannel_002, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->OpenSoftbusChannel(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); +} + +HWTEST_F(DsoftbusOutputAudioPluginTest, SetDataCallback_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + AVDataCallback cbk; + Status ret = plugin->SetDataCallback(cbk); + EXPECT_EQ(Status::OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/dsoftbus_output_audio_plugin_test.h b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/dsoftbus_output_audio_plugin_test.h new file mode 100644 index 0000000000000000000000000000000000000000..f9e0b6af973e2b4acde5fe95321fbad13305d66e --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_audio_test/dsoftbus_output_audio_plugin_test.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_OUTPUT_AUDIO_PLUGIN_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_OUTPUT_AUDIO_PLUGIN_TEST_H + +#include + +namespace OHOS { +namespace DistributedHardware { +using namespace testing::ext; +using namespace std; +class DsoftbusOutputAudioPluginTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_OUTPUT_AUDIO_PLUGIN_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/BUILD.gn b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d1091c4eac423e4f9526d8c6aad882f36b29049c --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/dsoftbus_output_test" + +ohos_unittest("DsoftbusOutputPluginTest") { + module_out_path = module_out_path + + include_dirs = [ + "${common_path}/include", + "${plugin_path}/interface", + "${plugin_path}/plugins/av_trans_output/dsoftbus_output", + "//third_party/ffmpeg", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/av_trans_log.cpp", + "${common_path}/src/av_trans_meta.cpp", + "${common_path}/src/av_trans_utils.cpp", + "${common_path}/src/softbus_channel_adapter.cpp", + "dsoftbus_output_plugin_test.cpp", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Dprivate = public", + ] + cflags_cc = cflags + + deps = [ + "${plugin_path}/plugins/av_trans_output/dsoftbus_output:plugin_AVTransDsoftbusOutput", + "//third_party/googletest:gtest_rtti", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "dsoftbus:softbus_client", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dsoftbus_output_plugin_test\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dsoftbus_output_unittest") { + testonly = true + deps = [ ":DsoftbusOutputPluginTest" ] +} diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/dsoftbus_output_plugin_test.cpp b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/dsoftbus_output_plugin_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5150c2b06c3c4b7e6d244bf75ae447db17244755 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/dsoftbus_output_plugin_test.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dsoftbus_output_plugin_test.h" + +#include "dsoftbus_output_plugin.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string PLUGINNAME = "dsoftbus_output_plugin"; + +void DsoftbusOutputPluginTest::SetUpTestCase(void) {} + +void DsoftbusOutputPluginTest::TearDownTestCase(void) {} + +void DsoftbusOutputPluginTest::SetUp(void) {} + +void DsoftbusOutputPluginTest::TearDown(void) {} + +HWTEST_F(DsoftbusOutputPluginTest, Reset_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); + plugin->bufferPopTask_ = std::make_shared("videoBufferQueuePopThread"); + ret = plugin->Reset(); + EXPECT_EQ(Status::OK, ret); +} + +HWTEST_F(DsoftbusOutputPluginTest, Prepare_001, TestSize.Level0) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusOutputPluginTest, Prepare_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::INITIALIZED; + plugin->ownerName_ = "ohos_dhardware.dcamera"; + Status ret = plugin->Prepare(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); +} + +HWTEST_F(DsoftbusOutputPluginTest, GetParameter_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string value = "dsoftbus_output_plugin_test"; + plugin->SetParameter(Tag::MEDIA_DESCRIPTION, value); + ValueType val; + Status ret = plugin->GetParameter(Tag::MEDIA_DESCRIPTION, val); + EXPECT_EQ(Status::OK, ret); + + plugin->paramsMap_.clear(); + ret = plugin->GetParameter(Tag::USER_FRAME_NUMBER, val); + EXPECT_EQ(Status::ERROR_NOT_EXISTED, ret); +} + +HWTEST_F(DsoftbusOutputPluginTest, Start_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusOutputPluginTest, Start_002, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + plugin->state_ = State::PREPARED; + Status ret = plugin->Start(); + EXPECT_EQ(Status::ERROR_INVALID_OPERATION, ret); +} + +HWTEST_F(DsoftbusOutputPluginTest, Stop_001, TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + Status ret = plugin->Stop(); + EXPECT_EQ(Status::ERROR_WRONG_STATE, ret); +} + +HWTEST_F(DsoftbusOutputPluginTest, PushData_001, testing::ext::TestSize.Level1) +{ + auto plugin = std::make_shared(PLUGINNAME); + std::string inPort = "inPort_test"; + std::shared_ptr buffer = nullptr; + int64_t offset = 1; + Status ret = plugin->PushData(inPort, buffer, offset); + EXPECT_EQ(Status::ERROR_NULL_POINTER, ret); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/dsoftbus_output_plugin_test.h b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/dsoftbus_output_plugin_test.h new file mode 100644 index 0000000000000000000000000000000000000000..3391e14685f15c0b6ee19deec973c5ce8bb88287 --- /dev/null +++ b/av_transport/av_trans_engine/plugin/test/av_trans_output/dsoftbus_output_test/dsoftbus_output_plugin_test.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_OUTPUT_PLUGIN_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_OUTPUT_PLUGIN_TEST_H + +#include + +namespace OHOS { +namespace DistributedHardware { +using namespace testing::ext; +using namespace std; +class DsoftbusOutputPluginTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_DSOFTBUS_OUTPUT_PLUGIN_TEST_H \ No newline at end of file diff --git a/av_transport/av_trans_handler/histreamer_ability_querier/BUILD.gn b/av_transport/av_trans_handler/histreamer_ability_querier/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..67b91eb7c2e5193b723bb4a6c9ce2038bc573000 --- /dev/null +++ b/av_transport/av_trans_handler/histreamer_ability_querier/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +config("handler_external_config") { + include_dirs = [ + "${common_path}/include", + "${engine_path}/av_sender/include", + "${engine_path}/av_receiver/include", + "${interface_path}", + ] +} + +ohos_shared_library("histreamer_ability_querier") { + public_configs = [ ":handler_external_config" ] + + include_dirs = [ + "include", + "//third_party/json/include", + "${media_standard_path}/interfaces/inner_api/native", + "${common_path}/include", + ] + + sources = [ + "${common_path}/src/av_trans_log.cpp", + "src/histreamer_ability_querier.cpp", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"av_trans_handler\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "hilog:libhilog", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + cflags = [ + "-O2", + "-fPIC", + "-Wall", + "-frtti", + "-fexceptions", + "-Wno-unused-but-set-variable", + "-Wno-format", + ] + + cflags_cc = cflags + + remove_configs = [ + "//build/config/compiler:no_rtti", + "//build/config/compiler:no_exceptions", + ] + + part_name = "distributed_hardware_fwk" + subsystem_name = "distributedhardware" +} + +ohos_rust_shared_ffi("histreamer_ability_querier_core") { + sources = [ "src/histreamer_ability_querier_core.rs" ] + crate_name = "histreamer_ability_querier_core" + crate_type = "cdylib" + subsystem_name = "distributedhardware" + part_name = "distributed_hardware_fwk" +} diff --git a/av_transport/av_trans_handler/histreamer_ability_querier/include/histreamer_ability_querier.h b/av_transport/av_trans_handler/histreamer_ability_querier/include/histreamer_ability_querier.h new file mode 100644 index 0000000000000000000000000000000000000000..45ef40312f3a06ff3027d1eadfa798791c643751 --- /dev/null +++ b/av_transport/av_trans_handler/histreamer_ability_querier/include/histreamer_ability_querier.h @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_HISTREAMER_ABILITY_QUERIER_H +#define OHOS_HISTREAMER_ABILITY_QUERIER_H + +#include +#include +#include + +#include "nlohmann/json.hpp" + +#include "plugin_audio_tags.h" +#include "plugin_video_tags.h" + +using OHOS::Media::Plugin::AudioAacProfile; +using OHOS::Media::Plugin::AudioAacStreamFormat; +using OHOS::Media::Plugin::AudioChannelLayout; +using OHOS::Media::Plugin::AudioSampleFormat; +using OHOS::Media::Plugin::VideoBitStreamFormat; +using OHOS::Media::Plugin::VideoPixelFormat; + +namespace OHOS { +namespace DistributedHardware { + +/******************* AudioEncoder Begin *****************/ +struct AudioEncoderIn { + std::string mime; + std::vector sample_rate; +}; + +struct AudioEncoderOut { + std::string mime; + uint32_t ad_mpeg_ver; + AudioAacProfile aac_profile; + AudioAacStreamFormat aac_stm_fmt; +}; + +struct AudioEncoder { + std::string name; + std::vector ins; + std::vector outs; +}; + +void ToJson(nlohmann::json &jsonObject, const AudioEncoderIn &audioEncoderIn); +void FromJson(const nlohmann::json &jsonObject, AudioEncoderIn &audioEncoderIn); + +void ToJson(nlohmann::json &jsonObject, const AudioEncoderOut &audioEncoderOut); +void FromJson(const nlohmann::json &jsonObject, AudioEncoderOut &audioEncoderOut); + +void ToJson(nlohmann::json &jsonObject, const AudioEncoder &audioEncoder); +void FromJson(const nlohmann::json &jsonObject, AudioEncoder &audioEncoder); +/******************* AudioEncoder End *******************/ + +/******************* AudioDecoder Begin *****************/ +struct AudioDecoderIn { + std::string mime; + std::vector channel_layout; +}; + +struct AudioDecoderOut { + std::string mime; + std::vector sample_fmt; +}; + +struct AudioDecoder { + std::string name; + std::vector ins; + std::vector outs; +}; + +void ToJson(nlohmann::json &jsonObject, const AudioDecoderIn &audioDecoderIn); +void FromJson(const nlohmann::json &jsonObject, AudioDecoderIn &audioDecoderIn); + +void ToJson(nlohmann::json &jsonObject, const AudioDecoderOut &audioDecoderOut); +void FromJson(const nlohmann::json &jsonObject, AudioDecoderOut &audioDecoderOut); + +void ToJson(nlohmann::json &jsonObject, const AudioDecoder &audioDecoder); +void FromJson(const nlohmann::json &jsonObject, AudioDecoder &audioDecoder); +/******************* AudioDecoder End *******************/ + +/******************* VideoEncoder Begin *****************/ +struct VideoEncoderIn { + std::string mime; + std::vector pixel_fmt; +}; + +struct VideoEncoderOut { + std::string mime; +}; + +struct VideoEncoder { + std::string name; + std::vector ins; + std::vector outs; +}; + +void ToJson(nlohmann::json &jsonObject, const VideoEncoderIn &videoEncoderIn); +void FromJson(const nlohmann::json &jsonObject, VideoEncoderIn &videoEncoderIn); + +void ToJson(nlohmann::json &jsonObject, const VideoEncoderOut &videoEncoderOut); +void FromJson(const nlohmann::json &jsonObject, VideoEncoderOut &videoEncoderOut); + +void ToJson(nlohmann::json &jsonObject, const VideoEncoder &videoEncoder); +void FromJson(const nlohmann::json &jsonObject, VideoEncoder &videoEncoder); +/******************* VideoEncoder End *******************/ + +/******************* VideoDecoder Begin *****************/ +struct VideoDecoderIn { + std::string mime; + std::vector vd_bit_stream_fmt; +}; + +struct VideoDecoderOut { + std::string mime; + std::vector pixel_fmt; +}; + +struct VideoDecoder { + std::string name; + std::vector ins; + std::vector outs; +}; + +void ToJson(nlohmann::json &jsonObject, const VideoDecoderIn &videoDecoderIn); +void FromJson(const nlohmann::json &jsonObject, VideoDecoderIn &videoDecoderIn); + +void ToJson(nlohmann::json &jsonObject, const VideoDecoderOut &videoDecoderOut); +void FromJson(const nlohmann::json &jsonObject, VideoDecoderOut &videoDecoderOut); + +void ToJson(nlohmann::json &jsonObject, const VideoDecoder &videoDecoder); +void FromJson(const nlohmann::json &jsonObject, VideoDecoder &videoDecoder); +/******************* VideoDecoder End *******************/ + +std::vector QueryAudioEncoderAbility(); +std::vector QueryAudioDecoderAbility(); +std::vector QueryVideoEncoderAbility(); +std::vector QueryVideoDecoderAbility(); + +template +void ToJson(const std::string &key, nlohmann::json &jsonObject, std::vector &objs); +template +void FromJson(const std::string &key, const nlohmann::json &jsonObject, std::vector &objs); + +#ifdef __cplusplus +extern "C" { +#endif +__attribute__((visibility("default"))) int32_t QueryAudioEncoderAbilityStr(char* res); +__attribute__((visibility("default"))) int32_t QueryAudioDecoderAbilityStr(char* res); +__attribute__((visibility("default"))) int32_t QueryVideoEncoderAbilityStr(char* res); +__attribute__((visibility("default"))) int32_t QueryVideoDecoderAbilityStr(char* res); +#ifdef __cplusplus +} +#endif +} +} +#endif \ No newline at end of file diff --git a/av_transport/av_trans_handler/histreamer_ability_querier/src/histreamer_ability_querier.cpp b/av_transport/av_trans_handler/histreamer_ability_querier/src/histreamer_ability_querier.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53b956b90df6c93ea1e28b930a0fd8a4c17c6033 --- /dev/null +++ b/av_transport/av_trans_handler/histreamer_ability_querier/src/histreamer_ability_querier.cpp @@ -0,0 +1,802 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "histreamer_ability_querier.h" + +#include +#include +#include +#include +#include "plugin_caps.h" +#include "plugin_manager.h" +#include "pipeline/filters/common/plugin_utils.h" + +#include "av_trans_log.h" + +using OHOS::Media::Plugin::PluginManager; +using OHOS::Media::Plugin::PluginType; +using OHOS::Media::Plugin::PluginInfo; +using OHOS::Media::Plugin::Capability; +using OHOS::Media::Plugin::CapabilitySet; +using OHOS::Media::Plugin::AnyCast; +using CapabilityID = OHOS::Media::Plugin::Capability::Key; + +namespace OHOS { +namespace DistributedHardware { + +const uint32_t MAX_MESSAGES_LEN = 1 * 1024 * 1024; +static const std::string NAME = "name"; +static const std::string INS = "ins"; +static const std::string OUTS = "outs"; +static const std::string MIME = "mime"; +static const std::string SAMPLE_RATE = "sample_rate"; +static const std::string AUDIO_SAMPLE_FORMAT = "sample_fmt"; +static const std::string AD_MPEG_VER = "ad_mpeg_ver"; +static const std::string AUDIO_AAC_PROFILE = "aac_profile"; +static const std::string AUDIO_AAC_STREAM_FORMAT = "aac_stm_fmt"; +static const std::string AUDIO_CHANNEL_LAYOUT = "channel_layout"; + +static const std::string VIDEO_PIXEL_FMT = "pixel_fmt"; +static const std::string VIDEO_BIT_STREAM_FMT = "vd_bit_stream_fmt"; + +static const std::string AUDIO_ENCODERS = "audioEncoders"; +static const std::string AUDIO_DECODERS = "audioDecoders"; +static const std::string VIDEO_ENCODERS = "videoEncoders"; +static const std::string VIDEO_DECODERS = "videoDecoders"; + +static const std::vector AUDIO_ENCODER_WANT = { "ffmpegAuEnc_aac" }; +static const std::vector AUDIO_DECODER_WANT = { "ffmpegAuDec_aac" }; +static const std::vector VIDEO_ENCODER_WANT = { + "HdiCodecAdapter.OMX.hisi.video.encoder.hevc", + "HdiCodecAdapter.OMX.hisi.video.encoder.avc", + "HdiCodecAdapter.OMX.rk.video_encoder.hevc", + "HdiCodecAdapter.OMX.rk.video_encoder.avc" + }; +static const std::vector VIDEO_DECODER_WANT = { + "HdiCodecAdapter.OMX.hisi.video.decoder.hevc", + "HdiCodecAdapter.OMX.hisi.video.decoder.avc", + "HdiCodecAdapter.OMX.rk.video_decoder.hevc", + "HdiCodecAdapter.OMX.rk.video_decoder.avc" + }; + +bool IsString(const nlohmann::json &jsonObj, const std::string &key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_string() && jsonObj[key].size() <= MAX_MESSAGES_LEN; + if (!res) { + AVTRANS_LOGE("the key %s in jsonObj is invalid.", key.c_str()); + } + return res; +} + +bool IsUInt8(const nlohmann::json &jsonObj, const std::string &key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_number_unsigned() && jsonObj[key] <= UINT8_MAX; + return res; +} + +bool IsUInt32(const nlohmann::json &jsonObj, const std::string &key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_number_unsigned() && jsonObj[key] <= UINT32_MAX; + if (!res) { + AVTRANS_LOGE("the key %s in jsonObj is invalid.", key.c_str()); + } + return res; +} + +std::vector ParseAudioEncoderIn(CapabilitySet &inCaps) +{ + std::vector ins; + for (auto &cap : inCaps) { + AVTRANS_LOGD("AudioEncoderIn Raw: %s", OHOS::Media::Pipeline::Capability2String(cap).c_str()); + AudioEncoderIn in; + in.mime = cap.mime; + in.sample_rate = AnyCast>(cap.keys[CapabilityID::AUDIO_SAMPLE_RATE]); + ins.push_back(in); + } + + return ins; +} + +std::vector ParseAudioEncoderOut(CapabilitySet &outCaps) +{ + std::vector outs; + for (auto &cap : outCaps) { + AVTRANS_LOGD("AudioEncoderOut Raw: %s", OHOS::Media::Pipeline::Capability2String(cap).c_str()); + AudioEncoderOut out; + out.mime = cap.mime; + out.ad_mpeg_ver = AnyCast(cap.keys[CapabilityID::AUDIO_MPEG_VERSION]); + outs.push_back(out); + } + + return outs; +} + +std::vector QueryAudioEncoderAbility() +{ + std::vector audioEncoders; + auto audioEncNameList = PluginManager::Instance().ListPlugins(PluginType::AUDIO_ENCODER); + for (const std::string& name : audioEncNameList) { + if (find(AUDIO_ENCODER_WANT.begin(), AUDIO_ENCODER_WANT.end(), name) == AUDIO_ENCODER_WANT.end()) { + AVTRANS_LOGI("AudioEncoder Plugin not want: %s", name.c_str()); + continue; + } + auto pluginInfo = PluginManager::Instance().GetPluginInfo(PluginType::AUDIO_ENCODER, name); + AudioEncoder audioEncoder; + audioEncoder.name = name; + audioEncoder.ins = ParseAudioEncoderIn(pluginInfo->inCaps); + audioEncoder.outs = ParseAudioEncoderOut(pluginInfo->outCaps); + audioEncoders.push_back(audioEncoder); + } + + return audioEncoders; +} + +void ToJson(nlohmann::json &jsonObject, const AudioEncoderIn &audioEncoderIn) +{ + jsonObject[MIME] = audioEncoderIn.mime; + nlohmann::json sampleRateJson; + for (auto rate : audioEncoderIn.sample_rate) { + sampleRateJson.push_back(rate); + } + jsonObject[SAMPLE_RATE] = sampleRateJson; +} + +void FromJson(const nlohmann::json &jsonObject, AudioEncoderIn &audioEncoderIn) +{ + if (!IsString(jsonObject, MIME)) { + AVTRANS_LOGE("AudioEncoderIn MIME is invalid!"); + return; + } + audioEncoderIn.mime = jsonObject.at(MIME).get(); + if (jsonObject.find(SAMPLE_RATE) == jsonObject.end()) { + AVTRANS_LOGE("AudioEncoderIn SAMPLE_RATE is invalid"); + } + audioEncoderIn.sample_rate = jsonObject.at(SAMPLE_RATE).get>(); +} + +void ToJson(nlohmann::json &jsonObject, const AudioEncoderOut &audioEncoderOut) +{ + jsonObject[MIME] = audioEncoderOut.mime; + jsonObject[AD_MPEG_VER] = audioEncoderOut.ad_mpeg_ver; + jsonObject[AUDIO_AAC_PROFILE] = (uint8_t)audioEncoderOut.aac_profile; + jsonObject[AUDIO_AAC_STREAM_FORMAT] = (uint8_t)audioEncoderOut.aac_stm_fmt; +} + +void FromJson(const nlohmann::json &jsonObject, AudioEncoderOut &audioEncoderOut) +{ + if (!IsString(jsonObject, MIME)) { + AVTRANS_LOGE("AudioEncoderOut MIME is invalid!"); + return; + } + audioEncoderOut.mime = jsonObject.at(MIME).get(); + + if (!IsUInt32(jsonObject, AD_MPEG_VER)) { + AVTRANS_LOGE("AudioEncoderOut AD_MPEG_VER is invalid"); + return; + } + audioEncoderOut.ad_mpeg_ver = jsonObject.at(AD_MPEG_VER).get(); + + if (!IsUInt8(jsonObject, AUDIO_AAC_PROFILE)) { + AVTRANS_LOGE("AudioEncoderOut AUDIO_AAC_PROFILE is invalid"); + return; + } + audioEncoderOut.aac_profile = (AudioAacProfile)jsonObject.at(AUDIO_AAC_PROFILE).get(); + + if (!IsUInt8(jsonObject, AUDIO_AAC_STREAM_FORMAT)) { + AVTRANS_LOGE("AudioEncoderOut AUDIO_AAC_STREAM_FORMAT is invalid"); + return; + } + audioEncoderOut.aac_stm_fmt = (AudioAacStreamFormat)jsonObject.at(AUDIO_AAC_STREAM_FORMAT).get(); +} + +void ToJson(nlohmann::json &jsonObject, const AudioEncoder &audioEncoder) +{ + jsonObject[NAME] = audioEncoder.name; + + nlohmann::json audioEncoderInsJson; + for (const auto &in : audioEncoder.ins) { + nlohmann::json audioEncoderInJson; + ToJson(audioEncoderInJson, in); + audioEncoderInsJson.push_back(audioEncoderInJson); + } + jsonObject[INS] = audioEncoderInsJson; + + nlohmann::json audioEncoderOutsJson; + for (const auto &out : audioEncoder.outs) { + nlohmann::json audioEncoderOutJson; + ToJson(audioEncoderOutJson, out); + audioEncoderOutsJson.push_back(audioEncoderOutJson); + } + jsonObject[OUTS] = audioEncoderOutsJson; +} + +void FromJson(const nlohmann::json &jsonObject, AudioEncoder &audioEncoder) +{ + if (!IsString(jsonObject, NAME)) { + AVTRANS_LOGE("AudioEncoder NAME is invalid"); + return; + } + audioEncoder.name = jsonObject.at(NAME).get(); + + if (jsonObject.find(INS) == jsonObject.end()) { + AVTRANS_LOGE("AudioEncoder INS is invalid"); + return; + } + + nlohmann::json audioEncoderInsJson = jsonObject[INS]; + for (const auto &inJson : audioEncoderInsJson) { + AudioEncoderIn in; + FromJson(inJson, in); + audioEncoder.ins.push_back(in); + } + + if (jsonObject.find(OUTS) == jsonObject.end()) { + AVTRANS_LOGE("AudioEncoder OUTS is invalid"); + return; + } + nlohmann::json audioEncoderOutsJson = jsonObject[OUTS]; + for (const auto &outJson : audioEncoderOutsJson) { + AudioEncoderOut out; + FromJson(outJson, out); + audioEncoder.outs.push_back(out); + } +} + +std::vector ParseAudioDecoderIn(CapabilitySet &inCaps) +{ + std::vector ins; + for (auto &cap : inCaps) { + AVTRANS_LOGD("AudioDecoderIn Raw: %s", OHOS::Media::Pipeline::Capability2String(cap).c_str()); + AudioDecoderIn in; + in.mime = cap.mime; + in.channel_layout = AnyCast>(cap.keys[CapabilityID::AUDIO_CHANNEL_LAYOUT]); + ins.push_back(in); + } + + return ins; +} + +std::vector ParseAudioDecoderOut(CapabilitySet &outCaps) +{ + std::vector outs; + for (auto &cap : outCaps) { + AVTRANS_LOGD("AudioDecoderOut Raw: %s", OHOS::Media::Pipeline::Capability2String(cap).c_str()); + AudioDecoderOut out; + out.mime = cap.mime; + out.sample_fmt = AnyCast>(cap.keys[CapabilityID::AUDIO_SAMPLE_FORMAT]); + outs.push_back(out); + } + + return outs; +} + +std::vector QueryAudioDecoderAbility() +{ + std::vector audioDecoders; + auto audioDecNameList = PluginManager::Instance().ListPlugins(PluginType::AUDIO_DECODER); + for (const std::string &name : audioDecNameList) { + if (find(AUDIO_DECODER_WANT.begin(), AUDIO_DECODER_WANT.end(), name) == AUDIO_DECODER_WANT.end()) { + AVTRANS_LOGI("AudioDecoder Plugin not want: %s", name.c_str()); + continue; + } + auto pluginInfo = PluginManager::Instance().GetPluginInfo(PluginType::AUDIO_DECODER, name); + AudioDecoder audioDecoder; + audioDecoder.name = name; + audioDecoder.ins = ParseAudioDecoderIn(pluginInfo->inCaps); + audioDecoder.outs = ParseAudioDecoderOut(pluginInfo->outCaps); + audioDecoders.push_back(audioDecoder); + } + + return audioDecoders; +} + +void ToJson(nlohmann::json &jsonObject, const AudioDecoderIn &audioDecoderIn) +{ + jsonObject[MIME] = audioDecoderIn.mime; + nlohmann::json channelLayoutJson; + for (auto &layout : audioDecoderIn.channel_layout) { + channelLayoutJson.push_back((uint64_t)layout); + } + jsonObject[AUDIO_CHANNEL_LAYOUT] = channelLayoutJson; +} + +void FromJson(const nlohmann::json &jsonObject, AudioDecoderIn &audioDecoderIn) +{ + if (!IsString(jsonObject, MIME)) { + AVTRANS_LOGE("AudioDecoderIn MIME is invalid"); + return; + } + audioDecoderIn.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(AUDIO_CHANNEL_LAYOUT) == jsonObject.end()) { + AVTRANS_LOGE("AudioEncoder AUDIO_CHANNEL_LAYOUT is invalid"); + return; + } + nlohmann::json channelLayoutJson = jsonObject[AUDIO_CHANNEL_LAYOUT]; + for (auto layout : channelLayoutJson) { + audioDecoderIn.channel_layout.push_back((AudioChannelLayout)layout); + } +} + +void ToJson(nlohmann::json &jsonObject, const AudioDecoderOut &audioDecoderOut) +{ + jsonObject[MIME] = audioDecoderOut.mime; + nlohmann::json sampleFormatsJson; + for (auto &sampleFormat : audioDecoderOut.sample_fmt) { + sampleFormatsJson.push_back((uint8_t)sampleFormat); + } + jsonObject[AUDIO_SAMPLE_FORMAT] = sampleFormatsJson; +} + +void FromJson(const nlohmann::json &jsonObject, AudioDecoderOut &audioDecoderOut) +{ + if (!IsString(jsonObject, MIME)) { + AVTRANS_LOGE("AudioDecoderOut MIME is invalid"); + return; + } + audioDecoderOut.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(AUDIO_SAMPLE_FORMAT) == jsonObject.end()) { + AVTRANS_LOGE("AudioDecoderOut AUDIO_SAMPLE_FORMAT is invalid"); + return; + } + + for (auto sampleFormatJson : jsonObject[AUDIO_SAMPLE_FORMAT]) { + audioDecoderOut.sample_fmt.push_back((AudioSampleFormat)sampleFormatJson); + } +} + +void ToJson(nlohmann::json &jsonObject, const AudioDecoder &audioDecoder) +{ + jsonObject[NAME] = audioDecoder.name; + nlohmann::json audioDecoderInsJson; + for (const auto &in : audioDecoder.ins) { + nlohmann::json audioDecoderInJson; + ToJson(audioDecoderInJson, in); + audioDecoderInsJson.push_back(audioDecoderInJson); + } + jsonObject[INS] = audioDecoderInsJson; + + nlohmann::json audioDecoderOutsJson; + for (const auto &out : audioDecoder.outs) { + nlohmann::json audioDecoderOutJson; + ToJson(audioDecoderOutJson, out); + audioDecoderOutsJson.push_back(audioDecoderOutJson); + } + jsonObject[OUTS] = audioDecoderOutsJson; +} + +void FromJson(const nlohmann::json &jsonObject, AudioDecoder &audioDecoder) +{ + if (!IsString(jsonObject, NAME)) { + AVTRANS_LOGE("AudioDecoder NAME is invalid"); + return; + } + audioDecoder.name = jsonObject.at(NAME).get(); + + if (jsonObject.find(INS) == jsonObject.end()) { + AVTRANS_LOGE("AudioDecoder INS is invalid"); + return; + } + + nlohmann::json audioDecoderInsJson = jsonObject[INS]; + for (const auto &inJson : audioDecoderInsJson) { + AudioDecoderIn in; + FromJson(inJson, in); + audioDecoder.ins.push_back(in); + } + + if (jsonObject.find(OUTS) == jsonObject.end()) { + AVTRANS_LOGE("AudioDecoder OUTS is invalid"); + return; + } + nlohmann::json audioDecoderOutsJson = jsonObject[OUTS]; + for (const auto &outJson : audioDecoderOutsJson) { + AudioDecoderOut out; + FromJson(outJson, out); + audioDecoder.outs.push_back(out); + } +} + +std::vector ParseVideoEncoderIn(CapabilitySet &inCaps) +{ + std::vector ins; + for (auto &cap : inCaps) { + AVTRANS_LOGD("VideoEncoderIn Raw: %s", OHOS::Media::Pipeline::Capability2String(cap).c_str()); + VideoEncoderIn in; + in.mime = cap.mime; + in.pixel_fmt = AnyCast>(cap.keys[CapabilityID::VIDEO_PIXEL_FORMAT]); + ins.push_back(in); + } + + return ins; +} + +std::vector ParseVideoEncoderOut(CapabilitySet &outCaps) +{ + std::vector outs; + for (auto &cap : outCaps) { + AVTRANS_LOGD("VideoEncoderOut Raw: %s", OHOS::Media::Pipeline::Capability2String(cap).c_str()); + VideoEncoderOut out; + out.mime = cap.mime; + outs.push_back(out); + } + + return outs; +} + +std::vector QueryVideoEncoderAbility() +{ + std::vector videoEncoders; + auto videoEncNameList = PluginManager::Instance().ListPlugins(PluginType::VIDEO_ENCODER); + for (const std::string& name : videoEncNameList) { + if (find(VIDEO_ENCODER_WANT.begin(), VIDEO_ENCODER_WANT.end(), name) == VIDEO_ENCODER_WANT.end()) { + AVTRANS_LOGI("VideoEncoder Plugin not want: %s", name.c_str()); + continue; + } + auto pluginInfo = PluginManager::Instance().GetPluginInfo(PluginType::VIDEO_ENCODER, name); + VideoEncoder videoEncoder; + videoEncoder.name = name; + videoEncoder.ins = ParseVideoEncoderIn(pluginInfo->inCaps); + videoEncoder.outs = ParseVideoEncoderOut(pluginInfo->outCaps); + videoEncoders.push_back(videoEncoder); + } + + return videoEncoders; +} + +void ToJson(nlohmann::json &jsonObject, const VideoEncoderIn &videoEncoderIn) +{ + jsonObject[MIME] = videoEncoderIn.mime; + nlohmann::json pixelFmtJson; + for (auto &fmt : videoEncoderIn.pixel_fmt) { + pixelFmtJson.push_back((uint32_t)fmt); + } + jsonObject[VIDEO_PIXEL_FMT] = pixelFmtJson; +} + +void FromJson(const nlohmann::json &jsonObject, VideoEncoderIn &videoEncoderIn) +{ + if (!IsString(jsonObject, MIME)) { + AVTRANS_LOGE("VideoEncoderIn MIME is invalid"); + return; + } + videoEncoderIn.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(VIDEO_PIXEL_FMT) == jsonObject.end()) { + AVTRANS_LOGE("VideoEncoderIn VIDEO_PIXEL_FMT is invalid"); + return; + } + for (auto fmt : jsonObject[VIDEO_PIXEL_FMT]) { + videoEncoderIn.pixel_fmt.push_back((VideoPixelFormat)fmt); + } +} + +void ToJson(nlohmann::json &jsonObject, const VideoEncoderOut &videoEncoderOut) +{ + jsonObject[MIME] = videoEncoderOut.mime; +} + +void FromJson(const nlohmann::json &jsonObject, VideoEncoderOut &videoEncoderOut) +{ + if (!IsString(jsonObject, MIME)) { + AVTRANS_LOGE("VideoEncoderOut MIME is invalid"); + return; + } + videoEncoderOut.mime = jsonObject[MIME].get(); +} + +void ToJson(nlohmann::json &jsonObject, const VideoEncoder &videoEncoder) +{ + jsonObject[NAME] = videoEncoder.name; + nlohmann::json videoEncoderInsJson; + for (const auto &in : videoEncoder.ins) { + nlohmann::json videoEncoderInJson; + ToJson(videoEncoderInJson, in); + videoEncoderInsJson.push_back(videoEncoderInJson); + } + jsonObject[INS] = videoEncoderInsJson; + + nlohmann::json videoEncoderOutsJson; + for (const auto &out : videoEncoder.outs) { + nlohmann::json videoEncoderOutJson; + ToJson(videoEncoderOutJson, out); + videoEncoderOutsJson.push_back(videoEncoderOutJson); + } + jsonObject[OUTS] = videoEncoderOutsJson; +} + +void FromJson(const nlohmann::json &jsonObject, VideoEncoder &videoEncoder) +{ + if (!IsString(jsonObject, NAME)) { + AVTRANS_LOGE("VideoEncoder NAME is invalid"); + return; + } + videoEncoder.name = jsonObject.at(NAME).get(); + + if (jsonObject.find(INS) == jsonObject.end()) { + AVTRANS_LOGE("VideoEncoder INS is invalid"); + return; + } + + nlohmann::json videoEncoderInsJson = jsonObject[INS]; + for (const auto &inJson : videoEncoderInsJson) { + VideoEncoderIn in; + FromJson(inJson, in); + videoEncoder.ins.push_back(in); + } + + if (jsonObject.find(OUTS) == jsonObject.end()) { + AVTRANS_LOGE("VideoEncoder OUTS is invalid"); + return; + } + nlohmann::json videoEncoderOutsJson = jsonObject[OUTS]; + for (const auto &outJson : videoEncoderOutsJson) { + VideoEncoderOut out; + FromJson(outJson, out); + videoEncoder.outs.push_back(out); + } +} + +std::vector ParseVideoDecoderIn(CapabilitySet &inCaps) +{ + std::vector ins; + for (auto &cap : inCaps) { + AVTRANS_LOGD("VideoDecoderIn Raw: %s", OHOS::Media::Pipeline::Capability2String(cap).c_str()); + VideoDecoderIn in; + in.mime = cap.mime; + in.vd_bit_stream_fmt = + AnyCast>(cap.keys[CapabilityID::VIDEO_BIT_STREAM_FORMAT]); + ins.push_back(in); + } + + return ins; +} + +std::vector ParseVideoDecoderOut(CapabilitySet &outCaps) +{ + std::vector outs; + for (auto &cap : outCaps) { + AVTRANS_LOGD("VideoDecoderOut Raw: %s", OHOS::Media::Pipeline::Capability2String(cap).c_str()); + VideoDecoderOut out; + out.mime = cap.mime; + out.pixel_fmt = AnyCast>(cap.keys[CapabilityID::VIDEO_PIXEL_FORMAT]); + outs.push_back(out); + } + + return outs; +} + +std::vector QueryVideoDecoderAbility() +{ + std::vector VideoDecoders; + auto videoDecNameList = PluginManager::Instance().ListPlugins(PluginType::VIDEO_DECODER); + for (const std::string& name : videoDecNameList) { + if (find(VIDEO_DECODER_WANT.begin(), VIDEO_DECODER_WANT.end(), name) == VIDEO_DECODER_WANT.end()) { + AVTRANS_LOGI("VideoDecoder Plugin not want: %s", name.c_str()); + continue; + } + auto pluginInfo = PluginManager::Instance().GetPluginInfo(PluginType::VIDEO_DECODER, name); + VideoDecoder videoDecoder; + videoDecoder.name = name; + videoDecoder.ins = ParseVideoDecoderIn(pluginInfo->inCaps); + videoDecoder.outs = ParseVideoDecoderOut(pluginInfo->outCaps); + VideoDecoders.push_back(videoDecoder); + } + + return VideoDecoders; +} + +void ToJson(nlohmann::json &jsonObject, const VideoDecoderIn &videoDecoderIn) +{ + jsonObject[MIME] = videoDecoderIn.mime; + nlohmann::json fmtJson; + for (auto &fmt : videoDecoderIn.vd_bit_stream_fmt) { + fmtJson.push_back((uint32_t)fmt); + } + jsonObject[VIDEO_BIT_STREAM_FMT] = fmtJson; +} + +void FromJson(const nlohmann::json &jsonObject, VideoDecoderIn &videoDecoderIn) +{ + if (!IsString(jsonObject, MIME)) { + AVTRANS_LOGE("VideoDecoderIn MIME is invalid"); + return; + } + videoDecoderIn.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(VIDEO_BIT_STREAM_FMT) == jsonObject.end()) { + AVTRANS_LOGE("VideoDecoderIn VIDEO_BIT_STREAM_FMT is invalid"); + return; + } + for (auto fmt : jsonObject[VIDEO_BIT_STREAM_FMT]) { + videoDecoderIn.vd_bit_stream_fmt.push_back((VideoBitStreamFormat)fmt); + } +} + +void ToJson(nlohmann::json &jsonObject, const VideoDecoderOut &videoDecoderOut) +{ + jsonObject[MIME] = videoDecoderOut.mime; + nlohmann::json fmtJson; + for (auto &fmt : videoDecoderOut.pixel_fmt) { + fmtJson.push_back((uint32_t)fmt); + } + jsonObject[VIDEO_PIXEL_FMT] = fmtJson; +} + +void FromJson(const nlohmann::json &jsonObject, VideoDecoderOut &videoDecoderOut) +{ + if (!IsString(jsonObject, MIME)) { + AVTRANS_LOGE("VideoDecoderOut MIME is invalid"); + return; + } + videoDecoderOut.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(VIDEO_PIXEL_FMT) == jsonObject.end()) { + AVTRANS_LOGE("VideoDecoderOut VIDEO_PIXEL_FMT is invalid"); + return; + } + for (auto fmt : jsonObject[VIDEO_PIXEL_FMT]) { + videoDecoderOut.pixel_fmt.push_back((VideoPixelFormat)fmt); + } +} + +void ToJson(nlohmann::json &jsonObject, const VideoDecoder &videoDecoder) +{ + jsonObject[NAME] = videoDecoder.name; + nlohmann::json videoDecoderInsJson; + for (const auto &in : videoDecoder.ins) { + nlohmann::json videoDecoderInJson; + ToJson(videoDecoderInJson, in); + videoDecoderInsJson.push_back(videoDecoderInJson); + } + jsonObject[INS] = videoDecoderInsJson; + + nlohmann::json videoDecoderOutsJson; + for (const auto &out : videoDecoder.outs) { + nlohmann::json videoDecoderOutJson; + ToJson(videoDecoderOutJson, out); + videoDecoderOutsJson.push_back(videoDecoderOutJson); + } + jsonObject[OUTS] = videoDecoderOutsJson; +} + +void FromJson(const nlohmann::json &jsonObject, VideoDecoder &videoDecoder) +{ + if (!IsString(jsonObject, NAME)) { + AVTRANS_LOGE("VideoDecoder NAME is invalid"); + return; + } + videoDecoder.name = jsonObject.at(NAME).get(); + + if (jsonObject.find(INS) == jsonObject.end()) { + AVTRANS_LOGE("VideoDecoder INS is invalid"); + return; + } + + nlohmann::json videoDecoderInsJson = jsonObject[INS]; + for (const auto &inJson : videoDecoderInsJson) { + VideoDecoderIn in; + FromJson(inJson, in); + videoDecoder.ins.push_back(in); + } + + if (jsonObject.find(OUTS) == jsonObject.end()) { + AVTRANS_LOGE("VideoDecoder OUTS is invalid"); + return; + } + nlohmann::json videoDecoderOutsJson = jsonObject[OUTS]; + for (const auto &outJson : videoDecoderOutsJson) { + VideoDecoderOut out; + FromJson(outJson, out); + videoDecoder.outs.push_back(out); + } +} + +template +void ToJson(const std::string &key, nlohmann::json &jsonObject, std::vector &objs) +{ + nlohmann::json jsonObjs; + for (auto &obj : objs) { + nlohmann::json jsonObj; + ToJson(jsonObj, obj); + jsonObjs.push_back(jsonObj); + } + jsonObject[key] = jsonObjs; +} + +template +void FromJson(const std::string &key, const nlohmann::json &jsonObject, std::vector &objs) +{ + if (jsonObject.find(key) == jsonObject.end()) { + AVTRANS_LOGE("JSONObject key invalid, key: %s", key.c_str()); + return; + } + for (const auto &json : jsonObject[key]) { + T obj; + FromJson(json, obj); + objs.push_back(obj); + } +} + +int32_t QueryAudioEncoderAbilityStr(char* res) +{ + std::vector audioEncoders = QueryAudioEncoderAbility(); + nlohmann::json jsonObject; + ToJson(AUDIO_ENCODERS, jsonObject, audioEncoders); + std::string ret = jsonObject.dump(); + AVTRANS_LOGI("QueryAudioEncoderAbilityStr ret: %s", ret.c_str()); + if (ret.length() > MAX_MESSAGES_LEN) { + AVTRANS_LOGE("QueryAudioEncoderAbilityStr too long"); + return 0; + } + if (memcpy_s(res, MAX_MESSAGES_LEN, ret.c_str(), ret.length()) != EOK) { + return 0; + } + return ret.length(); +} + +int32_t QueryAudioDecoderAbilityStr(char* res) +{ + std::vector audioDecoders = QueryAudioDecoderAbility(); + nlohmann::json jsonObject; + ToJson(AUDIO_DECODERS, jsonObject, audioDecoders); + std::string ret = jsonObject.dump(); + AVTRANS_LOGI("QueryAudioDecoderAbilityStr ret: %s", ret.c_str()); + if (ret.length() > MAX_MESSAGES_LEN) { + AVTRANS_LOGE("QueryAudioDecoderAbilityStr too long"); + return 0; + } + if (memcpy_s(res, MAX_MESSAGES_LEN, ret.c_str(), ret.length()) != EOK) { + return 0; + } + return ret.length(); +} + +int32_t QueryVideoEncoderAbilityStr(char* res) +{ + std::vector viudeoEncoders = QueryVideoEncoderAbility(); + nlohmann::json jsonObject; + ToJson(VIDEO_ENCODERS, jsonObject, viudeoEncoders); + std::string ret = jsonObject.dump(); + AVTRANS_LOGI("QueryVideoEncoderAbilityStr ret: %s", ret.c_str()); + if (ret.length() > MAX_MESSAGES_LEN) { + AVTRANS_LOGE("QueryVideoEncoderAbilityStr too long"); + return 0; + } + if (memcpy_s(res, MAX_MESSAGES_LEN, ret.c_str(), ret.length()) != EOK) { + return 0; + } + return ret.length(); +} + +int32_t QueryVideoDecoderAbilityStr(char* res) +{ + std::vector videoDecoders = QueryVideoDecoderAbility(); + nlohmann::json jsonObject; + ToJson(VIDEO_DECODERS, jsonObject, videoDecoders); + std::string ret = jsonObject.dump(); + AVTRANS_LOGI("QueryVideoDecoderAbilityStr ret: %s", ret.c_str()); + if (ret.length() > MAX_MESSAGES_LEN) { + AVTRANS_LOGE("QueryVideoDecoderAbilityStr too long"); + return 0; + } + if (memcpy_s(res, MAX_MESSAGES_LEN, ret.c_str(), ret.length()) != EOK) { + return 0; + } + return ret.length(); +} +} +} \ No newline at end of file diff --git a/av_transport/av_trans_handler/histreamer_ability_querier/src/histreamer_ability_querier_core.rs b/av_transport/av_trans_handler/histreamer_ability_querier/src/histreamer_ability_querier_core.rs new file mode 100644 index 0000000000000000000000000000000000000000..720836c9120bdcb76b930e1ac6a1d259d186fc10 --- /dev/null +++ b/av_transport/av_trans_handler/histreamer_ability_querier/src/histreamer_ability_querier_core.rs @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//! rust dynamic lib for query histreamer ability + +use std::os::raw::c_char; +use std::os::raw::c_int; + +static AUDIO_ABILITY: &str = "{ \"AAC\" }"; +static VIDEO_ABILITY: &str = "{ \"H264\", \"H265\" }"; + +/// function Query Ablility by ability type +#[no_mangle] +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub extern "C" fn Query(ability_type: u8, out: *mut c_char) -> c_int +{ + match ability_type { + 1 => { + let addr: *mut u8 = AUDIO_ABILITY.as_ptr() as *mut u8; + let len = AUDIO_ABILITY.len(); + unsafe { std::ptr::copy(addr, out, AUDIO_ABILITY.len()) }; + len as c_int + } + 2 => { + let addr: *mut u8 = VIDEO_ABILITY.as_ptr() as *mut u8; + let len = VIDEO_ABILITY.len(); + unsafe { std::ptr::copy(addr, out, VIDEO_ABILITY.len()) }; + len as c_int + } + _ => { 0 } + } +} \ No newline at end of file diff --git a/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/BUILD.gn b/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..036409253872b6bbe7bd59be0f216683f3d5a514 --- /dev/null +++ b/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +import( + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/distributed_av_transport.gni") + +module_out_path = "distributed_hardware_fwk/histreamer_ability_querier_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//third_party/json/include", + "${handler_path}/histreamer_ability_querier/include", + "${engine_path}/av_sender/include", + "${engine_path}/av_receiver/include", + "${interface_path}", + "${common_path}/include", + "${media_standard_path}/interfaces/inner_api/native", + ] +} + +ohos_unittest("HistreamerAbilityQuerierTest") { + module_out_path = module_out_path + + sources = [ "src/histreamer_ability_querier_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${handler_path}/histreamer_ability_querier:histreamer_ability_querier", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "histreamer:histreamer_base", + "histreamer:histreamer_codec_filters", + "histreamer:histreamer_ffmpeg_convert", + "histreamer:histreamer_plugin_base", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"HistreamerAbilityQuerierTest\"", + ] +} + +group("histreamer_ability_querier_test") { + testonly = true + deps = [ ":HistreamerAbilityQuerierTest" ] +} diff --git a/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/include/histreamer_ability_querier_test.h b/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/include/histreamer_ability_querier_test.h new file mode 100644 index 0000000000000000000000000000000000000000..abbbf30ab8e7d3395c88792dc25ac702a8eb9ad7 --- /dev/null +++ b/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/include/histreamer_ability_querier_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_HISTREAMER_ABILITY_QUERIER_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_HISTREAMER_ABILITY_QUERIER_TEST_H + +#include "nlohmann/json.hpp" +#include + +namespace OHOS { +namespace DistributedHardware { +class HistreamerAbilityQuerierTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +bool IsUInt8(const nlohmann::json& jsonObj, const std::string& key); + +bool IsUInt32(const nlohmann::json& jsonObj, const std::string& key); + +bool IsString(const nlohmann::json& jsonObj, const std::string& key); +} // namespace DistributedHardware +} // namespace OHOS +#endif \ No newline at end of file diff --git a/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/src/histreamer_ability_querier_test.cpp b/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/src/histreamer_ability_querier_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..661909bb24c93cee9aa40dbbf53564f1d987c740 --- /dev/null +++ b/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common/src/histreamer_ability_querier_test.cpp @@ -0,0 +1,538 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "histreamer_ability_querier_test.h" +#include "histreamer_ability_querier.h" + +#include +#include +#include +#include + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void HistreamerAbilityQuerierTest::SetUpTestCase(void) {} + +void HistreamerAbilityQuerierTest::TearDownTestCase(void) {} + +void HistreamerAbilityQuerierTest::SetUp() {} + +void HistreamerAbilityQuerierTest::TearDown() {} + +namespace { +int32_t g_maxMessagesLen = 1 * 1024 * 1024; +static const std::uint16_t UINT16_ONE = 1; +static const std::vector::size_type VIDEO_ENCODER_FOUR = 4; +static const std::vector::size_type VIDEO_DECODER_FOUR = 4; + +static const std::string TEST_STR = "test string"; +static const std::string KEY = "key"; +static const std::string NAME = "name"; +static const std::string MIME = "mime"; +static const std::string AUDIO_ENCODER_NAME = "ffmpegAuEnc_aac"; +static const std::string AUDIO_ENCODERIN_MIME = "audio/raw"; +static const std::string AUDIO_ENCODEROUT_MIME = "audio/mp4a-latm"; +static const std::string AD_MPEG_VER = "ad_mpeg_ver"; +static const std::uint32_t AD_MPEG_VER_VALUE = 4; +static const std::string AUDIO_AAC_PROFILE = "aac_profile"; +static const std::uint32_t AUDIO_AAC_PROFILE_VALUE = 0; +static const std::string AUDIO_AAC_STREAM_FORMAT = "aac_stm_fmt"; + +static const std::string AUDIO_DECODER_NAME = "ffmpegAuDec_aac"; +static const std::string AUDIO_DECODERIN_MIME = "audio/mp4a-latm"; +static const std::string AUDIO_DECODEROUT_MIME = "audio/raw"; + +static const std::string VIDEO_ENCODER_NAME = "HdiCodecAdapter.OMX.rk.video_encoder.hevc"; +static const std::string VIDEO_ENCODERIN_MIME = "video/raw"; + +static const std::string VIDEO_DECODER_NAME = "HdiCodecAdapter.OMX.rk.video_decoder.hevc"; +static const std::string VIDEO_DECODERIN_MIME = "video/hevc"; +static const std::string VIDEO_DECODEROUT_MIME = "video/raw"; + +static const std::vector AUDIO_ENCODER_WANT = { "ffmpegAuEnc_aac" }; +static const std::vector AUDIO_DECODER_WANT = { "ffmpegAuDec_aac" }; +static const std::vector VIDEO_ENCODER_WANT = { + "HdiCodecAdapter.OMX.hisi.video.encoder.hevc", + "HdiCodecAdapter.OMX.hisi.video.encoder.avc", + "HdiCodecAdapter.OMX.rk.video_encoder.hevc", + "HdiCodecAdapter.OMX.rk.video_encoder.avc" + }; +static const std::vector VIDEO_DECODER_WANT = { + "HdiCodecAdapter.OMX.hisi.video.decoder.hevc", + "HdiCodecAdapter.OMX.hisi.video.decoder.avc", + "HdiCodecAdapter.OMX.rk.video_decoder.hevc", + "HdiCodecAdapter.OMX.rk.video_decoder.avc" + }; +} + +/** + * @tc.name:histreamer_ability_querier_test_001 + * @tc.desc: Verify the QueryAudioEncoderAbility function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_001, TestSize.Level0) +{ + std::vector audioEncoders = QueryAudioEncoderAbility(); + EXPECT_FALSE(audioEncoders.empty()); + for (std::vector::size_type i = 0; i < audioEncoders.size(); i++) { + auto it = find(AUDIO_ENCODER_WANT.begin(), AUDIO_ENCODER_WANT.end(), audioEncoders[i].name); + EXPECT_TRUE(it != AUDIO_ENCODER_WANT.end()); + } +} + +/** + * @tc.name: histreamer_ability_querier_test_002 + * @tc.desc: Verify QueryAudioDecoderAbility function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_002, TestSize.Level0) +{ + std::vector audioDecoders = QueryAudioDecoderAbility(); + EXPECT_FALSE(audioDecoders.empty()); + for (std::vector::size_type i = 0; i < audioDecoders.size(); i++) { + auto it = find(AUDIO_DECODER_WANT.begin(), AUDIO_DECODER_WANT.end(), audioDecoders[i].name); + EXPECT_TRUE(it != AUDIO_DECODER_WANT.end()); + } +} + +/** + * @tc.name: histreamer_ability_querier_test_003 + * @tc.desc: Verify QueryVideoEncoderAbility function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_003, TestSize.Level0) +{ + std::vector videoEncoders = QueryVideoEncoderAbility(); + EXPECT_FALSE(videoEncoders.empty() || videoEncoders.size() > VIDEO_ENCODER_FOUR); + for (std::vector::size_type i = 0; i < videoEncoders.size(); i++) { + auto it = find(VIDEO_ENCODER_WANT.begin(), VIDEO_ENCODER_WANT.end(), videoEncoders[i].name); + EXPECT_TRUE(it != VIDEO_ENCODER_WANT.end()); + } +} + +/** + * @tc.name: histreamer_ability_querier_test_004 + * @tc.desc: Verify QueryVideoDecoderAbility function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + * + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_004, TestSize.Level0) +{ + std::vector videoDecoders = QueryVideoDecoderAbility(); + EXPECT_FALSE(videoDecoders.empty() || videoDecoders.size() > VIDEO_DECODER_FOUR); + for (std::vector::size_type i = 0; i < videoDecoders.size(); i++) { + auto it = find(VIDEO_DECODER_WANT.begin(), VIDEO_DECODER_WANT.end(), videoDecoders[i].name); + EXPECT_TRUE(it != VIDEO_DECODER_WANT.end()); + } +} + +/** + * @tc.name: histreamer_ability_querier_test_005 + * @tc.desc: Verify QueryAudioEncoderAbilityStr function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_005, TestSize.Level0) +{ + char* RES_MAX = new char[g_maxMessagesLen]; + EXPECT_TRUE(QueryAudioEncoderAbilityStr(RES_MAX) >= 0); + EXPECT_TRUE(QueryAudioEncoderAbilityStr(RES_MAX) <= g_maxMessagesLen); + delete[] RES_MAX; +} + +/** + * @tc.name: histreamer_ability_querier_test_006 + * @tc.desc: Verify QueryAudioDecoderAbilityStr function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_006, TestSize.Level0) +{ + char* RES_MAX = new char[g_maxMessagesLen]; + EXPECT_TRUE(QueryAudioDecoderAbilityStr(RES_MAX) >= 0); + EXPECT_TRUE(QueryAudioDecoderAbilityStr(RES_MAX) <= g_maxMessagesLen); + delete[] RES_MAX; +} + +/** + * @tc.name: histreamer_ability_querier_test_007 + * @tc.desc: Verify QueryVideoEncoderAbilityStr function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_007, TestSize.Level0) +{ + char* RES_MAX = new char[g_maxMessagesLen]; + EXPECT_TRUE(QueryVideoEncoderAbilityStr(RES_MAX) >= 0); + EXPECT_TRUE(QueryVideoEncoderAbilityStr(RES_MAX) <= g_maxMessagesLen); + delete[] RES_MAX; +} + +/** + * @tc.name: histreamer_ability_querier_test_008 + * @tc.desc: Verify the QueryVideoDecoderAbilityStr function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_008, TestSize.Level0) +{ + char* RES_MAX = new char[g_maxMessagesLen]; + EXPECT_TRUE(QueryVideoDecoderAbilityStr(RES_MAX) >= 0); + EXPECT_TRUE(QueryVideoDecoderAbilityStr(RES_MAX) <= g_maxMessagesLen); + delete[] RES_MAX; +} + +/** + * @tc.name: histreamer_ability_querier_test_009 + * @tc.desc: Verify the IsString function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_009, TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject[KEY] = TEST_STR; + EXPECT_TRUE(IsString(jsonObject, KEY)); + + jsonObject[KEY] = 1; + EXPECT_FALSE(IsString(jsonObject, KEY)); +} + +/** + * @tc.name: histreamer_ability_querier_test_010 + * @tc.desc: Verify the IsUint8 function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_010, TestSize.Level0) +{ + nlohmann::json jsonObject; + const uint8_t num_s = 1; + jsonObject[KEY] = num_s; + EXPECT_TRUE(IsUInt8(jsonObject, KEY)); + + const uint16_t num_b = UINT8_MAX + 1 ; + jsonObject[KEY] = num_b; + EXPECT_FALSE(IsUInt8(jsonObject, KEY)); +} + +/** + * @tc.name: histreamer_ability_querier_test_011 + * @tc.desc: Verify the IsUInt32 function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_011, TestSize.Level0) +{ + nlohmann::json jsonObject; + const uint32_t num_s = 1; + jsonObject[KEY] = num_s; + EXPECT_TRUE(IsUInt32(jsonObject, KEY)); + + const int32_t num_i = -1; + jsonObject[KEY] = num_i; + EXPECT_FALSE(IsUInt32(jsonObject, KEY)); +} + +/** + * @tc.name: histreamer_ability_querier_test_012 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioEncoderIn &audioEncoderIn) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_012, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioEncoderIn audioEncoderIn; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, audioEncoderIn); + EXPECT_TRUE(audioEncoderIn.mime.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_013 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioEncoderOut &audioEncoderOut) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_013, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioEncoderOut audioEncoderOut; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, audioEncoderOut); + EXPECT_TRUE(audioEncoderOut.mime.empty()); + + jsonObject[MIME] = AUDIO_ENCODEROUT_MIME; + jsonObject[AD_MPEG_VER] = TEST_STR; + FromJson(jsonObject, audioEncoderOut); + EXPECT_EQ(AUDIO_ENCODEROUT_MIME, audioEncoderOut.mime); + + jsonObject[AD_MPEG_VER] = AD_MPEG_VER_VALUE; + jsonObject[AUDIO_AAC_PROFILE] = TEST_STR; + FromJson(jsonObject, audioEncoderOut); + EXPECT_EQ(AD_MPEG_VER_VALUE, (uint32_t)audioEncoderOut.ad_mpeg_ver); + + jsonObject[AUDIO_AAC_PROFILE] = AUDIO_AAC_PROFILE_VALUE; + jsonObject[AUDIO_AAC_STREAM_FORMAT] = TEST_STR; + FromJson(jsonObject, audioEncoderOut); + EXPECT_EQ(AUDIO_AAC_PROFILE_VALUE, (uint32_t)audioEncoderOut.aac_profile); +} + +/** + * @tc.name: histreamer_ability_querier_test_014 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioEncoder &audioEncoder) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_014, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioEncoder audioEncoder; + jsonObject[NAME] = UINT16_ONE; + FromJson(jsonObject, audioEncoder); + EXPECT_TRUE(audioEncoder.name.empty()); + + jsonObject[NAME] = AUDIO_ENCODER_NAME; + FromJson(jsonObject, audioEncoder); + EXPECT_EQ(AUDIO_ENCODER_NAME, audioEncoder.name); + EXPECT_TRUE(audioEncoder.ins.empty()); + + AudioEncoderIn audioEncoderIn; + audioEncoderIn.mime = AUDIO_ENCODERIN_MIME; + audioEncoderIn.sample_rate = {96000, 88200, 64000, 48000, 44100, 32000}; + audioEncoder.ins.push_back(audioEncoderIn); + FromJson(jsonObject, audioEncoder); + EXPECT_FALSE(audioEncoder.ins.empty()); + EXPECT_TRUE(audioEncoder.outs.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_015 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioDecoderIn &audioDecoderIn) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_015, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioDecoderIn audioDecoderIn; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, audioDecoderIn); + EXPECT_TRUE(audioDecoderIn.mime.empty()); + + jsonObject[MIME] = AUDIO_DECODERIN_MIME; + FromJson(jsonObject, audioDecoderIn); + EXPECT_EQ(AUDIO_DECODERIN_MIME, audioDecoderIn.mime); + EXPECT_TRUE(audioDecoderIn.channel_layout.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_016 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioDecoderOut &audioDecoderOut) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_016, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioDecoderOut audioDecoderOut; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, audioDecoderOut); + EXPECT_TRUE(audioDecoderOut.mime.empty()); + + jsonObject[MIME] = AUDIO_DECODEROUT_MIME; + FromJson(jsonObject, audioDecoderOut); + EXPECT_EQ(AUDIO_DECODEROUT_MIME, audioDecoderOut.mime); + EXPECT_TRUE(audioDecoderOut.sample_fmt.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_017 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioDecoder &audioDecoder) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_017, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioDecoder audioDecoder; + jsonObject[NAME] = UINT16_ONE; + FromJson(jsonObject, audioDecoder); + EXPECT_TRUE(audioDecoder.name.empty()); + + jsonObject[NAME] = AUDIO_DECODER_NAME; + FromJson(jsonObject, audioDecoder); + EXPECT_EQ(AUDIO_DECODER_NAME, audioDecoder.name); + EXPECT_TRUE(audioDecoder.ins.empty()); + + AudioDecoderIn audioDecoderIn; + audioDecoderIn.mime = AUDIO_DECODERIN_MIME; + audioDecoderIn.channel_layout = { + AudioChannelLayout::CH_2POINT1, + AudioChannelLayout::CH_2_1, + AudioChannelLayout::SURROUND, + }; + audioDecoder.ins.push_back(audioDecoderIn); + FromJson(jsonObject, audioDecoder); + EXPECT_FALSE(audioDecoder.ins.empty()); + EXPECT_TRUE(audioDecoder.outs.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_018 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoEncoderIn &videoEncoderIn) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_018, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoEncoderIn videoEncoderIn; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, videoEncoderIn); + EXPECT_TRUE(videoEncoderIn.mime.empty()); + + jsonObject[MIME] = VIDEO_ENCODERIN_MIME; + FromJson(jsonObject, videoEncoderIn); + EXPECT_EQ(VIDEO_ENCODERIN_MIME, videoEncoderIn.mime); + EXPECT_TRUE(videoEncoderIn.pixel_fmt.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_019 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoEncoderOut &videoEncoderOut) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_019, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoEncoderOut videoEncoderOut; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, videoEncoderOut); + EXPECT_TRUE(videoEncoderOut.mime.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_020 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoEncoder &videoEncoder) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_020, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoEncoder videoEncoder; + jsonObject[NAME] = UINT16_ONE; + FromJson(jsonObject, videoEncoder); + EXPECT_TRUE(videoEncoder.name.empty()); + + jsonObject[NAME] = VIDEO_ENCODER_NAME; + FromJson(jsonObject, videoEncoder); + EXPECT_EQ(VIDEO_ENCODER_NAME, videoEncoder.name); + EXPECT_TRUE(videoEncoder.ins.empty()); + + VideoEncoderIn videoEncoderIn; + videoEncoderIn.mime = VIDEO_ENCODERIN_MIME; + videoEncoderIn.pixel_fmt = { + VideoPixelFormat::YUV410P, + VideoPixelFormat::RGBA, + }; + videoEncoder.ins.push_back(videoEncoderIn); + FromJson(jsonObject, videoEncoder); + EXPECT_FALSE(videoEncoder.ins.empty()); + EXPECT_TRUE(videoEncoder.outs.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_021 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoDecoderIn &videoDecoderIn) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_021, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoDecoderIn videoDecoderIn; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, videoDecoderIn); + EXPECT_TRUE(videoDecoderIn.mime.empty()); + + jsonObject[MIME] = VIDEO_DECODERIN_MIME; + FromJson(jsonObject, videoDecoderIn); + EXPECT_EQ(VIDEO_DECODERIN_MIME, videoDecoderIn.mime); + EXPECT_TRUE(videoDecoderIn.vd_bit_stream_fmt.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_022 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoDecoderOut &videoDecoderOut) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_022, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoDecoderOut videoDecoderOut; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, videoDecoderOut); + EXPECT_TRUE(videoDecoderOut.mime.empty()); + + jsonObject[MIME] = VIDEO_DECODEROUT_MIME; + FromJson(jsonObject, videoDecoderOut); + EXPECT_EQ(VIDEO_DECODEROUT_MIME, videoDecoderOut.mime); + EXPECT_TRUE(videoDecoderOut.pixel_fmt.empty()); +} + +/** + * @tc.name: histreamer_ability_querier_test_023 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoDecoder &videoDecoder) function. + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityQuerierTest, histreamer_ability_querier_test_023, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoDecoder videoDecoder; + jsonObject[NAME] = UINT16_ONE; + FromJson(jsonObject, videoDecoder); + EXPECT_TRUE(videoDecoder.name.empty()); + + jsonObject[NAME] = VIDEO_DECODER_NAME; + FromJson(jsonObject, videoDecoder); + EXPECT_EQ(VIDEO_DECODER_NAME, videoDecoder.name); + EXPECT_TRUE(videoDecoder.ins.empty()); + + VideoDecoderIn videoDecoderIn; + videoDecoderIn.mime = VIDEO_DECODERIN_MIME; + videoDecoderIn.vd_bit_stream_fmt = { + VideoBitStreamFormat::AVC1, + VideoBitStreamFormat::HEVC, + }; + videoDecoder.ins.push_back(videoDecoderIn); + FromJson(jsonObject, videoDecoder); + EXPECT_FALSE(videoDecoder.ins.empty()); + EXPECT_TRUE(videoDecoder.outs.empty()); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/common/include/av_sync_utils.h b/av_transport/common/include/av_sync_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..62a7033e15da586b9575b3e67784cf56b561dd6d --- /dev/null +++ b/av_transport/common/include/av_sync_utils.h @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_SHARED_MEMORY_H +#define OHOS_AV_TRANSPORT_SHARED_MEMORY_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +constexpr uint8_t INVALID_VALUE_FALG = 0; +constexpr uint32_t MAX_CLOCK_UNIT_COUNT = 50; +constexpr uint32_t DEFAULT_INVALID_FRAME_NUM = 0; + +struct AVTransSharedMemory { + int32_t fd; + int32_t size; + std::string name; +}; + +struct AVSyncClockUnit { + uint32_t index; + uint32_t frameNum; + int64_t pts; +}; + +/** + * @brief create shared memory space for av sync. + * @param name name for the shared memory. + * @return shared memory struct, include fd, size and name. + */ +AVTransSharedMemory CreateAVTransSharedMemory(const std::string &name, size_t size); + +/** + * @brief close shared memory space. + * @param memory shared memory. + */ +void CloseAVTransSharedMemory(const AVTransSharedMemory &memory) noexcept; + +/** + * @brief write the clock unit into the shared memory space. + * @param memory shared memory + * @param clockUnit the clock unit + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ +int32_t WriteClockUnitToMemory(const AVTransSharedMemory &memory, AVSyncClockUnit &clockUnit); + +/** + * @brief read clock unit from the shared memory space. + * @param memory shared memory + * @param clockUnit the clock unit + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ +int32_t ReadClockUnitFromMemory(const AVTransSharedMemory &memory, AVSyncClockUnit &clockUnit); + +/** + * @brief write frame number and pts into the shared memory space. + * @param memory shared memory + * @param frameNum the frame number + * @param timestamp the pts + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ +int32_t WriteFrameInfoToMemory(const AVTransSharedMemory &memory, uint32_t frameNum, int64_t timestamp); + +/** + * @brief read frame number and pts from the shared memory space. + * @param memory shared memory + * @param frameNum the frame number + * @param timestamp the pts + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ +int32_t ReadFrameInfoFromMemory(const AVTransSharedMemory &memory, uint32_t &frameNum, int64_t ×tamp); + +/** + * @brief reset the shared memory value to all zeros. + * @param memory shared memory + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ +int32_t ResetSharedMemory(const AVTransSharedMemory &memory); + +bool IsInValidSharedMemory(const AVTransSharedMemory &memory); +bool IsInValidClockUnit(const AVSyncClockUnit &clockUnit); + +std::string MarshalSharedMemory(const AVTransSharedMemory &memory); +AVTransSharedMemory UnmarshalSharedMemory(const std::string &jsonStr); + +uint32_t U8ToU32(const uint8_t *ptr); +uint64_t U8ToU64(const uint8_t *ptr); +void U32ToU8(uint8_t *ptr, uint32_t value); +void U64ToU8(uint8_t *ptr, uint64_t value); +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_SHARED_MEMORY_H \ No newline at end of file diff --git a/av_transport/common/include/av_trans_buffer.h b/av_transport/common/include/av_trans_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..71701c62c9c3a9b72ebded2616d691f1a0db6371 --- /dev/null +++ b/av_transport/common/include/av_trans_buffer.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_BUFFER_H +#define OHOS_AV_TRANSPORT_BUFFER_H + +#include +#include +#include + +#include "av_trans_types.h" + +namespace OHOS { +namespace DistributedHardware { +constexpr size_t INVALID_POSITION = -1; + +enum struct MetaType : uint32_t { + AUDIO, + VIDEO, +}; + +/** +* @brief BufferData description. Only manager the basic memory information. +*/ +class BufferData { +public: + explicit BufferData(size_t capacity); + BufferData(size_t capacity, std::shared_ptr bufData); + virtual ~BufferData() = default; + + size_t GetSize(); + size_t GetCapacity(); + uint8_t *GetAddress() const; + size_t Write(const uint8_t* in, size_t writeSize, size_t position = INVALID_POSITION); + size_t Read(uint8_t* out, size_t readSize, size_t position = INVALID_POSITION); + void Reset(); + void SetSize(size_t size); + +private: + size_t capacity_; + size_t size_; + std::shared_ptr address_; +}; + +/** + * @brief BufferMeta for buffer. Base class that describes various metadata. + */ +class BufferMeta { +public: + explicit BufferMeta(MetaType type); + virtual ~BufferMeta() = default; + + MetaType GetMetaType() const; + bool GetMetaItem(AVTransTag tag, std::string &value); + void SetMetaItem(AVTransTag tag, const std::string &value); + +private: + MetaType type_; + std::map tagMap_; +}; + +/** +* @brief AVTransBuffer base class. +* Contains the data storage and metadata information of the buffer (buffer description information). +*/ +class AVTransBuffer { +public: + explicit AVTransBuffer(MetaType type = MetaType::VIDEO); + ~AVTransBuffer() = default; + + std::shared_ptr GetBufferData(uint32_t index = 0); + std::shared_ptr CreateBufferData(size_t capacity); + std::shared_ptr WrapBufferData(const uint8_t* data, size_t capacity, size_t size); + std::shared_ptr GetBufferMeta(); + void UpdateBufferMeta(std::shared_ptr bufferMeta); + uint32_t GetDataCount(); + void Reset(); + bool IsEmpty(); + +private: + std::vector> data_ {}; + std::shared_ptr meta_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_BUFFER_H \ No newline at end of file diff --git a/av_transport/common/include/av_trans_constants.h b/av_transport/common/include/av_trans_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..05f04074c0ebbda56f1c18c623aed999b74a4864 --- /dev/null +++ b/av_transport/common/include/av_trans_constants.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_CONSTANTS_H +#define OHOS_AV_TRANSPORT_CONSTANTS_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +const int32_t AV_LOG_MAX_LEN = 4096; +const int32_t LINK_TYPE_MAX = 4; +const int32_t BASE_ENGINE_ID = 1000; +const int32_t DEVICE_ID_LENGTH = 65; +const int32_t INVALID_ENGINE_ID = -1; +const int32_t INVALID_SESSION_ID = -1; +const int32_t SESSION_WAIT_SECONDS = 5; +const int32_t INTERCERT_STRING_LENGTH = 20; +const int32_t PLUGIN_RANK = 100; +const int32_t PLUGIN_TASK_WAIT_TIME = 20; + +const uint32_t VIDEO_H264_LEVEL = 32; +const uint32_t MAX_DEVICE_ID_LEN = 100; +const uint32_t MAX_SESSION_NAME_LEN = 100; +const uint32_t MAX_MESSAGES_LEN = 40 * 1024 * 1024; +const uint32_t DSOFTBUS_INPUT_MAX_RECV_EXT_LEN = 104857600; +const uint32_t DSOFTBUS_INPUT_MAX_RECV_DATA_LEN = 104857600; +const uint32_t DEFAULT_FRAME_NUMBER = 100; +const uint32_t AUDIO_CHANNEL_LAYOUT_MONO = 1; +const uint32_t AUDIO_CHANNEL_LAYOUT_STEREO = 2; + +const int64_t DEFAULT_PTS = 100; + +const std::string EMPTY_STRING = ""; +const std::string SENDER_CONTROL_SESSION_NAME_SUFFIX = "sender.avtrans.control"; +const std::string RECEIVER_CONTROL_SESSION_NAME_SUFFIX = "receiver.avtrans.control"; +const std::string SENDER_DATA_SESSION_NAME_SUFFIX = "sender.avtrans.data"; +const std::string RECEIVER_DATA_SESSION_NAME_SUFFIX = "receiver.avtrans.data"; +const std::string AV_SYNC_SENDER_CONTROL_SESSION_NAME = "ohos.dhardware.av.sync.sender.control"; +const std::string AV_SYNC_RECEIVER_CONTROL_SESSION_NAME = "ohos.dhardware.av.sync.receiver.control"; + +const std::string AVINPUT_NAME = "builtin.avtransport.avinput"; +const std::string AVOUTPUT_NAME = "builtin.avtransport.avoutput"; +const std::string AENCODER_NAME = "builtin.recorder.audioencoder"; +const std::string VENCODER_NAME = "builtin.recorder.videoencoder"; +const std::string ADECODER_NAME = "builtin.player.audiodecoder"; +const std::string VDECODER_NAME = "builtin.player.videodecoder"; + +const std::string AVT_DATA_META_TYPE = "avtrans_data_meta_type"; +const std::string AVT_DATA_PARAM = "avtrans_data_param"; +const std::string AV_TRANS_SPECIAL_DEVICE_ID = "av.trans.special.device.id"; + +const std::string KEY_MY_DEV_ID = "myDevId"; +const std::string KEY_SCENE_TYPE = "sceneType"; +const std::string KEY_PEER_DEV_ID = "peerDevId"; +const std::string KEY_SESSION_ID = "sessionId"; +const std::string KEY_SESSION_NAME = "sessionName"; +const std::string KEY_AV_SYNC_FLAG = "avSyncFlag"; +const std::string KEY_START_FRAME_NUM = "startFrameNum"; +const std::string KEY_GROUP_INFO_ARRAY = "groupInfoArray"; +const std::string KEY_SHARED_MEM_FD = "sharedMemoryFd"; +const std::string KEY_SHARED_MEM_SIZE = "sharedMemorySize"; +const std::string KEY_SHARED_MEM_NAME = "sharedMemoryName"; + +const uint8_t DATA_WAIT_SECONDS = 1; +const size_t DATA_QUEUE_MAX_SIZE = 1000; +constexpr const char *SEND_CHANNEL_EVENT = "SendChannelEvent"; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_CONSTANTS_H \ No newline at end of file diff --git a/av_transport/common/include/av_trans_errno.h b/av_transport/common/include/av_trans_errno.h new file mode 100644 index 0000000000000000000000000000000000000000..45cf5b104207b1c32afefeb4299e0319145075f6 --- /dev/null +++ b/av_transport/common/include/av_trans_errno.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_ERRNO_H +#define OHOS_AV_TRANSPORT_ERRNO_H + +#include + +namespace OHOS { +namespace DistributedHardware { + /* + * The av transport module define errno, range: [-80000; -89999] + * Here's external errno, range: [-80000; -80199] + */ + constexpr int32_t DH_AVT_SUCCESS = 0; + constexpr int32_t ERR_DH_AVT_INVALID_PARAM = -80001; + constexpr int32_t ERR_DH_AVT_INIT_FAILED = -80002; + constexpr int32_t ERR_DH_AVT_START_FAILED = -80003; + constexpr int32_t ERR_DH_AVT_STOP_FAILED = -80004; + constexpr int32_t ERR_DH_AVT_RELEASE_FAILED = -80005; + constexpr int32_t ERR_DH_AVT_SETUP_FAILED = -80006; + constexpr int32_t ERR_DH_AVT_PUSH_DATA_FAILED = -80007; + constexpr int32_t ERR_DH_AVT_PULL_DATA_FAILED = -80008; + constexpr int32_t ERR_DH_AVT_SEND_MESSAGE_FAILED = -80009; + constexpr int32_t ERR_DH_AVT_CREATE_CHANNEL_FAILED = -80010; + constexpr int32_t ERR_DH_AVT_CHANNEL_ALREADY_CREATED = -80011; + constexpr int32_t ERR_DH_AVT_UNIMPLEMENTED = -80012; + constexpr int32_t ERR_DH_AVT_COMMON_FAILED = -80013; + constexpr int32_t ERR_DH_AVT_PAUSE_FAILED = -80014; + constexpr int32_t ERR_DH_AVT_RESUME_FAILED = -80015; + + /* Here's internal errno, range: [-81000; -89999] */ + constexpr int32_t ERR_DH_AVT_INVALID_PARAM_VALUE = -81000; + constexpr int32_t ERR_DH_AVT_INVALID_PARAM_TYPE = -81001; + constexpr int32_t ERR_DH_AVT_INVALID_OPERATION = -81002; + constexpr int32_t ERR_DH_AVT_UNSUPPORTED_FORMAT = -81003; + constexpr int32_t ERR_DH_AVT_NOT_EXISTED = -81004; + constexpr int32_t ERR_DH_AVT_TIMED_OUT = -81005; + constexpr int32_t ERR_DH_AVT_NO_MEMORY = -81006; + constexpr int32_t ERR_DH_AVT_INVALID_STATE = -81007; + constexpr int32_t ERR_DH_AVT_PERMISSION_DENIED = -81008; + constexpr int32_t ERR_DH_AVT_NO_NOTIFY = -81009; + constexpr int32_t ERR_DH_AVT_NULL_POINTER = -81010; + constexpr int32_t ERR_DH_AVT_SESSION_ERROR = -81011; + constexpr int32_t ERR_DH_AVT_SEND_DATA_FAILED = -81012; + constexpr int32_t ERR_DH_AVT_PREPARE_FAILED = -81013; + constexpr int32_t ERR_DH_AVT_SET_PARAM_FAILED = -81014; + constexpr int32_t ERR_DH_AVT_OUTPUT_DATA_FAILED = -80015; + constexpr int32_t ERR_DH_AVT_TIME_SYNC_FAILED = -80016; + constexpr int32_t ERR_DH_AVT_SERVICE_REMOTE_IS_NULL = -80017; + constexpr int32_t ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL = -80018; + constexpr int32_t ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL = -80019; + constexpr int32_t ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL = -80019; + constexpr int32_t ERR_DH_AVT_CTRL_CENTER_INIT_FAIL = -80020; + constexpr int32_t ERR_DH_AVT_REGISTER_CALLBACK_FAIL = -80021; + constexpr int32_t ERR_DH_AVT_FWK_INNER_KIT_NULL = -80022; + constexpr int32_t ERR_DH_AVT_SHARED_MEMORY_FAILED = -80023; + constexpr int32_t ERR_DH_AVT_MASTER_NOT_READY = -80024; + constexpr int32_t ERR_DH_AVT_SESSION_HAS_OPENED = -80025; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_ERRNO_H \ No newline at end of file diff --git a/av_transport/common/include/av_trans_log.h b/av_transport/common/include/av_trans_log.h new file mode 100644 index 0000000000000000000000000000000000000000..441ccdd3dd7d5039b18951811f8a9d936f06eab3 --- /dev/null +++ b/av_transport/common/include/av_trans_log.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_LOG_H +#define OHOS_AV_TRANSPORT_LOG_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DH_LOG_DEBUG, + DH_LOG_INFO, + DH_LOG_WARN, + DH_LOG_ERROR, +} DHLogLevel; + +void AVTransLog(DHLogLevel logLevel, const char *fmt, ...); + +#define AVTRANS_LOGD(fmt, ...) AVTransLog(DH_LOG_DEBUG, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define AVTRANS_LOGI(fmt, ...) AVTransLog(DH_LOG_INFO, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define AVTRANS_LOGW(fmt, ...) AVTransLog(DH_LOG_WARN, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define AVTRANS_LOGE(fmt, ...) AVTransLog(DH_LOG_ERROR, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +std::string GetAnonyString(const std::string &value); +std::string GetAnonyInt32(const int32_t value); + +#ifndef TRUE_RETURN +#define TRUE_RETURN(exec, fmt, args...) \ + do { \ + bool retCode = (exec); \ + if (retCode) { \ + AVTRANS_LOGE(fmt, ##args); \ + return; \ + } \ + } while (0) +#endif + +#ifndef TRUE_RETURN_V +#define TRUE_RETURN_V(exec, ret) \ + do { \ + bool retCode = (exec); \ + if (retCode) { \ + return ret; \ + } \ + } while (0) +#endif + +#ifndef TRUE_RETURN_V_MSG_E +#define TRUE_RETURN_V_MSG_E(exec, ret, fmt, args...) \ + do { \ + bool retCode = (exec); \ + if (retCode) { \ + AVTRANS_LOGE(fmt, ##args); \ + return ret; \ + } \ + } while (0) +#endif + +#ifndef TRUE_RETURN_V_MSG_D +#define TRUE_RETURN_V_MSG_D(exec, ret, fmt, args...) \ + do { \ + bool retCode = (exec); \ + if (retCode) { \ + AVTRANS_LOGD(fmt, ##args); \ + return ret; \ + } \ + } while (0) +#endif + +#ifndef TRUE_LOG_MSG +#define TRUE_LOG_MSG(exec, fmt, args...) \ + do { \ + bool retCode = (exec); \ + if (retCode) { \ + AVTRANS_LOGE(fmt, ##args); \ + } \ + } while (0) +#endif +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_LOG_H \ No newline at end of file diff --git a/av_transport/common/include/av_trans_message.h b/av_transport/common/include/av_trans_message.h new file mode 100644 index 0000000000000000000000000000000000000000..05005a17c129056804c5452a0bf472174fa6c4fa --- /dev/null +++ b/av_transport/common/include/av_trans_message.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_MESSAGE_H +#define OHOS_AV_TRANSPORT_MESSAGE_H + +#include +#include +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +class AVTransMessage { +public: + AVTransMessage(); + AVTransMessage(uint32_t type, std::string content, std::string dstDevId); + ~AVTransMessage(); + + std::string MarshalMessage(); + bool UnmarshalMessage(const std::string &jsonStr, const std::string &peerDevId); + +private: + bool IsUInt32(const nlohmann::json &msgJson, const std::string &key); + bool IsString(const nlohmann::json &msgJson, const std::string &key); + +public: + uint32_t type_; + std::string content_; + std::string dstDevId_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_MESSAGE_H \ No newline at end of file diff --git a/av_transport/common/include/av_trans_meta.h b/av_transport/common/include/av_trans_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..92e4f8dc1f90114968d7f1f75b6806270796172d --- /dev/null +++ b/av_transport/common/include/av_trans_meta.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_EXTEND_META_H +#define OHOS_AV_TRANSPORT_EXTEND_META_H + +#include "av_trans_types.h" + +// follwing head files depends on histreamer +#include "plugin_buffer.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; + +/** + * @brief av transport audio buffer metadata. + * Buffer metadata describing how data is laid out inside the buffer + */ +class AVTransAudioBufferMeta : public OHOS::Media::Plugin::BufferMeta { +public: + AVTransAudioBufferMeta() : OHOS::Media::Plugin::BufferMeta(BufferMetaType::AUDIO) {} + ~AVTransAudioBufferMeta() override = default; + + std::shared_ptr Clone() override; + + std::string MarshalAudioMeta(); + bool UnmarshalAudioMeta(const std::string &jsonStr); + +public: + int64_t pts_ {0}; + + int64_t cts_ {0}; + + uint32_t frameNum_ {0}; + + uint32_t channels_ {0}; + + uint32_t sampleRate_ {0}; + + BufferDataType dataType_ {BufferDataType::AUDIO}; + + AudioSampleFormat format_ {AudioSampleFormat::S8}; + +private: + friend class Buffer; +}; + +/** + * @brief av transport video buffer metadata. + * Extra buffer metadata describing video properties. + */ +class AVTransVideoBufferMeta : public OHOS::Media::Plugin::BufferMeta { +public: + AVTransVideoBufferMeta() : OHOS::Media::Plugin::BufferMeta(BufferMetaType::VIDEO) {} + ~AVTransVideoBufferMeta() override = default; + + std::shared_ptr Clone() override; + + std::string MarshalVideoMeta(); + bool UnmarshalVideoMeta(const std::string &jsonStr); + + int64_t pts_ {0}; + + int64_t cts_ {0}; + + uint32_t width_ {0}; + + uint32_t height_ {0}; + + uint32_t frameNum_ {0}; + + int64_t extPts_ {0}; + + uint32_t extFrameNum_ {0}; + + VideoPixelFormat format_ {VideoPixelFormat::UNKNOWN}; + + BufferDataType dataType_ {BufferDataType::VIDEO_STREAM}; + +private: + friend class Buffer; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_EXTEND_META_H \ No newline at end of file diff --git a/av_transport/common/include/av_trans_types.h b/av_transport/common/include/av_trans_types.h new file mode 100644 index 0000000000000000000000000000000000000000..58dc8c6805b92416951e14591ffc36b87ea2b5ff --- /dev/null +++ b/av_transport/common/include/av_trans_types.h @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_TYPES_H +#define OHOS_AV_TRANSPORT_TYPES_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +const std::string OWNER_NAME_D_CAMERA = "ohos.dhardware.dcamera"; +const std::string OWNER_NAME_D_SCREEN = "ohos.dhardware.dscreen"; +const std::string OWNER_NAME_D_MIC = "ohos.dhardware.daudio.dmic"; +const std::string OWNER_NAME_D_SPEAKER = "ohos.dhardware.daudio.dspeaker"; + +const std::string SCENE_TYPE_D_MIC = "dmic_stream"; +const std::string SCENE_TYPE_D_SCREEN = "dscreen_stream"; +const std::string SCENE_TYPE_D_SPEAKER = "dspeaker_stream"; +const std::string SCENE_TYPE_D_CAMERA_STR = "dcamera_stream"; +const std::string SCENE_TYPE_D_CAMERA_PIC = "dcamera_picture"; + +const std::string PKG_NAME_DH_FWK = "ohos.dhardware"; +const std::string PKG_NAME_D_AUDIO = "ohos.dhardware.daudio"; +const std::string PKG_NAME_D_CAMERA = "ohos.dhardware.dcamera"; +const std::string PKG_NAME_D_SCREEN = "ohos.dhardware.dscreen"; + +const std::string MIME_VIDEO_RAW = "video/raw"; +const std::string MIME_VIDEO_H264 = "video/avc"; +const std::string MIME_VIDEO_H265 = "video/hevc"; + +const std::string VIDEO_FORMAT_NV12 = "nv12"; +const std::string VIDEO_FORMAT_NV21 = "nv21"; +const std::string VIDEO_FORMAT_JEPG = "jpeg"; +const std::string VIDEO_FORMAT_YUVI420 = "yuvi420"; +const std::string VIDEO_FORMAT_RGBA8888 = "rgba8888"; + +enum struct TransRole : uint32_t { + AV_SENDER = 0, + AV_RECEIVER = 1, + UNKNOWN = 2 +}; + +enum struct AvSyncFlag : uint32_t { + MASTER = 0, + SLAVE = 1, + UNKNOWN = 2 +}; + +enum struct TransStrategy : uint32_t { + LOW_LATANCY_STRATEGY, + LOW_JITTER_STRATEGY +}; + +struct ChannelAttribute { + TransStrategy strategy; +}; + +enum struct BufferDataType : uint32_t { + AUDIO = 0, + VIDEO_STREAM, + PICTURE, + UNKNOW, +}; + +enum struct StateId : uint32_t { + IDLE = 0, + INITIALIZED = 1, + CH_CREATING = 2, + CH_CREATED = 3, + STARTED = 4, + PLAYING = 5, + STOPPED = 6, + BUTT, +}; + +enum struct TagSection : uint8_t { + REGULAR = 1, + D_AUDIO = 2, + D_VIDEO = 3, + MAX_SECTION = 64 +}; + +enum struct AVTransTag : uint32_t { + INVALID = 0, + SECTION_REGULAR_START = static_cast(TagSection::REGULAR) << 16U, + SECTION_D_AUDIO_START = static_cast(TagSection::D_AUDIO) << 16U, + SECTION_D_VIDEO_START = static_cast(TagSection::D_VIDEO) << 16U, + + /* -------------------- regular tag -------------------- */ + FRAME_NUMBER = SECTION_REGULAR_START + 1, + BUFFER_DATA_TYPE, + PRE_TIMESTAMP, + CUR_TIMESTAMP, + ENGINE_READY, + ENGINE_PAUSE, + ENGINE_RESUME, + START_AV_SYNC, + STOP_AV_SYNC, + TIME_SYNC_RESULT, + SHARED_MEMORY_FD, + + /* -------------------- d_audio tag -------------------- */ + AUDIO_CHANNELS = SECTION_D_AUDIO_START + 1, + AUDIO_SAMPLE_RATE, + AUDIO_CODEC_TYPE, + AUDIO_CHANNEL_MASK, + AUDIO_SAMPLE_FORMAT, + AUDIO_FRAME_SIZE, + AUDIO_STREAM_USAGE, + AUDIO_RENDER_FLAGS, + AUDIO_CONTENT_TYPE, + AUDIO_CHANNEL_LAYOUT, + AUDIO_BIT_RATE, + + /* -------------------- d_video tag -------------------- */ + VIDEO_WIDTH = SECTION_D_VIDEO_START + 1, + VIDEO_HEIGHT, + VIDEO_CODEC_TYPE, + VIDEO_PIXEL_FORMAT, + VIDEO_FRAME_RATE, + VIDEO_BIT_RATE, +}; + +enum struct EventType : uint32_t { + EVENT_CHANNEL_OPENED = 0, + EVENT_CHANNEL_OPEN_FAIL = 1, + EVENT_CHANNEL_CLOSED = 2, + EVENT_START_SUCCESS = 3, + EVENT_START_FAIL = 4, + EVENT_STOP_SUCCESS = 5, + EVENT_STOP_FAIL = 6, + EVENT_ENGINE_ERROR = 7, + EVENT_REMOTE_ERROR = 8, + EVENT_DATA_RECEIVED = 9, + EVENT_TIME_SYNC_RESULT = 10, + EVENT_ADD_STREAM = 11, + EVENT_REMOVE_STREAM = 12, +}; + +struct AVTransEvent { + EventType type; + std::string content; + std::string peerDevId; +}; + +struct AVStreamInfo { + std::string sceneType; + std::string peerDevId; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_TYPES_H \ No newline at end of file diff --git a/av_transport/common/include/av_trans_utils.h b/av_transport/common/include/av_trans_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0ca6694ac73095e708b75d94140fe35f2f70951f --- /dev/null +++ b/av_transport/common/include/av_trans_utils.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_UTILS_H +#define OHOS_AV_TRANSPORT_UTILS_H + +#include +#include +#include +#include + +#include "av_trans_buffer.h" +#include "av_trans_types.h" +#include "nlohmann/json.hpp" + +// follwing head files depends on histreamer +#include "event.h" +#include "plugin_event.h" +#include "plugin_buffer.h" +#include "plugin_source_tags.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Media; +using namespace OHOS::Media::Plugin; +using AVBuffer = OHOS::Media::Plugin::Buffer; +const int64_t NS_ONE_US = 1000; +const int64_t NS_ONE_MS = 1000000; +const int64_t NS_ONE_S = 1000000000; +std::string TransName2PkgName(const std::string &ownerName); +MediaType TransName2MediaType(const std::string &ownerName); + +std::shared_ptr TransBuffer2HiSBuffer(const std::shared_ptr &transBuffer); +std::shared_ptr HiSBuffer2TransBuffer(const std::shared_ptr &hisBuffer); +void Convert2HiSBufferMeta(std::shared_ptr transBuffer, std::shared_ptr hisBuffer); +void Convert2TransBufferMeta(std::shared_ptr hisBuffer, std::shared_ptr transBuffer); + +std::string BuildChannelDescription(const std::string &ownerName, const std::string &peerDevId); +void ParseChannelDescription(const std::string &descJsonStr, std::string &ownerName, std::string &peerDevId); + +EventType CastEventType(Plugin::PluginEventType type, bool isAbnormal); +void DumpBufferToFile(std::string fileName, uint8_t *buffer, int32_t bufSize); + +bool IsUInt32(const nlohmann::json &jsonObj, const std::string &key); +bool IsInt64(const nlohmann::json &jsonObj, const std::string &key); +bool IsString(const nlohmann::json &jsonObj, const std::string &key); + +int64_t GetCurrentTime(); + +void GenerateAdtsHeader(unsigned char* adtsHeader, uint32_t packetLen, uint32_t profile, uint32_t sampleRate, + uint32_t channels); + +template +inline std::shared_ptr ReinterpretCastPointer(const std::shared_ptr &ptr) noexcept +{ + return std::shared_ptr(ptr, reinterpret_cast(ptr.get())); +} +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_UTILS_H \ No newline at end of file diff --git a/av_transport/common/include/single_instance.h b/av_transport/common/include/single_instance.h new file mode 100644 index 0000000000000000000000000000000000000000..5529167c4f0d506090185008e7f1de1b09444739 --- /dev/null +++ b/av_transport/common/include/single_instance.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AV_TRANSPORT_SINGLE_INSTANCE_H +#define OHOS_AV_TRANSPORT_SINGLE_INSTANCE_H + +namespace OHOS { +namespace DistributedHardware { +#define REMOVE_NO_USE_CONSTRUCTOR(className) \ +private: \ + className(const className&) = delete; \ + className& operator= (const className&) = delete; \ + className(className&&) = delete; \ + className& operator= (className&&) = delete; \ + +#define DECLARE_SINGLE_INSTANCE_BASE(className) \ +public: \ + static className & GetInstance(); \ +private: \ + className(const className&) = delete; \ + className& operator= (const className&) = delete; \ + className(className&&) = delete; \ + className& operator= (className&&) = delete; \ + +#define DECLARE_SINGLE_INSTANCE(className) \ + DECLARE_SINGLE_INSTANCE_BASE(className) \ +private: \ + className() = default; \ + virtual ~className() = default; \ + +#define IMPLEMENT_SINGLE_INSTANCE(className) \ +className & className::GetInstance() \ +{ \ + static className instance; \ + return instance; \ +} +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_AV_TRANSPORT_SINGLE_INSTANCE_H diff --git a/av_transport/common/include/softbus_channel_adapter.h b/av_transport/common/include/softbus_channel_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..4e2a407e805ca4fc658b410a0fbba10c819e5d62 --- /dev/null +++ b/av_transport/common/include/softbus_channel_adapter.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_SOFTBUS_CHANNEL_ADAPTER +#define OHOS_SOFTBUS_CHANNEL_ADAPTER + +#include +#include +#include + +#include "av_trans_types.h" +#include "session.h" +#include "single_instance.h" +#include "softbus_bus_center.h" +#include "softbus_common.h" + +namespace OHOS { +namespace DistributedHardware { +class ISoftbusChannelListener { +public: + virtual ~ISoftbusChannelListener() = default; + virtual void OnChannelEvent(const AVTransEvent &event) = 0; + virtual void OnStreamReceived(const StreamData *data, const StreamData *ext) = 0; +}; + +class SoftbusChannelAdapter { + DECLARE_SINGLE_INSTANCE_BASE(SoftbusChannelAdapter); +public: + int32_t CreateChannelServer(const std::string &pkgName, const std::string &sessName); + int32_t RemoveChannelServer(const std::string &pkgName, const std::string &sessName); + + int32_t OpenSoftbusChannel(const std::string &mySessName, const std::string &peerSessName, + const std::string &peerDevId); + int32_t CloseSoftbusChannel(const std::string &mySessName, const std::string &peerDevId); + + int32_t SendBytesData(const std::string &sessName, const std::string &peerDevId, const std::string &data); + int32_t SendStreamData(const std::string &sessName, const std::string &peerDevId, const StreamData *data, + const StreamData *ext); + + int32_t RegisterChannelListener(const std::string &sessName, const std::string &peerDevId, + ISoftbusChannelListener *listener); + int32_t UnRegisterChannelListener(const std::string &sessName, const std::string &peerDevId); + + int32_t StartDeviceTimeSync(const std::string &pkgName, const std::string &sessName, + const std::string &peerDevId); + int32_t StopDeviceTimeSync(const std::string &pkgName, const std::string &sessName, + const std::string &peerDevId); + + void SendChannelEvent(ISoftbusChannelListener *listener, const AVTransEvent &event); + + int32_t OnSoftbusChannelOpened(int32_t sessionId, int32_t result); + void OnSoftbusChannelClosed(int32_t sessionId); + void OnSoftbusBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + void OnSoftbusTimeSyncResult(const TimeSyncResultInfo *info, int32_t result); + void OnSoftbusStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *frameInfo); + +private: + SoftbusChannelAdapter(); + ~SoftbusChannelAdapter(); + + std::string GetSessionNameById(int32_t sessionId); + int32_t GetSessIdBySessName(const std::string &sessName, const std::string &peerDevId); + std::string GetPeerDevIdBySessId(int32_t sessionId); + std::string GetOwnerFromSessName(const std::string &sessName); + +private: + std::mutex name2IdMtx_; + std::mutex timeSyncMtx_; + std::mutex idMapMutex_; + std::mutex listenerMtx_; + + ISessionListener sessListener_; + std::set sessionNameSet_; + std::set timeSyncSessNames_; + std::map devId2SessIdMap_; + std::map listenerMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_SOFTBUS_CHANNEL_ADAPTER diff --git a/av_transport/common/src/av_sync_utils.cpp b/av_transport/common/src/av_sync_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79915ed2dd7075d33a31fefef0c6abf592f6ea2a --- /dev/null +++ b/av_transport/common/src/av_sync_utils.cpp @@ -0,0 +1,335 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_sync_utils.h" + +#include +#include +#include +#include "ashmem.h" +#include "nlohmann/json.hpp" + +#include "av_trans_constants.h" +#include "av_trans_errno.h" +#include "av_trans_log.h" + +namespace OHOS { +namespace DistributedHardware { +AVTransSharedMemory CreateAVTransSharedMemory(const std::string &name, size_t size) +{ + int32_t fd = AshmemCreate(name.c_str(), size); + if (fd <= 0) { + AVTRANS_LOGE("create av trans shared memory failed, name=%s, fd=%" PRId32, name.c_str(), fd); + return AVTransSharedMemory{0, 0, name}; + } + + unsigned int prot = PROT_READ | PROT_WRITE; + int result = AshmemSetProt(fd, static_cast(prot)); + if (result < 0) { + AVTRANS_LOGE("AshmemSetProt failed, name=%s, fd=%" PRId32, name.c_str(), fd); + (void)::close(fd); + return AVTransSharedMemory{0, 0, name}; + } + + void *addr = ::mmap(nullptr, size, static_cast(prot), MAP_SHARED, fd, 0); + if (addr == MAP_FAILED) { + AVTRANS_LOGE("shared memory mmap failed, name=%s, fd=%" PRId32, name.c_str(), fd); + (void)::close(fd); + return AVTransSharedMemory{0, 0, name}; + } + + uint8_t *base = reinterpret_cast(addr); + (void)memset_s(base, size, INVALID_VALUE_FALG, size); + + AVTRANS_LOGI("create av trans shared memory success, name=%s, size=%" PRId32 ", fd=%" PRId32, + name.c_str(), size, fd); + return AVTransSharedMemory{fd, size, name}; +} + +void CloseAVTransSharedMemory(const AVTransSharedMemory &memory) noexcept +{ + AVTRANS_LOGI("close shared memory, name=%s, size=%" PRId32 ", fd=%" PRId32, memory.name.c_str(), + memory.size, memory.fd); + if (IsInValidSharedMemory(memory)) { + AVTRANS_LOGE("invalid input shared memory"); + return; + } + if (memory.fd > 0) { + (void)::close(memory.fd); + } +} + +int32_t WriteClockUnitToMemory(const AVTransSharedMemory &memory, AVSyncClockUnit &clockUnit) +{ + AVTRANS_LOGI("write clock unit to shared memory, name=%s, size=%" PRId32 ", fd=%" PRId32, + memory.name.c_str(), memory.size, memory.fd); + TRUE_RETURN_V_MSG_E(IsInValidSharedMemory(memory), ERR_DH_AVT_INVALID_PARAM, "invalid input shared memory"); + + AVTRANS_LOGI("clock unit index=%" PRId32 ", frameNum=%" PRId32 ", pts=%lld", clockUnit.index, + clockUnit.frameNum, (long long)clockUnit.pts); + TRUE_RETURN_V_MSG_E(IsInValidClockUnit(clockUnit), ERR_DH_AVT_INVALID_PARAM, "invalid input clock unit"); + + int size = AshmemGetSize(memory.fd); + TRUE_RETURN_V_MSG_E(size != memory.size, ERR_DH_AVT_SHARED_MEMORY_FAILED, "invalid memory size = %" PRId32, size); + + unsigned int prot = PROT_WRITE; + int result = AshmemSetProt(memory.fd, static_cast(prot)); + TRUE_RETURN_V_MSG_E(result < 0, ERR_DH_AVT_SHARED_MEMORY_FAILED, "AshmemSetProt failed"); + + void *addr = ::mmap(nullptr, static_cast(memory.size), static_cast(prot), MAP_SHARED, memory.fd, 0); + if (addr == MAP_FAILED) { + free(addr); + addr = nullptr; + AVTRANS_LOGE("shared memory mmap failed, mmap address is invalid."); + return ERR_DH_AVT_SHARED_MEMORY_FAILED; + } + + uint8_t *base = reinterpret_cast(addr); + size_t fOffset = (sizeof(uint32_t) + sizeof(int64_t)) * clockUnit.index; + size_t tOffset = fOffset + sizeof(uint32_t); + U64ToU8(base + tOffset, clockUnit.pts); + U32ToU8(base + fOffset, clockUnit.frameNum); + + clockUnit.index ++; + if (clockUnit.index == MAX_CLOCK_UNIT_COUNT) { + clockUnit.index = 0; + } + + AVTRANS_LOGI("write clock unit frameNum=%" PRId32 ", pts=%lld to shared memory success", + clockUnit.frameNum, (long long)(clockUnit.pts)); + return DH_AVT_SUCCESS; +} + +int32_t ReadClockUnitFromMemory(const AVTransSharedMemory &memory, AVSyncClockUnit &clockUnit) +{ + AVTRANS_LOGI("read clock unit from shared memory, name=%s, size=%" PRId32 ", fd=%" PRId32, + memory.name.c_str(), memory.size, memory.fd); + TRUE_RETURN_V_MSG_E(IsInValidSharedMemory(memory), ERR_DH_AVT_INVALID_PARAM, "invalid input shared memory"); + + AVTRANS_LOGI("clock unit index=%" PRId32 ", frameNum=%" PRId32, clockUnit.index, clockUnit.frameNum); + TRUE_RETURN_V_MSG_E((clockUnit.frameNum <= 0), ERR_DH_AVT_INVALID_PARAM, "invalid input frame number"); + + int size = AshmemGetSize(memory.fd); + TRUE_RETURN_V_MSG_E(size != memory.size, ERR_DH_AVT_SHARED_MEMORY_FAILED, "invalid memory size = %" PRId32, size); + + unsigned int prot = PROT_WRITE; + int result = AshmemSetProt(memory.fd, static_cast(prot)); + TRUE_RETURN_V_MSG_E(result < 0, ERR_DH_AVT_SHARED_MEMORY_FAILED, "AshmemSetProt failed"); + + void *addr = ::mmap(nullptr, static_cast(memory.size), static_cast(prot), MAP_SHARED, memory.fd, 0); + if (addr == MAP_FAILED) { + free(addr); + addr = nullptr; + AVTRANS_LOGE("shared memory mmap failed, mmap address is invalid."); + return ERR_DH_AVT_SHARED_MEMORY_FAILED; + } + + uint8_t *base = reinterpret_cast(addr); + uint32_t firstUnit = U8ToU32(base); + TRUE_RETURN_V_MSG_E(firstUnit == 0, ERR_DH_AVT_MASTER_NOT_READY, "master queue not ready, clock is null."); + + uint32_t index = 0; + int64_t latestPts = 0; + size_t unitSize = sizeof(uint32_t) + sizeof(int64_t); + while (index < MAX_CLOCK_UNIT_COUNT) { + uint32_t frameNum = U8ToU32(base + (index * unitSize)); + int64_t pts = static_cast(U8ToU64(base + (index * unitSize) + sizeof(uint32_t))); + if (pts > latestPts) { + latestPts = pts; + clockUnit.pts = pts; + clockUnit.frameNum = frameNum; + } + index++; + } + AVTRANS_LOGI("read clock unit from shared memory success, frameNum=%" PRId32 ", pts=%lld", + clockUnit.frameNum, (long long)clockUnit.pts); + return DH_AVT_SUCCESS; +} + +int32_t WriteFrameInfoToMemory(const AVTransSharedMemory &memory, uint32_t frameNum, int64_t timestamp) +{ + AVTRANS_LOGI("write frame info to shared memory, name=%s, size=%" PRId32 ", fd=%" PRId32, + memory.name.c_str(), memory.size, memory.fd); + TRUE_RETURN_V_MSG_E(IsInValidSharedMemory(memory), ERR_DH_AVT_INVALID_PARAM, "invalid input shared memory"); + + TRUE_RETURN_V_MSG_E((frameNum <= 0), ERR_DH_AVT_INVALID_PARAM, "invalid input frame number"); + + int size = AshmemGetSize(memory.fd); + TRUE_RETURN_V_MSG_E(size != memory.size, ERR_DH_AVT_SHARED_MEMORY_FAILED, "invalid memory size = %" PRId32, size); + + unsigned int prot = PROT_WRITE; + int result = AshmemSetProt(memory.fd, static_cast(prot)); + TRUE_RETURN_V_MSG_E(result < 0, ERR_DH_AVT_SHARED_MEMORY_FAILED, "AshmemSetProt failed"); + + void *addr = ::mmap(nullptr, static_cast(memory.size), static_cast(prot), MAP_SHARED, memory.fd, 0); + if (addr == MAP_FAILED) { + free(addr); + addr = nullptr; + AVTRANS_LOGE("shared memory mmap failed, mmap address is invalid."); + return ERR_DH_AVT_SHARED_MEMORY_FAILED; + } + + uint8_t *base = reinterpret_cast(addr); + U32ToU8(base, frameNum); + U64ToU8(base + sizeof(uint32_t), timestamp); + + AVTRANS_LOGI("write frameNum=%" PRId32 ", timestamp=%lld to shared memory success", frameNum, (long long)timestamp); + return DH_AVT_SUCCESS; +} + +int32_t ReadFrameInfoFromMemory(const AVTransSharedMemory &memory, uint32_t &frameNum, int64_t ×tamp) +{ + AVTRANS_LOGI("read frame info from shared memory, name=%s, size=%" PRId32 ", fd=%" PRId32, + memory.name.c_str(), memory.size, memory.fd); + TRUE_RETURN_V_MSG_E(IsInValidSharedMemory(memory), ERR_DH_AVT_INVALID_PARAM, "invalid input shared memory"); + + int size = AshmemGetSize(memory.fd); + TRUE_RETURN_V_MSG_E(size != memory.size, ERR_DH_AVT_SHARED_MEMORY_FAILED, "invalid memory size = %" PRId32, size); + + unsigned int prot = PROT_WRITE; + int result = AshmemSetProt(memory.fd, static_cast(prot)); + TRUE_RETURN_V_MSG_E(result < 0, ERR_DH_AVT_SHARED_MEMORY_FAILED, "AshmemSetProt failed"); + + void *addr = ::mmap(nullptr, static_cast(memory.size), static_cast(prot), MAP_SHARED, memory.fd, 0); + if (addr == MAP_FAILED) { + free(addr); + addr = nullptr; + AVTRANS_LOGE("shared memory mmap failed, mmap address is invalid."); + return ERR_DH_AVT_SHARED_MEMORY_FAILED; + } + + uint8_t *base = reinterpret_cast(addr); + frameNum = U8ToU32(base); + timestamp = static_cast(U8ToU64(base + sizeof(uint32_t))); + TRUE_RETURN_V_MSG_E(frameNum <= 0, ERR_DH_AVT_MASTER_NOT_READY, "master queue not ready, frameNum is null."); + + AVTRANS_LOGI("read frameNum=%" PRId32 ", timestamp=%lld from shared memory success.", frameNum, + (long long)timestamp); + return DH_AVT_SUCCESS; +} + +int32_t ResetSharedMemory(const AVTransSharedMemory &memory) +{ + AVTRANS_LOGI("reset shared memory, name=%s, size=%" PRId32 ", fd=%" PRId32, memory.name.c_str(), + memory.size, memory.fd); + TRUE_RETURN_V_MSG_E(IsInValidSharedMemory(memory), ERR_DH_AVT_INVALID_PARAM, "invalid input shared memory"); + + int size = AshmemGetSize(memory.fd); + TRUE_RETURN_V_MSG_E(size != memory.size, ERR_DH_AVT_SHARED_MEMORY_FAILED, "invalid memory size = %" PRId32, size); + + unsigned int prot = PROT_WRITE; + int result = AshmemSetProt(memory.fd, static_cast(prot)); + TRUE_RETURN_V_MSG_E(result < 0, ERR_DH_AVT_SHARED_MEMORY_FAILED, "AshmemSetProt failed"); + + void *addr = ::mmap(nullptr, static_cast(memory.size), static_cast(prot), MAP_SHARED, memory.fd, 0); + if (addr == MAP_FAILED) { + free(addr); + addr = nullptr; + AVTRANS_LOGE("shared memory mmap failed, mmap address is invalid."); + return ERR_DH_AVT_SHARED_MEMORY_FAILED; + } + (void)memset_s(reinterpret_cast(addr), size, INVALID_VALUE_FALG, size); + + AVTRANS_LOGI("reset shared memory success."); + return DH_AVT_SUCCESS; +} + +bool IsInValidSharedMemory(const AVTransSharedMemory &memory) +{ + return (memory.fd <= 0) || (memory.size <= 0) || memory.name.empty(); +} + +bool IsInValidClockUnit(const AVSyncClockUnit &clockUnit) +{ + return (clockUnit.index < 0) || (clockUnit.index >= MAX_CLOCK_UNIT_COUNT) || (clockUnit.frameNum <= 0) + || (clockUnit.pts <= 0); +} + +std::string MarshalSharedMemory(const AVTransSharedMemory &memory) +{ + nlohmann::json memoryJson; + + memoryJson[KEY_SHARED_MEM_FD] = memory.fd; + memoryJson[KEY_SHARED_MEM_SIZE] = memory.size; + memoryJson[KEY_SHARED_MEM_NAME] = memory.name; + + return memoryJson.dump(); +} + +AVTransSharedMemory UnmarshalSharedMemory(const std::string &jsonStr) +{ + nlohmann::json paramJson = nlohmann::json::parse(jsonStr, nullptr, false); + if (paramJson.is_discarded()) { + return AVTransSharedMemory{0, 0, ""}; + } + + if (!paramJson.contains(KEY_SHARED_MEM_FD) || !paramJson.contains(KEY_SHARED_MEM_SIZE) || + !paramJson.contains(KEY_SHARED_MEM_NAME)) { + return AVTransSharedMemory{0, 0, ""}; + } + + if (!paramJson[KEY_SHARED_MEM_FD].is_number_integer() || !paramJson[KEY_SHARED_MEM_SIZE].is_number_integer() || + !paramJson[KEY_SHARED_MEM_NAME].is_string()) { + return AVTransSharedMemory{0, 0, ""}; + } + + int32_t fd = paramJson[KEY_SHARED_MEM_FD].get(); + int32_t size = paramJson[KEY_SHARED_MEM_SIZE].get(); + std::string name = paramJson[KEY_SHARED_MEM_NAME].get(); + + return AVTransSharedMemory{ fd, size, name }; +} + +void U32ToU8(uint8_t *ptr, uint32_t value) +{ + ptr[0] = (uint8_t)((value) & 0xff); + ptr[1] = (uint8_t)((value >> 8) & 0xff); + ptr[2] = (uint8_t)((value >> 16) & 0xff); + ptr[3] = (uint8_t)((value >> 24) & 0xff); +} + +void U64ToU8(uint8_t *ptr, uint64_t value) +{ + ptr[0] = (uint8_t)((value) & 0xff); + ptr[1] = (uint8_t)((value >> 8) & 0xff); + ptr[2] = (uint8_t)((value >> 16) & 0xff); + ptr[3] = (uint8_t)((value >> 24) & 0xff); + ptr[4] = (uint8_t)((value >> 32) & 0xff); + ptr[5] = (uint8_t)((value >> 40) & 0xff); + ptr[6] = (uint8_t)((value >> 48) & 0xff); + ptr[7] = (uint8_t)((value >> 56) & 0xff); +} + +uint32_t U8ToU32(const uint8_t *ptr) +{ + return (((uint32_t)(ptr[0] & 0xff)) | + ((uint32_t)(ptr[1] & 0xff) << 8) | + ((uint32_t)(ptr[2] & 0xff) << 16) | + ((uint32_t)(ptr[3] & 0xff) << 24)); +} + +uint64_t U8ToU64(const uint8_t *ptr) +{ + return (((uint64_t)(ptr[0] & 0xff)) | + ((uint64_t)(ptr[1] & 0xff) << 8) | + ((uint64_t)(ptr[2] & 0xff) << 16) | + ((uint64_t)(ptr[3] & 0xff) << 24) | + ((uint64_t)(ptr[4] & 0xff) << 32) | + ((uint64_t)(ptr[5] & 0xff) << 40) | + ((uint64_t)(ptr[6] & 0xff) << 48) | + ((uint64_t)(ptr[7] & 0xff) << 56)); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/common/src/av_trans_buffer.cpp b/av_transport/common/src/av_trans_buffer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4bae8246d94fbe281aa9a424768e34bb930daefd --- /dev/null +++ b/av_transport/common/src/av_trans_buffer.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_buffer.h" + +#include + +namespace OHOS { +namespace DistributedHardware { +AVTransBuffer::AVTransBuffer(MetaType type) : meta_() +{ + meta_ = std::make_shared(type); +} + +std::shared_ptr AVTransBuffer::CreateBufferData(size_t capacity) +{ + auto bufData = std::make_shared(capacity); + data_.push_back(bufData); + return bufData; +} + +std::shared_ptr AVTransBuffer::WrapBufferData(const uint8_t* data, size_t capacity, size_t size) +{ + auto bufData = std::make_shared(capacity, + std::shared_ptr(const_cast(data), [](void* ptr) {})); + bufData->SetSize(size); + data_.push_back(bufData); + return bufData; +} + +std::shared_ptr AVTransBuffer::GetBufferData(uint32_t index) +{ + if (data_.size() <= index) { + return nullptr; + } + return data_[index]; +} + +std::shared_ptr AVTransBuffer::GetBufferMeta() +{ + return meta_; +} + +void AVTransBuffer::UpdateBufferMeta(std::shared_ptr bufferMeta) +{ + meta_ = bufferMeta; +} + +uint32_t AVTransBuffer::GetDataCount() +{ + return data_.size(); +} + +bool AVTransBuffer::IsEmpty() +{ + return data_.empty(); +} + +void AVTransBuffer::Reset() +{ + data_[0]->Reset(); + MetaType type = meta_->GetMetaType(); + meta_.reset(); + meta_ = std::make_shared(type); +} + +BufferData::BufferData(size_t capacity) + : capacity_(capacity), size_(0), address_(nullptr) +{ + address_ = std::shared_ptr(new uint8_t[capacity], std::default_delete()); +} + +BufferData::BufferData(size_t capacity, std::shared_ptr bufData) + : capacity_(capacity), size_(0), address_(std::move(bufData)) +{ +} + +size_t BufferData::GetSize() +{ + return size_; +} + +size_t BufferData::GetCapacity() +{ + return capacity_; +} + +uint8_t* BufferData::GetAddress() const +{ + return address_.get(); +} + +size_t BufferData::Write(const uint8_t* in, size_t writeSize, size_t position) +{ + size_t start = 0; + if (position == INVALID_POSITION) { + start = size_; + } else { + start = std::min(position, capacity_); + } + size_t length = std::min(writeSize, capacity_ - start); + if (memcpy_s(GetAddress() + start, length, in, length) != EOK) { + return 0; + } + size_ = start + length; + return length; +} + +size_t BufferData::Read(uint8_t* out, size_t readSize, size_t position) +{ + size_t start = 0; + size_t maxLength = size_; + if (position != INVALID_POSITION) { + start = std::min(position, size_); + maxLength = size_ - start; + } + size_t length = std::min(readSize, maxLength); + if (memcpy_s(out, length, GetAddress() + start, length) != EOK) { + return 0; + } + return length; +} + +void BufferData::Reset() +{ + this->size_ = 0; +} + +void BufferData::SetSize(size_t size) +{ + this->size_ = size; +} + +BufferMeta::BufferMeta(MetaType type) : type_(type) +{ +} + +bool BufferMeta::GetMetaItem(AVTransTag tag, std::string& value) +{ + if (tagMap_.count(tag) != 0) { + value = tagMap_[tag]; + return true; + } else { + return false; + } +} + +void BufferMeta::SetMetaItem(AVTransTag tag, const std::string& value) +{ + tagMap_[tag] = value; +} + +MetaType BufferMeta::GetMetaType() const +{ + return type_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/common/src/av_trans_log.cpp b/av_transport/common/src/av_trans_log.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d334a836e1913626eb3619eee5677421efe0955 --- /dev/null +++ b/av_transport/common/src/av_trans_log.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_log.h" + +#include "securec.h" + +#ifdef HI_LOG_ENABLE +#include "hilog/log.h" +#else +#include +#endif + +namespace OHOS { +namespace DistributedHardware { +const std::string DAVTRANS_LOG_TITLE_TAG = "DAVTRANS"; +constexpr int32_t AV_LOG_MAX_LEN = 4096; + +static void AVTransLogOut(DHLogLevel logLevel, const char *logBuf) +{ +#ifdef HI_LOG_ENABLE + LogLevel hiLogLevel = LOG_INFO; + switch (logLevel) { + case DH_LOG_DEBUG: + hiLogLevel = LOG_DEBUG; + break; + case DH_LOG_INFO: + hiLogLevel = LOG_INFO; + break; + case DH_LOG_WARN: + hiLogLevel = LOG_WARN; + break; + case DH_LOG_ERROR: + hiLogLevel = LOG_ERROR; + break; + default: + break; + } + (void)HiLogPrint(LOG_CORE, hiLogLevel, LOG_DOMAIN, DAVTRANS_LOG_TITLE_TAG.c_str(), "%{public}s", logBuf); +#else + switch (logLevel) { + case DH_LOG_DEBUG: + printf("[D]%s\n", logBuf); + break; + case DH_LOG_INFO: + printf("[I]%s\n", logBuf); + break; + case DH_LOG_WARN: + printf("[W]%s\n", logBuf); + break; + case DH_LOG_ERROR: + printf("[E]%s\n", logBuf); + break; + default: + break; + } +#endif +} + +void AVTransLog(DHLogLevel logLevel, const char *fmt, ...) +{ + char logBuf[AV_LOG_MAX_LEN] = {0}; + va_list arg; + + (void)memset_s(&arg, sizeof(va_list), 0, sizeof(va_list)); + va_start(arg, fmt); + int32_t ret = vsprintf_s(logBuf, sizeof(logBuf), fmt, arg); + va_end(arg); + if (ret < 0) { + AVTransLogOut(logLevel, "AVTrans log length error."); + return; + } + AVTransLogOut(logLevel, logBuf); +} + +std::string GetAnonyString(const std::string &value) +{ + constexpr size_t INT32_SHORT_ID_LENGTH = 20; + constexpr size_t INT32_PLAINTEXT_LENGTH = 4; + constexpr size_t INT32_MIN_ID_LENGTH = 3; + std::string res; + std::string tmpStr("******"); + size_t strLen = value.length(); + if (strLen < INT32_MIN_ID_LENGTH) { + return tmpStr; + } + + if (strLen <= INT32_SHORT_ID_LENGTH) { + res += value[0]; + res += tmpStr; + res += value[strLen - 1]; + } else { + res.append(value, 0, INT32_PLAINTEXT_LENGTH); + res += tmpStr; + res.append(value, strLen - INT32_PLAINTEXT_LENGTH, INT32_PLAINTEXT_LENGTH); + } + + return res; +} + +std::string GetAnonyInt32(const int32_t value) +{ + constexpr int32_t INT32_STRING_LENGTH = 40; + char tempBuffer[INT32_STRING_LENGTH] = ""; + int32_t secRet = sprintf_s(tempBuffer, INT32_STRING_LENGTH, "%d", value); + if (secRet <= 0) { + std::string nullString(""); + return nullString; + } + size_t length = strlen(tempBuffer); + for (size_t i = 1; i <= length - 1; i++) { + tempBuffer[i] = '*'; + } + if (length == 0x01) { + tempBuffer[0] = '*'; + } + + std::string tempString(tempBuffer); + return tempString; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/common/src/av_trans_message.cpp b/av_transport/common/src/av_trans_message.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db3eda7a2c1342e54433e16460e70f74414fae55 --- /dev/null +++ b/av_transport/common/src/av_trans_message.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_message.h" + +#include "av_trans_constants.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string KEY_TYPE = "type"; +const std::string KEY_CONTENT = "content"; +const std::string KEY_DST_DEVID = "dstDevId"; + +AVTransMessage::AVTransMessage() +{ + type_ = 0; +} + +AVTransMessage::AVTransMessage(uint32_t type, std::string content, std::string dstDevId) + : type_(type), content_(content), dstDevId_(dstDevId) +{ +} + +AVTransMessage::~AVTransMessage() +{ +} + +std::string AVTransMessage::MarshalMessage() +{ + nlohmann::json msgJson; + msgJson[KEY_TYPE] = type_; + msgJson[KEY_CONTENT] = content_; + msgJson[KEY_DST_DEVID] = dstDevId_; + return msgJson.dump(); +} + +bool AVTransMessage::UnmarshalMessage(const std::string& jsonStr, const std::string &peerDevId) +{ + nlohmann::json msgJson = nlohmann::json::parse(jsonStr, nullptr, false); + if (msgJson.is_discarded()) { + return false; + } + if (!IsUInt32(msgJson, KEY_TYPE) || !IsString(msgJson, KEY_CONTENT)) { + return false; + } + type_ = msgJson[KEY_TYPE].get(); + content_ = msgJson[KEY_CONTENT].get(); + dstDevId_ = peerDevId; + return true; +} + +bool AVTransMessage::IsUInt32(const nlohmann::json &msgJson, const std::string &key) +{ + return msgJson.contains(key) && msgJson[key].is_number_unsigned() && msgJson[key] <= UINT32_MAX; +} + +bool AVTransMessage::IsString(const nlohmann::json &msgJson, const std::string &key) +{ + return msgJson.contains(key) && msgJson[key].is_string() && msgJson[key].size() <= MAX_MESSAGES_LEN; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/common/src/av_trans_meta.cpp b/av_transport/common/src/av_trans_meta.cpp new file mode 100644 index 0000000000000000000000000000000000000000..37adf6fcf4729eb1554d024f8a919d42692a3ba1 --- /dev/null +++ b/av_transport/common/src/av_trans_meta.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_meta.h" + +#include "av_trans_utils.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +const std::string META_DATA_TYPE = "meta_data_type"; +const std::string META_TIMESTAMP = "meta_timestamp"; +const std::string META_FRAME_NUMBER = "meta_frame_number"; +const std::string META_EXT_TIMESTAMP = "meta_ext_timestamp"; +const std::string META_EXT_FRAME_NUMBER = "meta_ext_frame_number"; + +std::shared_ptr AVTransAudioBufferMeta::Clone() +{ + auto bufferMeta = std::make_shared(); + bufferMeta->pts_ = pts_; + bufferMeta->cts_ = cts_; + bufferMeta->format_ = format_; + bufferMeta->dataType_ = dataType_; + bufferMeta->frameNum_ = frameNum_; + bufferMeta->channels_ = channels_; + bufferMeta->sampleRate_ = sampleRate_; + bufferMeta->Update(*this); + return bufferMeta; +} + +std::string AVTransAudioBufferMeta::MarshalAudioMeta() +{ + nlohmann::json metaJson; + metaJson[META_DATA_TYPE] = dataType_; + metaJson[META_TIMESTAMP] = pts_; + metaJson[META_FRAME_NUMBER] = frameNum_; + return metaJson.dump(); +} + +bool AVTransAudioBufferMeta::UnmarshalAudioMeta(const std::string& jsonStr) +{ + nlohmann::json metaJson = nlohmann::json::parse(jsonStr, nullptr, false); + if (metaJson.is_discarded()) { + return false; + } + if (!IsUInt32(metaJson, META_DATA_TYPE) || !IsInt64(metaJson, META_TIMESTAMP) || + !IsUInt32(metaJson, META_FRAME_NUMBER)) { + return false; + } + dataType_ = metaJson[META_DATA_TYPE].get(); + pts_ = metaJson[META_TIMESTAMP].get(); + frameNum_ = metaJson[META_FRAME_NUMBER].get(); + return true; +} + +std::shared_ptr AVTransVideoBufferMeta::Clone() +{ + auto bufferMeta = std::make_shared(); + bufferMeta->pts_ = pts_; + bufferMeta->cts_ = cts_; + bufferMeta->width_ = width_; + bufferMeta->height_ = height_; + bufferMeta->format_ = format_; + bufferMeta->dataType_ = dataType_; + bufferMeta->frameNum_ = frameNum_; + bufferMeta->extPts_ = extPts_; + bufferMeta->extFrameNum_ = extFrameNum_; + bufferMeta->Update(*this); + return bufferMeta; +} + +std::string AVTransVideoBufferMeta::MarshalVideoMeta() +{ + nlohmann::json metaJson; + metaJson[META_DATA_TYPE] = dataType_; + metaJson[META_TIMESTAMP] = pts_; + metaJson[META_FRAME_NUMBER] = frameNum_; + if (extPts_ > 0) { + metaJson[META_EXT_TIMESTAMP] = extPts_; + } + if (extFrameNum_ > 0) { + metaJson[META_EXT_FRAME_NUMBER] = extFrameNum_; + } + return metaJson.dump(); +} + +bool AVTransVideoBufferMeta::UnmarshalVideoMeta(const std::string& jsonStr) +{ + nlohmann::json metaJson = nlohmann::json::parse(jsonStr, nullptr, false); + if (metaJson.is_discarded()) { + return false; + } + if (IsUInt32(metaJson, META_DATA_TYPE)) { + dataType_ = metaJson[META_DATA_TYPE].get(); + } + if (IsInt64(metaJson, META_TIMESTAMP)) { + pts_ = metaJson[META_TIMESTAMP].get(); + } + if (IsUInt32(metaJson, META_FRAME_NUMBER)) { + frameNum_ = metaJson[META_FRAME_NUMBER].get(); + } + if (IsInt64(metaJson, META_EXT_TIMESTAMP)) { + extPts_ = metaJson[META_EXT_TIMESTAMP].get(); + } + if (IsUInt32(metaJson, META_EXT_FRAME_NUMBER)) { + extFrameNum_ = metaJson[META_EXT_FRAME_NUMBER].get(); + } + return true; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/common/src/av_trans_utils.cpp b/av_transport/common/src/av_trans_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..17931cbb688a6e78a7ad9d8073f5013aacc77791 --- /dev/null +++ b/av_transport/common/src/av_trans_utils.cpp @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "av_trans_utils.h" + +#include +#include + +#include "av_trans_constants.h" +#include "av_trans_log.h" +#include "av_trans_meta.h" + +#include "plugin/common/share_allocator.h" + +namespace OHOS { +namespace DistributedHardware { +using HiSBufferMeta = OHOS::Media::Plugin::BufferMeta; +using TransBufferMeta = OHOS::DistributedHardware::BufferMeta; + +const std::string KEY_OWNER_NAME = "ownerName"; +const std::string KEY_PEER_DEVID = "peerDevId"; + +std::string TransName2PkgName(const std::string &ownerName) +{ + const static std::pair mapArray[] = { + {OWNER_NAME_D_MIC, PKG_NAME_D_AUDIO}, + {OWNER_NAME_D_CAMERA, PKG_NAME_D_CAMERA}, + {OWNER_NAME_D_SCREEN, PKG_NAME_D_SCREEN}, + {OWNER_NAME_D_SPEAKER, PKG_NAME_D_AUDIO}, + }; + for (const auto& item : mapArray) { + if (item.first == ownerName) { + return item.second; + } + } + return EMPTY_STRING; +} + +OHOS::Media::Plugin::MediaType TransName2MediaType(const std::string &ownerName) +{ + const static std::pair mapArray[] = { + {OWNER_NAME_D_MIC, OHOS::Media::Plugin::MediaType::AUDIO}, + {OWNER_NAME_D_CAMERA, OHOS::Media::Plugin::MediaType::VIDEO}, + {OWNER_NAME_D_SCREEN, OHOS::Media::Plugin::MediaType::VIDEO}, + {OWNER_NAME_D_SPEAKER, OHOS::Media::Plugin::MediaType::AUDIO}, + }; + for (const auto& item : mapArray) { + if (item.first == ownerName) { + return item.second; + } + } + return OHOS::Media::Plugin::MediaType::UNKNOWN; +} + +std::string BuildChannelDescription(const std::string &ownerName, const std::string &peerDevId) +{ + nlohmann::json descJson; + descJson[KEY_OWNER_NAME] = ownerName; + descJson[KEY_PEER_DEVID] = peerDevId; + return descJson.dump(); +} + +void ParseChannelDescription(const std::string &descJsonStr, std::string &ownerName, std::string &peerDevId) +{ + nlohmann::json descJson = nlohmann::json::parse(descJsonStr, nullptr, false); + if (descJson.is_discarded()) { + return; + } + if (!descJson.contains(KEY_OWNER_NAME) || !descJson.contains(KEY_PEER_DEVID)) { + return; + } + if (!IsString(descJson, KEY_OWNER_NAME) || !IsString(descJson, KEY_PEER_DEVID)) { + return; + } + ownerName = descJson[KEY_OWNER_NAME].get(); + peerDevId = descJson[KEY_PEER_DEVID].get(); +} + +std::shared_ptr TransBuffer2HiSBuffer(const std::shared_ptr& transBuffer) +{ + if ((transBuffer == nullptr) || transBuffer->IsEmpty()) { + return nullptr; + } + + auto data = transBuffer->GetBufferData(); + if (data == nullptr) { + return nullptr; + } + + auto hisBuffer = std::make_shared(); + hisBuffer->WrapMemory(data->GetAddress(), data->GetCapacity(), data->GetSize()); + + Convert2HiSBufferMeta(transBuffer, hisBuffer); + return hisBuffer; +} + +std::shared_ptr HiSBuffer2TransBuffer(const std::shared_ptr& hisBuffer) +{ + if ((hisBuffer == nullptr) || hisBuffer->IsEmpty()) { + return nullptr; + } + + auto memory = hisBuffer->GetMemory(); + if (memory == nullptr) { + return nullptr; + } + + auto transBuffer = std::make_shared(); + transBuffer->WrapBufferData(memory->GetReadOnlyData(), memory->GetCapacity(), memory->GetSize()); + + Convert2TransBufferMeta(hisBuffer, transBuffer); + return transBuffer; +} + +void Convert2HiSBufferMeta(std::shared_ptr transBuffer, std::shared_ptr hisBuffer) +{ + std::shared_ptr transMeta = transBuffer->GetBufferMeta(); + if ((transMeta->GetMetaType() == MetaType::AUDIO)) { + auto hisAMeta = std::make_shared(); + + std::string value; + transMeta->GetMetaItem(AVTransTag::BUFFER_DATA_TYPE, value); + uint32_t dataType = static_cast(std::atoi(value.c_str())); + hisAMeta->dataType_ = (BufferDataType)dataType; + + transMeta->GetMetaItem(AVTransTag::AUDIO_SAMPLE_FORMAT, value); + uint32_t format = static_cast(std::atoi(value.c_str())); + hisAMeta->format_ = (AudioSampleFormat)format; + + transMeta->GetMetaItem(AVTransTag::AUDIO_SAMPLE_RATE, value); + hisAMeta->sampleRate_ = static_cast(std::atoi(value.c_str())); + + hisBuffer->UpdateBufferMeta(*hisAMeta); + } else { + auto hisVMeta = std::make_shared(); + + std::string value; + transMeta->GetMetaItem(AVTransTag::BUFFER_DATA_TYPE, value); + uint32_t dataType = static_cast(std::atoi(value.c_str())); + hisVMeta->dataType_ = (BufferDataType)dataType; + + transMeta->GetMetaItem(AVTransTag::VIDEO_PIXEL_FORMAT, value); + uint32_t format = static_cast(std::atoi(value.c_str())); + hisVMeta->format_ = (VideoPixelFormat)format; + + transMeta->GetMetaItem(AVTransTag::VIDEO_WIDTH, value); + hisVMeta->width_ = static_cast(std::atoi(value.c_str())); + + transMeta->GetMetaItem(AVTransTag::VIDEO_HEIGHT, value); + hisVMeta->height_ = static_cast(std::atoi(value.c_str())); + + TRUE_LOG_MSG(!transMeta->GetMetaItem(AVTransTag::PRE_TIMESTAMP, value), "get PRE_TIMESTAMP meta failed"); + hisVMeta->pts_ = std::stoll(value.c_str()); + + hisBuffer->pts = std::stoll(value.c_str()); + hisBuffer->UpdateBufferMeta(*hisVMeta); + } +} + +void Convert2TransBufferMeta(std::shared_ptr hisBuffer, std::shared_ptr transBuffer) +{ + std::shared_ptr hisMeta = hisBuffer->GetBufferMeta(); + if ((hisMeta->GetType() == BufferMetaType::AUDIO)) { + std::shared_ptr hisAMeta = ReinterpretCastPointer(hisMeta); + TRUE_RETURN(hisAMeta == nullptr, "hisAMeta is null"); + + auto transAMeta = std::make_shared(MetaType::AUDIO); + transAMeta->SetMetaItem(AVTransTag::BUFFER_DATA_TYPE, std::to_string((uint32_t)(hisAMeta->dataType_))); + transAMeta->SetMetaItem(AVTransTag::AUDIO_SAMPLE_FORMAT, std::to_string((uint32_t)(hisAMeta->format_))); + transAMeta->SetMetaItem(AVTransTag::AUDIO_SAMPLE_RATE, std::to_string(hisAMeta->sampleRate_)); + + transBuffer->UpdateBufferMeta(transAMeta); + } else { + std::shared_ptr hisVMeta = ReinterpretCastPointer(hisMeta); + TRUE_RETURN(hisVMeta == nullptr, "hisAMeta is null"); + + auto transVMeta = std::make_shared(MetaType::VIDEO); + transVMeta->SetMetaItem(AVTransTag::BUFFER_DATA_TYPE, std::to_string((uint32_t)(hisVMeta->dataType_))); + transVMeta->SetMetaItem(AVTransTag::VIDEO_PIXEL_FORMAT, std::to_string((uint32_t)(hisVMeta->format_))); + transVMeta->SetMetaItem(AVTransTag::VIDEO_WIDTH, std::to_string(hisVMeta->width_)); + transVMeta->SetMetaItem(AVTransTag::VIDEO_HEIGHT, std::to_string(hisVMeta->height_)); + transVMeta->SetMetaItem(AVTransTag::PRE_TIMESTAMP, std::to_string(hisVMeta->pts_)); + + transBuffer->UpdateBufferMeta(transVMeta); + } +} + +EventType CastEventType(Plugin::PluginEventType type, bool isAbnormal) +{ + switch (type) { + case Plugin::PluginEventType::EVENT_CHANNEL_OPENED: + return EventType::EVENT_START_SUCCESS; + case Plugin::PluginEventType::EVENT_CHANNEL_OPEN_FAIL: + return EventType::EVENT_START_FAIL; + case Plugin::PluginEventType::EVENT_CHANNEL_CLOSED: + return isAbnormal ? EventType::EVENT_ENGINE_ERROR : EventType::EVENT_STOP_SUCCESS; + default: + AVTRANS_LOGE("unsupport plugin event type."); + } + return EventType::EVENT_ENGINE_ERROR; +} + +void DumpBufferToFile(std::string fileName, uint8_t *buffer, int32_t bufSize) +{ + if (fileName.empty()) { + AVTRANS_LOGE("input fileName is empty."); + return; + } + std::ofstream ofs(fileName, std::ios::binary | std::ios::out | std::ios::app); + if (!ofs.is_open()) { + AVTRANS_LOGE("open file failed."); + return; + } + ofs.write((const char*)(buffer), bufSize); + ofs.close(); +} + +bool IsUInt32(const nlohmann::json &jsonObj, const std::string &key) +{ + return jsonObj.contains(key) && jsonObj[key].is_number_unsigned() && jsonObj[key] <= UINT32_MAX; +} + +bool IsInt64(const nlohmann::json &jsonObj, const std::string &key) +{ + return jsonObj.contains(key) && jsonObj[key].is_number_integer() && INT64_MIN <= jsonObj[key] && + jsonObj[key] <= INT64_MAX; +} + +bool IsString(const nlohmann::json &jsonObj, const std::string &key) +{ + return jsonObj.contains(key) && jsonObj[key].is_string() && jsonObj[key].size() <= MAX_MESSAGES_LEN; +} + +int64_t GetCurrentTime() +{ + struct timespec time = { 0, 0 }; + clock_gettime(CLOCK_MONOTONIC, &time); + return time.tv_sec * NS_ONE_S + time.tv_nsec; +} + +void GenerateAdtsHeader(unsigned char* adtsHeader, uint32_t packetLen, uint32_t profile, uint32_t sampleRate, + uint32_t channels) +{ + static std::map mapSampleRateToFreIndex { + {96000, 0}, + {88200, 1}, + {64000, 2}, + {48000, 3}, + {44100, 4}, + {32000, 5}, + {24000, 6}, + {16000, 8}, + {12000, 9}, + {11025, 10}, + {8000, 11}, + {7350, 12}, + }; + // profile only support AAC LC: 1 + uint32_t freqIdx = mapSampleRateToFreIndex[sampleRate]; // 48KHz : 3 + adtsHeader[0] = (unsigned char) 0xFF; + adtsHeader[1] = (unsigned char) 0xF9; + adtsHeader[2] = (unsigned char) (((profile - 1) << 6) + (freqIdx << 2) + (channels >> 2)); + adtsHeader[3] = (unsigned char) (((channels & 3) << 6) + (packetLen >> 11)); + adtsHeader[4] = (unsigned char) ((packetLen & 0x7FF) >> 3); + adtsHeader[5] = (unsigned char) (((packetLen & 7) << 5) + 0x1F); + adtsHeader[6] = (unsigned char) 0xFC; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/common/src/softbus_channel_adapter.cpp b/av_transport/common/src/softbus_channel_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a09c0a214a7d7f8331b25b2e25aa6b57c8a3f128 --- /dev/null +++ b/av_transport/common/src/softbus_channel_adapter.cpp @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "softbus_channel_adapter.h" + +#include +#include +#include + +#include "av_trans_constants.h" +#include "av_trans_errno.h" +#include "av_trans_log.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "SoftbusChannelAdapter" + +IMPLEMENT_SINGLE_INSTANCE(SoftbusChannelAdapter); + +static int32_t OnSessionOpened(int32_t sessionId, int32_t result) +{ + return SoftbusChannelAdapter::GetInstance().OnSoftbusChannelOpened(sessionId, result); +} + +static void OnSessionClosed(int32_t sessionId) +{ + SoftbusChannelAdapter::GetInstance().OnSoftbusChannelClosed(sessionId); +} + +static void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + SoftbusChannelAdapter::GetInstance().OnSoftbusBytesReceived(sessionId, data, dataLen); +} + +static void OnStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *frameInfo) +{ + SoftbusChannelAdapter::GetInstance().OnSoftbusStreamReceived(sessionId, data, ext, frameInfo); +} + +static void onDevTimeSyncResult(const TimeSyncResultInfo *info, int32_t result) +{ + SoftbusChannelAdapter::GetInstance().OnSoftbusTimeSyncResult(info, result); +} + +SoftbusChannelAdapter::SoftbusChannelAdapter() +{ + sessListener_.OnSessionOpened = OnSessionOpened; + sessListener_.OnSessionClosed = OnSessionClosed; + sessListener_.OnBytesReceived = OnBytesReceived; + sessListener_.OnStreamReceived = OnStreamReceived; + sessListener_.OnMessageReceived = nullptr; + sessListener_.OnQosEvent = nullptr; +} + +SoftbusChannelAdapter::~SoftbusChannelAdapter() +{ + listenerMap_.clear(); + sessionNameSet_.clear(); + timeSyncSessNames_.clear(); + devId2SessIdMap_.clear(); +} + +int32_t SoftbusChannelAdapter::CreateChannelServer(const std::string& pkgName, const std::string &sessName) +{ + AVTRANS_LOGI("Create session server for sessionName:%s.", sessName.c_str()); + TRUE_RETURN_V_MSG_E(pkgName.empty(), ERR_DH_AVT_INVALID_PARAM, "input pkgName is empty."); + TRUE_RETURN_V_MSG_E(sessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input sessionName is empty."); + + std::lock_guard setLock(name2IdMtx_); + if (sessionNameSet_.find(sessName) == sessionNameSet_.end()) { + int32_t ret = CreateSessionServer(pkgName.c_str(), sessName.c_str(), &sessListener_); + TRUE_RETURN_V_MSG_E(ret != DH_AVT_SUCCESS, ERR_DH_AVT_CREATE_CHANNEL_FAILED, "create session server failed"); + } else { + AVTRANS_LOGE("Session has already created for name:%s", sessName.c_str()); + } + sessionNameSet_.insert(sessName); + + AVTRANS_LOGI("Create session server success for sessionName:%s.", sessName.c_str()); + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::RemoveChannelServer(const std::string& pkgName, const std::string &sessName) +{ + AVTRANS_LOGI("Remove session server for sessionName:%s.", sessName.c_str()); + TRUE_RETURN_V_MSG_E(pkgName.empty(), ERR_DH_AVT_INVALID_PARAM, "input pkgName is empty."); + TRUE_RETURN_V_MSG_E(sessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input sessionName is empty."); + + std::lock_guard setLock(name2IdMtx_); + if (sessionNameSet_.find(sessName) == sessionNameSet_.end()) { + AVTRANS_LOGE("Can not found session name:%s", sessName.c_str()); + return ERR_DH_AVT_INVALID_PARAM_VALUE; + } + RemoveSessionServer(pkgName.c_str(), sessName.c_str()); + sessionNameSet_.erase(sessName); + + AVTRANS_LOGI("Remove session server success for sessionName:%s.", sessName.c_str()); + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::OpenSoftbusChannel(const std::string& mySessName, const std::string &peerSessName, + const std::string &peerDevId) +{ + AVTRANS_LOGI("Open softbus channel for mySessName:%s, peerSessName:%s, peerDevId:%s.", + mySessName.c_str(), peerSessName.c_str(), GetAnonyString(peerDevId).c_str()); + TRUE_RETURN_V_MSG_E(mySessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input mySessName is empty."); + TRUE_RETURN_V_MSG_E(peerSessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerSessName is empty."); + TRUE_RETURN_V_MSG_E(peerDevId.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerDevId is empty."); + + int32_t existSessId = GetSessIdBySessName(mySessName, peerDevId); + if (existSessId > 0) { + AVTRANS_LOGI("Softbus channel already opened, sessionId:%" PRId32, existSessId); + return ERR_DH_AVT_SESSION_HAS_OPENED; + } + + int dataType = TYPE_BYTES; + int streamType = INVALID; + if (mySessName.find("avtrans.data") != std::string::npos) { + dataType = TYPE_STREAM; + streamType = COMMON_VIDEO_STREAM; + } + + SessionAttribute attr = { 0 }; + attr.dataType = dataType; + attr.linkTypeNum = LINK_TYPE_MAX; + LinkType linkTypeList[LINK_TYPE_MAX] = { + LINK_TYPE_WIFI_P2P, + LINK_TYPE_WIFI_WLAN_5G, + LINK_TYPE_WIFI_WLAN_2G, + LINK_TYPE_BR, + }; + int32_t ret = memcpy_s(attr.linkType, sizeof(attr.linkType), linkTypeList, sizeof(linkTypeList)); + if (ret != EOK) { + AVTRANS_LOGE("Data copy failed."); + return ERR_DH_AVT_NO_MEMORY; + } + attr.attr.streamAttr.streamType = streamType; + int32_t sessionId = OpenSession(mySessName.c_str(), peerSessName.c_str(), peerDevId.c_str(), "0", &attr); + if (sessionId < 0) { + AVTRANS_LOGE("Open softbus session failed for sessionId:%" PRId32, sessionId); + return ERR_DH_AVT_SESSION_ERROR; + } + { + std::lock_guard lock(idMapMutex_); + devId2SessIdMap_.insert(std::make_pair(mySessName + "_" + peerDevId, sessionId)); + } + AVTRANS_LOGI("Open softbus channel finished, sessionId:%" PRId32, sessionId); + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::CloseSoftbusChannel(const std::string& sessName, const std::string &peerDevId) +{ + AVTRANS_LOGI("Close softbus channel for sessName:%s, peerDevId:%s.", sessName.c_str(), + GetAnonyString(peerDevId).c_str()); + TRUE_RETURN_V_MSG_E(sessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input sessName is empty."); + TRUE_RETURN_V_MSG_E(peerDevId.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerDevId is empty."); + + int32_t sessionId = GetSessIdBySessName(sessName, peerDevId); + CloseSession(sessionId); + { + std::lock_guard lock(idMapMutex_); + devId2SessIdMap_.erase(sessName + "_" + peerDevId); + } + + AVTRANS_LOGI("Close softbus channel success, sessionId:%" PRId32, sessionId); + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::SendBytesData(const std::string& sessName, const std::string &peerDevId, + const std::string &data) +{ + AVTRANS_LOGI("Send bytes data for sessName:%s, peerDevId:%s.", sessName.c_str(), GetAnonyString(peerDevId).c_str()); + TRUE_RETURN_V_MSG_E(sessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input sessName is empty."); + TRUE_RETURN_V_MSG_E(peerDevId.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerDevId is empty."); + TRUE_RETURN_V_MSG_E(data.empty(), ERR_DH_AVT_INVALID_PARAM, "input data string is empty."); + + int32_t ret = SendBytes(GetSessIdBySessName(sessName, peerDevId), data.c_str(), strlen(data.c_str())); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Send bytes data failed ret:%" PRId32, ret); + return ERR_DH_AVT_SEND_DATA_FAILED; + } + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::SendStreamData(const std::string& sessName, const std::string &peerDevId, + const StreamData *data, const StreamData *ext) +{ + TRUE_RETURN_V_MSG_E(sessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input sessName is empty."); + TRUE_RETURN_V_MSG_E(peerDevId.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerDevId is empty."); + TRUE_RETURN_V_MSG_E(data == nullptr, ERR_DH_AVT_INVALID_PARAM, "input data is nullptr."); + TRUE_RETURN_V_MSG_E(ext == nullptr, ERR_DH_AVT_INVALID_PARAM, "input ext data is nullptr."); + + StreamFrameInfo frameInfo = {0}; + int32_t ret = SendStream(GetSessIdBySessName(sessName, peerDevId), data, ext, &frameInfo); + if (ret != DH_AVT_SUCCESS) { + AVTRANS_LOGE("Send stream data failed ret:%" PRId32, ret); + return ERR_DH_AVT_SEND_DATA_FAILED; + } + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::RegisterChannelListener(const std::string& sessName, const std::string &peerDevId, + ISoftbusChannelListener *listener) +{ + AVTRANS_LOGI("Register channel listener for sessName:%s, peerDevId:%s.", + sessName.c_str(), GetAnonyString(peerDevId).c_str()); + TRUE_RETURN_V_MSG_E(sessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input sessName is empty."); + TRUE_RETURN_V_MSG_E(peerDevId.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerDevId is empty."); + TRUE_RETURN_V_MSG_E(listener == nullptr, ERR_DH_AVT_INVALID_PARAM, "input callback is nullptr."); + + std::lock_guard lock(listenerMtx_); + listenerMap_.insert(std::make_pair(sessName + "_" + peerDevId, listener)); + + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::UnRegisterChannelListener(const std::string& sessName, const std::string &peerDevId) +{ + AVTRANS_LOGI("Unregister channel listener for sessName:%s, peerDevId:%s.", + sessName.c_str(), GetAnonyString(peerDevId).c_str()); + TRUE_RETURN_V_MSG_E(sessName.empty(), ERR_DH_AVT_INVALID_PARAM, "input sessName is empty."); + TRUE_RETURN_V_MSG_E(peerDevId.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerDevId is empty."); + + std::lock_guard lock(listenerMtx_); + listenerMap_.erase(sessName + "_" + peerDevId); + + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::StartDeviceTimeSync(const std::string &pkgName, const std::string& sessName, + const std::string &peerDevId) +{ + AVTRANS_LOGI("Start device time sync for peerDeviceId:%s.", GetAnonyString(peerDevId).c_str()); + TRUE_RETURN_V_MSG_E(peerDevId.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerDevId is empty."); + + ITimeSyncCb timeSyncCbk = {.onTimeSyncResult = onDevTimeSyncResult}; + int32_t ret = StartTimeSync(pkgName.c_str(), peerDevId.c_str(), TimeSyncAccuracy::SUPER_HIGH_ACCURACY, + TimeSyncPeriod::SHORT_PERIOD, &timeSyncCbk); + if (ret != 0) { + AVTRANS_LOGE("StartTimeSync failed ret:%" PRId32, ret); + return ERR_DH_AVT_TIME_SYNC_FAILED; + } + + std::lock_guard lock(timeSyncMtx_); + timeSyncSessNames_.insert(sessName + "_" + peerDevId); + + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::StopDeviceTimeSync(const std::string &pkgName, const std::string& sessName, + const std::string &peerDevId) +{ + AVTRANS_LOGI("Stop device time sync for peerDeviceId:%s.", GetAnonyString(peerDevId).c_str()); + TRUE_RETURN_V_MSG_E(peerDevId.empty(), ERR_DH_AVT_INVALID_PARAM, "input peerDevId is empty."); + + int32_t ret = StopTimeSync(pkgName.c_str(), peerDevId.c_str()); + if (ret != 0) { + AVTRANS_LOGE("StopTimeSync failed ret:%" PRId32, ret); + return ERR_DH_AVT_TIME_SYNC_FAILED; + } + + std::lock_guard lock(timeSyncMtx_); + timeSyncSessNames_.erase(sessName + "_" + peerDevId); + + return DH_AVT_SUCCESS; +} + +int32_t SoftbusChannelAdapter::GetSessIdBySessName(const std::string& sessName, const std::string &peerDevId) +{ + std::lock_guard lock(idMapMutex_); + std::string idMapKey = sessName + "_" + peerDevId; + if (devId2SessIdMap_.find(idMapKey) == devId2SessIdMap_.end()) { + AVTRANS_LOGE("Can not find sessionId for sessName:%s, peerDevId:%s.", + sessName.c_str(), GetAnonyString(peerDevId).c_str()); + return -1; + } + return devId2SessIdMap_[idMapKey]; +} + +std::string SoftbusChannelAdapter::GetSessionNameById(int32_t sessionId) +{ + std::lock_guard lock(idMapMutex_); + for (auto it = devId2SessIdMap_.begin(); it != devId2SessIdMap_.end(); it++) { + if (it->second == sessionId) { + return it->first; + } + } + + AVTRANS_LOGE("No available channel or invalid sessionId:%" PRId32, sessionId); + return EMPTY_STRING; +} + +int32_t SoftbusChannelAdapter::OnSoftbusChannelOpened(int32_t sessionId, int32_t result) +{ + AVTRANS_LOGI("On softbus channel opened, sessionId:%" PRId32", result:%" PRId32, sessionId, result); + + char peerDevIdChar[MAX_DEVICE_ID_LEN] = ""; + int32_t ret = GetPeerDeviceId(sessionId, peerDevIdChar, sizeof(peerDevIdChar)); + TRUE_RETURN_V_MSG_E(ret != 0, ret, "Get peer device id from softbus failed."); + std::string peerDevId(peerDevIdChar); + + char sessNameChar[MAX_SESSION_NAME_LEN] = ""; + ret = GetMySessionName(sessionId, sessNameChar, sizeof(sessNameChar)); + TRUE_RETURN_V_MSG_E(ret != 0, ret, "Get my session name from softbus failed."); + std::string sessName(sessNameChar); + + EventType type = (result == 0) ? EventType::EVENT_CHANNEL_OPENED : EventType::EVENT_CHANNEL_OPEN_FAIL; + AVTransEvent event = {type, sessName, peerDevId}; + + { + std::lock_guard lock(idMapMutex_); + { + std::lock_guard lock(listenerMtx_); + for (auto it = listenerMap_.begin(); it != listenerMap_.end(); it++) { + if (((it->first).find(sessName) != std::string::npos) && (it->second != nullptr)) { + std::thread(&SoftbusChannelAdapter::SendChannelEvent, this, it->second, event).detach(); + devId2SessIdMap_.erase(it->first); + devId2SessIdMap_.insert(std::make_pair(it->first, sessionId)); + } + } + } + } + + int32_t existSessId = GetSessIdBySessName(sessName, peerDevId); + if (existSessId == -1) { + std::lock_guard lock(idMapMutex_); + devId2SessIdMap_.insert(std::make_pair(sessName + "_" + peerDevId, sessionId)); + } + + return DH_AVT_SUCCESS; +} + +void SoftbusChannelAdapter::OnSoftbusChannelClosed(int32_t sessionId) +{ + AVTRANS_LOGI("On softbus channel closed, sessionId:%" PRId32, sessionId); + + std::string peerDevId = GetPeerDevIdBySessId(sessionId); + AVTransEvent event = {EventType::EVENT_CHANNEL_CLOSED, "", peerDevId}; + + std::lock_guard lock(idMapMutex_); + for (auto it = devId2SessIdMap_.begin(); it != devId2SessIdMap_.end();) { + if (it->second == sessionId) { + event.content = GetOwnerFromSessName(it->first); + std::lock_guard lock(listenerMtx_); + std::thread(&SoftbusChannelAdapter::SendChannelEvent, this, listenerMap_[it->first], event).detach(); + devId2SessIdMap_.erase(it++); + } else { + it++; + } + } +} + +void SoftbusChannelAdapter::OnSoftbusBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + AVTRANS_LOGI("On softbus channel bytes received, sessionId:%" PRId32, sessionId); + TRUE_RETURN(data == nullptr, "input data is nullptr."); + TRUE_RETURN(dataLen == 0, "input dataLen is 0."); + + char peerDevIdChar[MAX_DEVICE_ID_LEN] = ""; + int32_t ret = GetPeerDeviceId(sessionId, peerDevIdChar, sizeof(peerDevIdChar)); + TRUE_RETURN(ret != 0, "Get peer device id from softbus failed."); + std::string peerDevId(peerDevIdChar); + + std::string dataStr = std::string(reinterpret_cast(data), dataLen); + AVTransEvent event = {EventType::EVENT_DATA_RECEIVED, dataStr, peerDevId}; + + std::lock_guard lock(idMapMutex_); + for (auto it = devId2SessIdMap_.begin(); it != devId2SessIdMap_.end(); it++) { + if (it->second == sessionId) { + std::lock_guard lock(listenerMtx_); + std::thread(&SoftbusChannelAdapter::SendChannelEvent, this, listenerMap_[it->first], event).detach(); + } + } +} + +void SoftbusChannelAdapter::OnSoftbusStreamReceived(int32_t sessionId, const StreamData *data, + const StreamData *ext, const StreamFrameInfo *frameInfo) +{ + (void)frameInfo; + TRUE_RETURN(data == nullptr, "input data is nullptr."); + TRUE_RETURN(ext == nullptr, "input ext data is nullptr."); + + std::lock_guard lock(idMapMutex_); + for (auto it = devId2SessIdMap_.begin(); it != devId2SessIdMap_.end(); it++) { + if (it->second == sessionId) { + std::lock_guard lock(listenerMtx_); + ISoftbusChannelListener *listener = listenerMap_[it->first]; + TRUE_RETURN(listener == nullptr, "Can not find channel listener."); + listener->OnStreamReceived(data, ext); + } + } +} + +void SoftbusChannelAdapter::OnSoftbusTimeSyncResult(const TimeSyncResultInfo *info, int32_t result) +{ + AVTRANS_LOGI("On softbus channel time sync result:%" PRId32, result); + TRUE_RETURN(result == 0, "On softbus channel time sync failed"); + + int32_t millisecond = info->result.millisecond; + int32_t microsecond = info->result.microsecond; + TimeSyncAccuracy accuracy = info->result.accuracy; + AVTRANS_LOGI("Time sync success, flag:%" PRId32", millisecond:%" PRId32 ", microsecond:%" PRId32 + ", accuracy:%" PRId32, info->flag, millisecond, microsecond, accuracy); + + std::string targetDevId(info->target.targetNetworkId); + std::string masterDevId(info->target.masterNetworkId); + std::lock_guard lock(timeSyncMtx_); + for (auto sessName : timeSyncSessNames_) { + std::lock_guard lock(listenerMtx_); + ISoftbusChannelListener *listener = listenerMap_[sessName]; + if (listener != nullptr) { + listener->OnChannelEvent({EventType::EVENT_TIME_SYNC_RESULT, std::to_string(millisecond), targetDevId}); + } + } +} + +std::string SoftbusChannelAdapter::GetPeerDevIdBySessId(int32_t sessionId) +{ + std::lock_guard lock(idMapMutex_); + for (auto it = devId2SessIdMap_.begin(); it != devId2SessIdMap_.end(); it++) { + if (it->second != sessionId) { + continue; + } + std::string::size_type position = (it->first).find_last_of("_"); + if (position == std::string::npos) { + continue; + } + std::string peerDevId = (it->first).substr(position + 1); + if (peerDevId != AV_TRANS_SPECIAL_DEVICE_ID) { + return peerDevId; + } + } + return EMPTY_STRING; +} + +std::string SoftbusChannelAdapter::GetOwnerFromSessName(const std::string &sessName) +{ + std::string::size_type position = sessName.find_first_of("_"); + if (position != std::string::npos) { + return sessName.substr(0, position); + } + return EMPTY_STRING; +} + +void SoftbusChannelAdapter::SendChannelEvent(ISoftbusChannelListener *listener, const AVTransEvent &event) +{ + pthread_setname_np(pthread_self(), SEND_CHANNEL_EVENT); + + TRUE_RETURN(listener == nullptr, "input listener is nullptr."); + listener->OnChannelEvent(event); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/av_transport/distributed_av_transport.gni b/av_transport/distributed_av_transport.gni new file mode 100644 index 0000000000000000000000000000000000000000..924f2c7fcd10a23e9f88ed5eef61fed07b22befd --- /dev/null +++ b/av_transport/distributed_av_transport.gni @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +distributedhardwarefwk_path = + "//foundation/distributedhardware/distributed_hardware_fwk" + +distributed_av_transport_path = "${distributedhardwarefwk_path}/av_transport" + +histreamer_path = "//foundation/multimedia/histreamer/engine" + +dsoftbus_path = "//foundation/communication/dsoftbus" + +media_standard_path = "//foundation/multimedia/player_framework" + +drivers_disaplay_path = "//drivers/peripheral/display" + +common_path = "${distributed_av_transport_path}/common" + +engine_path = "${distributed_av_transport_path}/av_trans_engine" + +interface_path = "${distributed_av_transport_path}/interface" + +handler_path = "${distributed_av_transport_path}/av_trans_handler" + +control_center_path = "${distributed_av_transport_path}/av_trans_control_center" + +filters_path = "${distributed_av_transport_path}/av_trans_engine/filters" + +dh_fwk_utils_path = "${distributedhardwarefwk_path}/common/utils" + +dh_fwk_services_path = "${distributedhardwarefwk_path}/services" + +dh_fwk_sdk_path = "${distributedhardwarefwk_path}/interfaces/inner_kits" + +plugin_path = "${engine_path}/plugin" + +output_controller_path = "${plugin_path}/plugins/av_trans_output/output_control" + +build_flags = [ "-Werror" ] diff --git a/av_transport/interface/i_av_engine_provider.h b/av_transport/interface/i_av_engine_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..c3b5fc7d00c384e2477592b1254efba639266c24 --- /dev/null +++ b/av_transport/interface/i_av_engine_provider.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_I_AV_ENGINE_PROVIDER_H +#define OHOS_I_AV_ENGINE_PROVIDER_H + +#include +#include +#include + +#include "i_av_engine_provider_callback.h" +#include "i_av_receiver_engine.h" +#include "i_av_sender_engine.h" + +namespace OHOS { +namespace DistributedHardware { +/** + * @brief AV engine provider interface. + * + * AV engine provider is used to create or query the sender engines and receiver engines. + * It is loaded and running both on the source and the sink device. + * + * @since 1.0 + * @version 1.0 + */ +class IAVEngineProvider { +public: + /** + * @brief Destructor. + * @return No return value. + */ + virtual ~IAVEngineProvider() = default; + + /** + * @brief Create an av sender engine. + * @param peerDevId id of the remote target device. + * @return Returns a IAVSenderEngine shared pointer if successful, otherwise returns null pointer. + */ + virtual std::shared_ptr CreateAVSenderEngine(const std::string &peerDevId) + { + (void)peerDevId; + return nullptr; + } + + /** + * @brief Get the av sender engine list. + * @return Returns the av sender engine list if successful, otherwise returns empty vector. + */ + virtual std::vector> GetAVSenderEngineList() + { + std::vector> list; + return list; + } + + /** + * @brief Create an av receiver engine. + * @param peerDevId id of the remote target device. + * @return Returns a IAVReceiverEngine shared pointer if successful, otherwise returns null pointer. + */ + virtual std::shared_ptr CreateAVReceiverEngine(const std::string &peerDevId) + { + (void)peerDevId; + return nullptr; + } + + /** + * @brief Get the av receiver engine list. + * @return Returns the av receiver engine list if successful, otherwise returns empty vector. + */ + virtual std::vector> GetAVReceiverEngineList() + { + std::vector> list; + return list; + } + + /** + * @brief Register interface callback to the engine provider. + * @param callback interface callback. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t RegisterProviderCallback(const std::shared_ptr &callback) + { + (void)callback; + return DH_AVT_SUCCESS; + } +}; +} // DistributedHardware +} // OHOS +#endif // OHOS_I_AV_ENGINE_PROVIDER_H \ No newline at end of file diff --git a/av_transport/interface/i_av_engine_provider_callback.h b/av_transport/interface/i_av_engine_provider_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..f7ba3872f77cf48231ac39e89fe0937d7b533f20 --- /dev/null +++ b/av_transport/interface/i_av_engine_provider_callback.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_I_AV_ENGINE_PROVIDER_CALLBACK_H +#define OHOS_I_AV_ENGINE_PROVIDER_CALLBACK_H + +#include "av_trans_errno.h" +#include "av_trans_types.h" + +namespace OHOS { +namespace DistributedHardware { +/** + * @brief AV engine provider callback interface. + * + * AV engine provider callback is used to receive the engine provider state change events. + * + * @since 1.0 + * @version 1.0 + */ +class IAVEngineProviderCallback { +public: + /** + * @brief Destructor. + * @return No return value. + */ + virtual ~IAVEngineProviderCallback() = default; + + /** + * @brief Report the engine provider state change events to the distributed service. + * @param event event content. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t OnProviderEvent(const AVTransEvent &event) = 0; +}; +} // DistributedHardware +} // OHOS +#endif // OHOS_I_AV_ENGINE_PROVIDER_CALLBACK_H \ No newline at end of file diff --git a/av_transport/interface/i_av_receiver_engine.h b/av_transport/interface/i_av_receiver_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..7ad79e35ce8e8e3a67c1227b353e57ab76a3dd9a --- /dev/null +++ b/av_transport/interface/i_av_receiver_engine.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_I_AV_RECEIVER_ENGINE_H +#define OHOS_I_AV_RECEIVER_ENGINE_H + +#include +#include + +#include "av_trans_errno.h" +#include "av_trans_message.h" +#include "av_trans_types.h" +#include "i_av_receiver_engine_callback.h" + +namespace OHOS { +namespace DistributedHardware { +/** + * @brief AV receiver engine interface. + * + * AV receiver engine is loaded and running on the sink device. + * It supports the management and control the histreamer pipeline, as well as processing of video and audio data. + * + * @since 1.0 + * @version 1.0 + */ +class IAVReceiverEngine { +public: + /** + * @brief Destructor. + * @return No return value. + */ + virtual ~IAVReceiverEngine() = default; + + /** + * @brief Initialize the av receiver engine. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t Initialize() = 0; + + /** + * @brief Release the av receiver engine. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t Release() = 0; + + /** + * @brief Start the pipeline and plugins in the receiver engine. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t Start() = 0; + + /** + * @brief Stop the pipeline and plugins in the receiver engine. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t Stop() = 0; + + /** + * @brief Set parameter to the receiver engine. + * @param tag parameter key. + * @param value parameter value. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t SetParameter(AVTransTag tag, const std::string &value) = 0; + + /** + * @brief Send message to the receiver engine or the source device. + * @param message message content. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t SendMessage(const std::shared_ptr &message) = 0; + + /** + * @brief Create control channel for the receiver engine. + * @param dstDevIds ids of the target devices. + * @param attribution channel attributes. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t CreateControlChannel(const std::vector &dstDevIds, + const ChannelAttribute &attribution) = 0; + + /** + * @brief Register interface callback to the receiver engine. + * @param callback interface callback. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t RegisterReceiverCallback(const std::shared_ptr &callback) = 0; +}; +} // DistributedHardware +} // OHOS +#endif // OHOS_I_AV_RECEIVER_ENGINE_H \ No newline at end of file diff --git a/av_transport/interface/i_av_receiver_engine_callback.h b/av_transport/interface/i_av_receiver_engine_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..c71eb6064a1a0cd61b20af4a5c776205c6c8d3b1 --- /dev/null +++ b/av_transport/interface/i_av_receiver_engine_callback.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_I_AV_RECEIVER_ENGINE_CALLBACK_H +#define OHOS_I_AV_RECEIVER_ENGINE_CALLBACK_H + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_message.h" +#include "av_trans_types.h" + +namespace OHOS { +namespace DistributedHardware { +/** + * @brief AV receiver engine callback interface. + * + * AV receiver engine callback is used to receive the engine state change events, + * message notification and available buffer data. + * + * @since 1.0 + * @version 1.0 + */ +class IAVReceiverEngineCallback { +public: + /** + * @brief Destructor. + * @return No return value. + */ + virtual ~IAVReceiverEngineCallback() = default; + + /** + * @brief Report the engine state change events to the distributed service. + * @param event event content. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t OnReceiverEvent(const AVTransEvent &event) = 0; + + /** + * @brief Report the engine message to the distributed service. + * @param message message content. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t OnMessageReceived(const std::shared_ptr &message) = 0; + + /** + * @brief Report the available buffer data to the distributed service. + * @param buffer buffer data. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t OnDataAvailable(const std::shared_ptr &buffer) = 0; +}; +} // DistributedHardware +} // OHOS +#endif // OHOS_I_AV_RECEIVER_ENGINE_CALLBACK_H \ No newline at end of file diff --git a/av_transport/interface/i_av_sender_engine.h b/av_transport/interface/i_av_sender_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..ac2067eb5f9b45d85370c1d22402ba53fe0d70d6 --- /dev/null +++ b/av_transport/interface/i_av_sender_engine.h @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_I_AV_SENDER_ENGINE_H +#define OHOS_I_AV_SENDER_ENGINE_H + +#include +#include + +#include "av_trans_buffer.h" +#include "av_trans_errno.h" +#include "av_trans_message.h" +#include "av_trans_types.h" +#include "i_av_sender_engine_callback.h" + +namespace OHOS { +namespace DistributedHardware { +/** + * @brief AV sender engine interface. + * + * AV sender engine is loaded and running on the source device. + * It supports the management and control the histreamer pipeline, as well as processing of video and audio data. + * + * @since 1.0 + * @version 1.0 + */ +class IAVSenderEngine { +public: + /** + * @brief Destructor. + * @return No return value. + */ + virtual ~IAVSenderEngine() = default; + + /** + * @brief Initialize the av sender engine. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t Initialize() = 0; + + /** + * @brief Release the av sender engine. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t Release() = 0; + + /** + * @brief Start the pipeline and plugins in the sender engine. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t Start() = 0; + + /** + * @brief Stop the pipeline and plugins in the sender engine. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t Stop() = 0; + + /** + * @brief Push video or audio data to the sender engine. + * @param buffer video or audio buffer data. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t PushData(const std::shared_ptr &buffer) = 0; + + /** + * @brief Set parameter to the sender engine. + * @param tag parameter key. + * @param value parameter value. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t SetParameter(AVTransTag tag, const std::string &value) = 0; + + /** + * @brief Send message to the sender engine or the sink device. + * @param message message content. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t SendMessage(const std::shared_ptr &message) = 0; + + /** + * @brief Create control channel for the sender engine. + * @param dstDevIds ids of the target devices. + * @param attribution channel attributes. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t CreateControlChannel(const std::vector &dstDevIds, + const ChannelAttribute &attribution) = 0; + + /** + * @brief Register interface callback to the sender engine. + * @param callback interface callback. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t RegisterSenderCallback(const std::shared_ptr &callback) = 0; +}; +} // DistributedHardware +} // OHOS +#endif // OHOS_I_AV_SENDER_ENGINE_H \ No newline at end of file diff --git a/av_transport/interface/i_av_sender_engine_callback.h b/av_transport/interface/i_av_sender_engine_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..a5905211f998998e043876c5dd84a11110d49466 --- /dev/null +++ b/av_transport/interface/i_av_sender_engine_callback.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_I_AV_SENDER_ENGINE_CALLBACK_H +#define OHOS_I_AV_SENDER_ENGINE_CALLBACK_H + +#include "av_trans_errno.h" +#include "av_trans_message.h" +#include "av_trans_types.h" + +namespace OHOS { +namespace DistributedHardware { +/** + * @brief AV sender engine callback interface. + * + * AV sender engine callback is used to receive the engine state change events and message notification. + * + * @since 1.0 + * @version 1.0 + */ +class IAVSenderEngineCallback { +public: + /** + * @brief Destructor. + * @return No return value. + */ + virtual ~IAVSenderEngineCallback() = default; + + /** + * @brief Report the engine state change events to the distributed service. + * @param event event content. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t OnSenderEvent(const AVTransEvent &event) = 0; + + /** + * @brief Report the engine message to the distributed service. + * @param message message content. + * @return Returns DH_AVT_SUCCESS(0) if successful, otherwise returns other error code. + */ + virtual int32_t OnMessageReceived(const std::shared_ptr &message) = 0; +}; +} // DistributedHardware +} // OHOS +#endif // OHOS_I_AV_SENDER_ENGINE_CALLBACK_H \ No newline at end of file diff --git a/bundle.json b/bundle.json index 652bc657a83cbc51e9e020006ce8cb5d542219a6..d4b2a75ba570d90f0d41a0bc362fe2092b694389 100644 --- a/bundle.json +++ b/bundle.json @@ -1,13 +1,13 @@ { "name": "@ohos/distributed_hardware_fwk", "description": "distributed hardware framework", - "version": "3.1", + "version": "4.0", "author": {}, "repository": "https://gitee.com/openharmony/distributed_hardware_fwk", "license": "Apache License 2.0", "publishAs": "code-segment", "segment": { - "destPath": "foundation/distributedhardware/distributed_hardware_fwk/" + "destPath": "foundation/distributedhardware/distributed_hardware_fwk" }, "dirs": {}, "scripts": {}, @@ -21,32 +21,35 @@ "adapted_system_type": [ "standard" ], - "rom": "128K", - "ram": "6M", + "rom": "128KB", + "ram": "6144KB", "hisysevent_config": [ "//foundation/distributedhardware/distributed_hardware_fwk/hisysevent.yaml" ], "deps": { "components": [ "dsoftbus", - "distributeddatamgr", "eventhandler", - "hitrace_native", + "hitrace", "c_utils", - "hiviewdfx_hilog_native", - "startup_l2", - "bundle_framework", + "hilog", "samgr", "ipc", "safwk", - "common", - "hisysevent_native", - "ability_runtime", - "device_manager" + "hisysevent", + "device_manager", + "config_policy", + "init", + "kv_store", + "resource_schedule_service", + "graphic_2d", + "histreamer", + "bounds_checking_function" ], "third_party": [ "json", - "googletest" + "googletest", + "openssl" ] }, "build": { @@ -55,15 +58,68 @@ "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", "//foundation/distributedhardware/distributed_hardware_fwk/sa_profile:dhfwk_sa_profile", "//foundation/distributedhardware/distributed_hardware_fwk/sa_profile:dhardware.cfg", - "//foundation/distributedhardware/distributed_hardware_fwk/interfaces/inner_kits:libdhfwk_sdk" + "//foundation/distributedhardware/distributed_hardware_fwk/interfaces/inner_kits:libdhfwk_sdk", + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_engine/av_sender:distributed_av_sender", + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_engine/av_receiver:distributed_av_receiver", + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_handler/histreamer_ability_querier:histreamer_ability_querier" + ], + "inner_kits": [ + { + "type": "so", + "name": "//foundation/distributedhardware/distributed_hardware_fwk/interfaces/inner_kits:libdhfwk_sdk", + "header": { + "header_files": [ + "distributed_hardware_fwk_kit.h", + "distributed_hardware_fwk_kit_paras.h" + ], + "header_base": "//foundation/distributedhardware/distributed_hardware_fwk/interfaces/inner_kits/include" + } + }, + { + "type": "so", + "name": "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_engine/av_sender:distributed_av_sender", + "header": { + "header_files": [], + "header_base": "//foundation/distributedhardware/distributed_hardware_fwk/av_transport" + } + }, + { + "type": "so", + "name": "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_engine/av_receiver:distributed_av_receiver", + "header": { + "header_files": [], + "header_base": "//foundation/distributedhardware/distributed_hardware_fwk/av_transport" + } + }, + { + "type": "so", + "name": "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils", + "header": { + "header_files": [ + "anonymous_string.h", + "dh_utils_hisysevent.h", + "dh_utils_hitrace.h", + "dh_utils_tool.h", + "histreamer_ability_parser.h", + "histreamer_query_tool.h" + ], + "header_base": "//foundation/distributedhardware/distributed_hardware_fwk/utils/include" + } + } ], "test": [ + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_handler/histreamer_ability_querier/test/unittest/common:histreamer_ability_querier_test", + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_control_center/test/unittest:AvTransControlCenterTest", "//foundation/distributedhardware/distributed_hardware_fwk/utils/test/unittest:utils_test", "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice/test/unittest:test", "//foundation/distributedhardware/distributed_hardware_fwk/interfaces/inner_kits/test/unittest:kit_test", "//foundation/distributedhardware/distributed_hardware_fwk/utils/test/fuzztest:fuzztest", "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice/test/fuzztest:fuzztest", - "//foundation/distributedhardware/distributed_hardware_fwk/interfaces/inner_kits/test/fuzztest:fuzztest" + "//foundation/distributedhardware/distributed_hardware_fwk/interfaces/inner_kits/test/fuzztest:fuzztest", + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_engine/filters/test:filter_test", + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_engine/av_receiver/test/unittest:receiver_test", + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_engine/av_sender/test/unittest:sender_test", + "//foundation/distributedhardware/distributed_hardware_fwk/av_transport/av_trans_engine/plugin/test:plugin_test" ] } } diff --git a/common/utils/include/constants.h b/common/utils/include/constants.h index 319daed24ffaa811be47ece17d028877c72d4294..72da5f4703b3fc6fff9094354388f149e3aca953 100644 --- a/common/utils/include/constants.h +++ b/common/utils/include/constants.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,15 +25,18 @@ namespace DistributedHardware { constexpr int32_t ENABLE_TIMEOUT_MS = 1000; constexpr int32_t DISABLE_TIMEOUT_MS = 500; constexpr uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024; + constexpr uint32_t MIN_MESSAGE_LEN = 0; constexpr uint32_t MAX_ID_LEN = 256; constexpr uint32_t MAX_TOPIC_SIZE = 128; constexpr uint32_t MAX_LISTENER_SIZE = 256; constexpr uint32_t MAX_COMP_SIZE = 128; constexpr uint32_t MAX_DB_RECORD_SIZE = 10000; constexpr uint32_t MAX_ONLINE_DEVICE_SIZE = 10000; + constexpr int32_t MODE_ENABLE = 0; + constexpr int32_t MODE_DISABLE = 1; + constexpr uint32_t MAX_SWITCH_SIZE = 256; + const std::string LOW_LATENCY_KEY = "identity"; const std::u16string DHMS_STUB_INTERFACE_TOKEN = u"ohos.distributedhardware.accessToken"; - const std::string COMPONENTSLOAD_PROFILE_PATH = - R"(/vendor/etc/distributedhardware/distributed_hardware_components_cfg.json)"; const std::string APP_ID = "dtbhardware_manager_service"; const std::string GLOBAL_CAPABILITY_ID = "global_capability_info"; const std::string GLOBAL_VERSION_ID = "global_version_info"; @@ -58,6 +61,17 @@ namespace DistributedHardware { const std::string DH_COMPONENT_TYPE = "dhType"; const std::string DH_COMPONENT_SINK_VER = "version"; const std::string DH_COMPONENT_DEFAULT_VERSION = "1.0"; + const std::string LOW_LATENCY_ENABLE = "low_latency_enable"; + constexpr const char *DO_RECOVER = "DoRecover"; + constexpr const char *SEND_ONLINE = "SendOnLine"; + constexpr const char *DISABLE_TASK_INNER = "DisableTask"; + constexpr const char *ENABLE_TASK_INNER = "EnableTask"; + constexpr const char *OFFLINE_TASK_INNER = "OffLineTask"; + constexpr const char *TRIGGER_TASK = "TriggerTask"; + constexpr const char *EVENT_RUN = "EventRun"; + constexpr const char *START_EVENT = "StartEvent"; + constexpr const char *COMPONENTSLOAD_PROFILE_PATH = + "etc/distributedhardware/distributed_hardware_components_cfg.json"; } // namespace DistributedHardware } // namespace OHOS #endif diff --git a/common/utils/include/dhardware_ipc_interface_code.h b/common/utils/include/dhardware_ipc_interface_code.h new file mode 100644 index 0000000000000000000000000000000000000000..4027e585aa1bfb3b1daa027b95a726ebd561fc74 --- /dev/null +++ b/common/utils/include/dhardware_ipc_interface_code.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DHARDWARE_IPC_INTERFACE_CODE_H +#define OHOS_DHARDWARE_IPC_INTERFACE_CODE_H + +#include + +/* SAID: 4801 */ +namespace OHOS { +namespace DistributedHardware { +enum class DHMsgInterfaceCode : uint32_t { + REG_PUBLISHER_LISTNER = 1, + UNREG_PUBLISHER_LISTENER = 2, + PUBLISH_MESSAGE = 3, + INIT_CTL_CEN = 4, + RELEASE_CTL_CEN = 5, + CREATE_CTL_CEN_CHANNEL = 6, + NOTIFY_AV_EVENT = 7, + REGISTER_CTL_CEN_CALLBACK = 8, + QUERY_LOCAL_SYS_SPEC = 9, +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif \ No newline at end of file diff --git a/common/utils/include/distributed_hardware_errno.h b/common/utils/include/distributed_hardware_errno.h index 5a8a55c3a018984c31119ba1ed5008932e5558da..0bc24ce9e41f247404ce9d24a84dcfdd508dff49 100644 --- a/common/utils/include/distributed_hardware_errno.h +++ b/common/utils/include/distributed_hardware_errno.h @@ -77,6 +77,7 @@ namespace DistributedHardware { constexpr int32_t ERR_DH_FWK_LOADER_CONFIG_JSON_INVALID = -10601; constexpr int32_t ERR_DH_FWK_LOADER_GET_LOCAL_VERSION_FAIL = -10602; constexpr int32_t ERR_DH_FWK_LOADER_DLCLOSE_FAIL = -10603; + constexpr int32_t ERR_DH_FWK_LOADER_PROFILE_PATH_IS_NULL = -10604; /* Task errno, range: [-10700, -10799] */ constexpr int32_t ERR_DH_FWK_TASK_TIMEOUT = -10700; diff --git a/common/utils/include/iav_trans_control_center_callback.h b/common/utils/include/iav_trans_control_center_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..bcbe6338f28ed5bd4d945efd8464c0c979fbd7f3 --- /dev/null +++ b/common/utils/include/iav_trans_control_center_callback.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_I_AV_TRANSPORT_CONTROL_CENTER_CALLBACK_H +#define OHOS_I_AV_TRANSPORT_CONTROL_CENTER_CALLBACK_H + +#include "iremote_broker.h" + +#include "av_sync_utils.h" +#include "av_trans_errno.h" +#include "av_trans_types.h" + +namespace OHOS { +namespace DistributedHardware { +class IAVTransControlCenterCallback : public IRemoteBroker { +public: + virtual int32_t SetParameter(AVTransTag tag, const std::string &value) = 0; + virtual int32_t SetSharedMemory(const AVTransSharedMemory &memory) = 0; + virtual int32_t Notify(const AVTransEvent &event) = 0; + + enum class Message : uint32_t { + SET_PARAMETER = 1, + SET_SHARED_MEMORY = 2, + NOTIFY_AV_EVENT = 3 + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.IAVTransControlCenterCallback"); +}; +} +} +#endif \ No newline at end of file diff --git a/common/utils/include/idistributed_hardware.h b/common/utils/include/idistributed_hardware.h index 84a4a4b6dc3e15030947dc5ea663dba2370b24a7..c919ae238d565f495d3bb521be2d012f8184d5a5 100644 --- a/common/utils/include/idistributed_hardware.h +++ b/common/utils/include/idistributed_hardware.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,6 +23,8 @@ #include "iremote_broker.h" #include "device_type.h" +#include "distributed_hardware_fwk_kit_paras.h" +#include "iav_trans_control_center_callback.h" #include "ipublisher_listener.h" namespace OHOS { @@ -35,12 +37,14 @@ public: virtual int32_t RegisterPublisherListener(const DHTopic topic, const sptr &listener) = 0; virtual int32_t UnregisterPublisherListener(const DHTopic topic, const sptr &listener) = 0; virtual int32_t PublishMessage(const DHTopic topic, const std::string &msg) = 0; -public: - enum class Message : uint32_t { - REG_PUBLISHER_LISTNER = 1, - UNREG_PUBLISHER_LISTENER = 2, - PUBLISH_MESSAGE = 3 - }; + virtual std::string QueryLocalSysSpec(QueryLocalSysSpecType spec) = 0; + + virtual int32_t InitializeAVCenter(const TransRole &transRole, int32_t &engineId) = 0; + virtual int32_t ReleaseAVCenter(int32_t engineId) = 0; + virtual int32_t CreateControlChannel(int32_t engineId, const std::string &peerDevId) = 0; + virtual int32_t NotifyAVCenter(int32_t engineId, const AVTransEvent &event) = 0; + virtual int32_t RegisterCtlCenterCallback(int32_t engineId, + const sptr &callback) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/utils/include/ipublisher_listener.h b/common/utils/include/ipublisher_listener.h index 5ac03510d990c0ff60b04cfbdb0388f205207481..5a4938ecd66b8da2d8cb420792890a706250b7aa 100644 --- a/common/utils/include/ipublisher_listener.h +++ b/common/utils/include/ipublisher_listener.h @@ -34,8 +34,10 @@ enum class DHTopic : uint32_t { TOPIC_STOP_DSCREEN = 3, // publish device offline message TOPIC_DEV_OFFLINE = 4, + // publish low latency message + TOPIC_LOW_LATENCY = 5, // Topic max border, not use for real topic - TOPIC_MAX = 5 + TOPIC_MAX = 6 }; class IPublisherListener : public IRemoteBroker { diff --git a/distributedhardwarefwk.gni b/distributedhardwarefwk.gni index 9bbb95386f553844788b8b5bf8f8bd1a27ed3c28..aed3ee1b85865d19de1ce1205bb7cade6f937c31 100644 --- a/distributedhardwarefwk.gni +++ b/distributedhardwarefwk.gni @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -22,4 +22,14 @@ services_path = "${distributedhardwarefwk_path}/services" innerkits_path = "${distributedhardwarefwk_path}/interfaces/inner_kits" +av_trans_path = "${distributedhardwarefwk_path}/av_transport" + +av_center_svc_path = "${av_trans_path}/av_trans_control_center/services" + +av_center_kits_path = "${av_trans_path}/av_trans_control_center/inner_kits" + build_flags = [ "-Werror" ] + +declare_args() { + dhardware_low_latency = false +} diff --git a/figures/distributedhardwarefwk_arch.png b/figures/distributedhardwarefwk_arch.png index 85998d82d54b9c88f88c4f7b769cf8189e79ff89..9dbb7d88595f153b003bccdddc6a938d31ecb9f6 100644 Binary files a/figures/distributedhardwarefwk_arch.png and b/figures/distributedhardwarefwk_arch.png differ diff --git a/hisysevent.yaml b/hisysevent.yaml index 3e4eacf790f0eaec15a0a00d767c1144542ad3d6..ea418990d96f286f66ad6c5c46a74233f31940fb 100644 --- a/hisysevent.yaml +++ b/hisysevent.yaml @@ -62,7 +62,7 @@ DHFWK_EXIT_END: DHFWK_RELEASE_FAIL: __BASE: {type: FAULT, level: CRITICAL, desc: dhfwk component dlclose failed} - DHTYPE: {type: STRING, desc: dhtype} + DHTYPE: {type: STRING, desc: the dhardware module which release fail} ERR_CODE: {type: INT32, desc: dlclose failed result} ERR_MSG: {type: STRING, desc: dhfwk component dlclose failed} diff --git a/interfaces/inner_kits/BUILD.gn b/interfaces/inner_kits/BUILD.gn index 3c78bfa807ba572ff540a152aa933d3647fa9a85..a79b85d5a23d8f3b0d34b3e3d2e6372191d3e0a1 100644 --- a/interfaces/inner_kits/BUILD.gn +++ b/interfaces/inner_kits/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -17,8 +17,9 @@ import( ohos_shared_library("libdhfwk_sdk") { include_dirs = [ - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", + "${av_center_kits_path}/include", + "${av_trans_path}/common/include", + "${av_trans_path}/interface", "${innerkits_path}/include", "${innerkits_path}/include/ipc", "${common_path}/log/include", @@ -30,6 +31,8 @@ ohos_shared_library("libdhfwk_sdk") { ] sources = [ + "${av_center_kits_path}/src/av_trans_control_center_callback.cpp", + "${av_center_kits_path}/src/av_trans_control_center_callback_stub.cpp", "${innerkits_path}/src/distributed_hardware_fwk_kit.cpp", "${innerkits_path}/src/ipc/dhfwk_sa_manager.cpp", "${innerkits_path}/src/ipc/distributed_hardware_proxy.cpp", @@ -39,7 +42,6 @@ ohos_shared_library("libdhfwk_sdk") { deps = [ "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", "${utils_path}:distributedhardwareutils", - "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", ] defines = [ @@ -51,6 +53,7 @@ ohos_shared_library("libdhfwk_sdk") { external_deps = [ "c_utils:utils", "ipc:ipc_core", + "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/interfaces/inner_kits/include/distributed_hardware_fwk_kit.h b/interfaces/inner_kits/include/distributed_hardware_fwk_kit.h index bcd53d91d4d226baa555a28acaae03ced6f85518..d92ccf082ebff62d65be9e353343ceafb39aad67 100644 --- a/interfaces/inner_kits/include/distributed_hardware_fwk_kit.h +++ b/interfaces/inner_kits/include/distributed_hardware_fwk_kit.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,6 +23,7 @@ #include #include "refbase.h" +#include "distributed_hardware_fwk_kit_paras.h" #include "ipublisher_listener.h" #include "idistributed_hardware.h" @@ -34,16 +35,116 @@ namespace OHOS { namespace DistributedHardware { class DistributedHardwareFwkKit final { public: + /** + * @brief Constructor. + * @return No return value. + */ API_EXPORT DistributedHardwareFwkKit(); + + /** + * @brief Destructor. + * @return No return value. + */ API_EXPORT ~DistributedHardwareFwkKit(); + + /** + * @brief Register publisher listener. + * @param topic Distributed hardware topic. + * @param listener Publisher listener. + * @return Returns 0 if success. + */ API_EXPORT int32_t RegisterPublisherListener(const DHTopic topic, sptr listener); + + /** + * @brief Unregister publisher listener. + * @param topic Distributed hardware topic. + * @param listener Publisher listener. + * @return Returns 0 if success. + */ API_EXPORT int32_t UnregisterPublisherListener(const DHTopic topic, sptr listener); + + /** + * @brief Publish message. + * @param topic Distributed hardware topic. + * @param message Message content. + * @return Returns 0 if success. + */ API_EXPORT int32_t PublishMessage(const DHTopic topic, const std::string &message); + /** + * @brief Distributed hardware framework online. + * @param isOnLine Online or not. + * @return No return value. + */ void OnDHFWKOnLine(bool isOnLine); + + /** + * @brief Query Local system specifications + * + * @param spec specification type + * @return specification in string format + */ + API_EXPORT std::string QueryLocalSysSpec(QueryLocalSysSpecType spec); + + /** + * @brief Initialize distributed av control center + * + * @param transRole transport role, eg. sender or receiver + * @param engineId transport engine id + * @return Returns 0 if success. + */ + API_EXPORT int32_t InitializeAVCenter(const TransRole &transRole, int32_t &engineId); + + /** + * @brief Release distributed av control center + * + * @param engineId transport engine id + * @return Returns 0 if success. + */ + API_EXPORT int32_t ReleaseAVCenter(int32_t engineId); + + /** + * @brief Create control channel betweent the local and the remote av control center + * + * @param engineId transport engine id + * @param peerDevId the peer device id + * @return Returns 0 if success. + */ + API_EXPORT int32_t CreateControlChannel(int32_t engineId, const std::string &peerDevId); + + /** + * @brief Notify event from transport engine to av control center + * + * @param engineId transport engine id + * @param event the event content + * @return Returns 0 if success. + */ + API_EXPORT int32_t NotifyAVCenter(int32_t engineId, const AVTransEvent &event); + + /** + * @brief Register av control center callback. + * + * @param engineId transport engine id + * @param callback av control center callback. + * @return Returns 0 if success. + */ + API_EXPORT int32_t RegisterCtlCenterCallback(int32_t engineId, const sptr &callback); + private: + /** + * @brief Determine whether the topic is valid. + * @param topic Distributed hardware topic. + * @return Returns true if success. + */ bool IsDHTopicValid(DHTopic topic); + /** + * @brief Determine whether the QueryLocalSysSpecType is valid. + * @param topic Query Local Sys Spec Type. + * @return Returns true if success. + */ + bool IsQueryLocalSysSpecTypeValid(QueryLocalSysSpecType spec); + private: std::mutex listenerMutex_; std::unordered_map>> listenerMap_; diff --git a/interfaces/inner_kits/include/distributed_hardware_fwk_kit_paras.h b/interfaces/inner_kits/include/distributed_hardware_fwk_kit_paras.h new file mode 100644 index 0000000000000000000000000000000000000000..a289e04ce377f6613d2b0c46ed26fe42368fc0d2 --- /dev/null +++ b/interfaces/inner_kits/include/distributed_hardware_fwk_kit_paras.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_FWK_KIT_PARAS_H +#define OHOS_DISTRIBUTED_HARDWARE_FWK_KIT_PARAS_H + +#include + +namespace OHOS { +namespace DistributedHardware { + const std::string KEY_HISTREAMER_VIDEO_ENCODER = "histmVidEnc"; + const std::string KEY_HISTREAMER_VIDEO_DECODER = "histmVidDec"; + const std::string KEY_HISTREAMER_AUDIO_ENCODER = "histmAudEnc"; + const std::string KEY_HISTREAMER_AUDIO_DECODER = "histmAudDec"; + /** + * @brief query local system common specifications, + * such as Audio/Video Encoder/Decoder + */ + enum class QueryLocalSysSpecType : uint32_t { + MIN = 0, + HISTREAMER_AUDIO_ENCODER, + HISTREAMER_AUDIO_DECODER, + HISTREAMER_VIDEO_ENCODER, + HISTREAMER_VIDEO_DECODER, + MAX = 5 + }; +} +} + +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/include/ipc/distributed_hardware_proxy.h b/interfaces/inner_kits/include/ipc/distributed_hardware_proxy.h index bf3b38e59efd72aa97f18e5578f3df87b7eae1d5..14c50bcd3e64487edd8de64155c40e06611df624 100644 --- a/interfaces/inner_kits/include/ipc/distributed_hardware_proxy.h +++ b/interfaces/inner_kits/include/ipc/distributed_hardware_proxy.h @@ -18,6 +18,7 @@ #include +#include "distributed_hardware_fwk_kit_paras.h" #include "iremote_proxy.h" #include "refbase.h" #include "idistributed_hardware.h" @@ -35,6 +36,13 @@ public: int32_t RegisterPublisherListener(const DHTopic topic, const sptr &listener) override; int32_t UnregisterPublisherListener(const DHTopic topic, const sptr &listener) override; int32_t PublishMessage(const DHTopic topic, const std::string &msg) override; + std::string QueryLocalSysSpec(QueryLocalSysSpecType spec) override; + + int32_t InitializeAVCenter(const TransRole &transRole, int32_t &engineId) override; + int32_t ReleaseAVCenter(int32_t engineId) override; + int32_t CreateControlChannel(int32_t engineId, const std::string &peerDevId) override; + int32_t NotifyAVCenter(int32_t engineId, const AVTransEvent &event) override; + int32_t RegisterCtlCenterCallback(int32_t engineId, const sptr &callback) override; private: static inline BrokerDelegator delegator_; diff --git a/interfaces/inner_kits/src/distributed_hardware_fwk_kit.cpp b/interfaces/inner_kits/src/distributed_hardware_fwk_kit.cpp index b55a32a93f7dd459183bbd52c7c9ec5ecda5abaa..3825e89f47c097d249cb5b8c98201b27e8d8fc4d 100644 --- a/interfaces/inner_kits/src/distributed_hardware_fwk_kit.cpp +++ b/interfaces/inner_kits/src/distributed_hardware_fwk_kit.cpp @@ -17,6 +17,7 @@ #include +#include "anonymous_string.h" #include "constants.h" #include "dhfwk_sa_manager.h" #include "distributed_hardware_errno.h" @@ -140,5 +141,88 @@ void DistributedHardwareFwkKit::OnDHFWKOnLine(bool isOnLine) } } } + +bool DistributedHardwareFwkKit::IsQueryLocalSysSpecTypeValid(QueryLocalSysSpecType spec) +{ + return spec > QueryLocalSysSpecType::MIN && spec < QueryLocalSysSpecType::MAX; +} + +std::string DistributedHardwareFwkKit::QueryLocalSysSpec(enum QueryLocalSysSpecType spec) +{ + DHLOGI("Query Local Sys Spec, %d", (uint32_t)spec); + if (!IsQueryLocalSysSpecTypeValid(spec)) { + DHLOGE("Topic invalid, topic: %" PRIu32, (uint32_t)spec); + return ""; + } + + if (DHFWKSAManager::GetInstance().GetDHFWKProxy() == nullptr) { + DHLOGI("DHFWK not online, can not publish message"); + return ""; + } + + return DHFWKSAManager::GetInstance().GetDHFWKProxy()->QueryLocalSysSpec(spec); +} + +int32_t DistributedHardwareFwkKit::InitializeAVCenter(const TransRole &transRole, int32_t &engineId) +{ + DHLOGI("Initialize av control center, transRole: %" PRIu32, (uint32_t)transRole); + + if (DHFWKSAManager::GetInstance().GetDHFWKProxy() == nullptr) { + DHLOGI("DHFWK not online or get proxy failed, can not initializeA av control center"); + return ERR_DH_FWK_POINTER_IS_NULL; + } + + return DHFWKSAManager::GetInstance().GetDHFWKProxy()->InitializeAVCenter(transRole, engineId); +} + +int32_t DistributedHardwareFwkKit::ReleaseAVCenter(int32_t engineId) +{ + DHLOGI("Release av control center, engineId: %" PRId32, engineId); + + if (DHFWKSAManager::GetInstance().GetDHFWKProxy() == nullptr) { + DHLOGI("DHFWK not online or get proxy failed, can not release av control center"); + return ERR_DH_FWK_POINTER_IS_NULL; + } + + return DHFWKSAManager::GetInstance().GetDHFWKProxy()->ReleaseAVCenter(engineId); +} + +int32_t DistributedHardwareFwkKit::CreateControlChannel(int32_t engineId, const std::string &peerDevId) +{ + DHLOGI("Create av control center channel, engineId: %" PRId32 ", peerDevId=%s.", engineId, + GetAnonyString(peerDevId).c_str()); + + if (DHFWKSAManager::GetInstance().GetDHFWKProxy() == nullptr) { + DHLOGI("DHFWK not online or get proxy failed, can not create av control center channel"); + return ERR_DH_FWK_POINTER_IS_NULL; + } + + return DHFWKSAManager::GetInstance().GetDHFWKProxy()->CreateControlChannel(engineId, peerDevId); +} + +int32_t DistributedHardwareFwkKit::NotifyAVCenter(int32_t engineId, const AVTransEvent &event) +{ + DHLOGI("Notify av control center, engineId: %" PRId32 ", event type=%" PRId32, engineId, event.type); + + if (DHFWKSAManager::GetInstance().GetDHFWKProxy() == nullptr) { + DHLOGI("DHFWK not online or get proxy failed, can not notity av control center event."); + return ERR_DH_FWK_POINTER_IS_NULL; + } + + return DHFWKSAManager::GetInstance().GetDHFWKProxy()->NotifyAVCenter(engineId, event); +} + +int32_t DistributedHardwareFwkKit::RegisterCtlCenterCallback(int32_t engineId, + const sptr &callback) +{ + DHLOGI("Register av control center callback. engineId: %" PRId32, engineId); + + if (DHFWKSAManager::GetInstance().GetDHFWKProxy() == nullptr) { + DHLOGI("DHFWK not online or get proxy failed, can not register av control center callback."); + return ERR_DH_FWK_POINTER_IS_NULL; + } + + return DHFWKSAManager::GetInstance().GetDHFWKProxy()->RegisterCtlCenterCallback(engineId, callback); +} } // DistributedHardware } // OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/src/ipc/distributed_hardware_proxy.cpp b/interfaces/inner_kits/src/ipc/distributed_hardware_proxy.cpp index cb54443031adbda5abe02cad501308adc93d094f..f3b7847f924f66672543351da3a1a24db4c63a1f 100644 --- a/interfaces/inner_kits/src/ipc/distributed_hardware_proxy.cpp +++ b/interfaces/inner_kits/src/ipc/distributed_hardware_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,10 +15,13 @@ #include "distributed_hardware_proxy.h" +#include #include #include "anonymous_string.h" +#include "av_trans_errno.h" #include "constants.h" +#include "dhardware_ipc_interface_code.h" #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" #include "nlohmann/json.hpp" @@ -46,7 +49,7 @@ int32_t DistributedHardwareProxy::RegisterPublisherListener(const DHTopic topic, DHLOGE("remote service is null"); return ERR_DH_FWK_SERVICE_REMOTE_IS_NULL; } - if (DHTopic::TOPIC_MIN > topic || topic > DHTopic::TOPIC_MAX) { + if (topic < DHTopic::TOPIC_MIN || topic > DHTopic::TOPIC_MAX) { DHLOGE("Topic is invalid!"); return ERR_DH_FWK_PARA_INVALID; } @@ -67,7 +70,7 @@ int32_t DistributedHardwareProxy::RegisterPublisherListener(const DHTopic topic, DHLOGE("DistributedHardwareProxy write listener failed"); return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; } - int32_t ret = remote->SendRequest((uint32_t)IDistributedHardware::Message::REG_PUBLISHER_LISTNER, + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::REG_PUBLISHER_LISTNER), data, reply, option); if (ret != NO_ERROR) { DHLOGE("Send Request failed, ret: %d", ret); @@ -95,7 +98,7 @@ int32_t DistributedHardwareProxy::UnregisterPublisherListener(const DHTopic topi DHLOGE("remote service is null"); return ERR_DH_FWK_SERVICE_REMOTE_IS_NULL; } - if (DHTopic::TOPIC_MIN > topic || topic > DHTopic::TOPIC_MAX) { + if (topic < DHTopic::TOPIC_MIN || topic > DHTopic::TOPIC_MAX) { DHLOGE("Topic is invalid!"); return ERR_DH_FWK_PARA_INVALID; } @@ -116,7 +119,7 @@ int32_t DistributedHardwareProxy::UnregisterPublisherListener(const DHTopic topi DHLOGE("DistributedHardwareProxy write listener failed"); return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; } - int32_t ret = remote->SendRequest((uint32_t)IDistributedHardware::Message::UNREG_PUBLISHER_LISTENER, + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::UNREG_PUBLISHER_LISTENER), data, reply, option); if (ret != NO_ERROR) { DHLOGE("Send Request failed, ret: %d", ret); @@ -138,7 +141,7 @@ int32_t DistributedHardwareProxy::PublishMessage(const DHTopic topic, const std: DHLOGE("remote service is null"); return ERR_DH_FWK_SERVICE_REMOTE_IS_NULL; } - if (DHTopic::TOPIC_MIN > topic || topic > DHTopic::TOPIC_MAX) { + if (topic < DHTopic::TOPIC_MIN || topic > DHTopic::TOPIC_MAX) { DHLOGE("Topic is invalid!"); return ERR_DH_FWK_PARA_INVALID; } @@ -163,7 +166,7 @@ int32_t DistributedHardwareProxy::PublishMessage(const DHTopic topic, const std: DHLOGE("DistributedHardwareProxy write listener failed"); return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; } - int32_t ret = remote->SendRequest((uint32_t)IDistributedHardware::Message::PUBLISH_MESSAGE, + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::PUBLISH_MESSAGE), data, reply, option); if (ret != NO_ERROR) { DHLOGE("Send Request failed, ret: %d", ret); @@ -177,5 +180,211 @@ int32_t DistributedHardwareProxy::PublishMessage(const DHTopic topic, const std: return ret; } + +std::string DistributedHardwareProxy::QueryLocalSysSpec(QueryLocalSysSpecType spec) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("remote service is null"); + return ""; + } + if (spec < QueryLocalSysSpecType::MIN || spec > QueryLocalSysSpecType::MAX) { + DHLOGE("Sys spec type is invalid!"); + return ""; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + DHLOGE("WriteInterfaceToken fail!"); + return ""; + } + if (!data.WriteUint32((uint32_t)spec)) { + DHLOGE("DistributedHardwareProxy write local sys spec failed"); + return ""; + } + + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::QUERY_LOCAL_SYS_SPEC), + data, reply, option); + if (ret != NO_ERROR) { + DHLOGE("Send Request failed, ret: %d", ret); + return ""; + } + + std::string specStr = reply.ReadString(); + DHLOGI("Query local sys spec %" PRIu32 ", get: %s", (uint32_t)spec, specStr.c_str()); + return specStr; +} + +int32_t DistributedHardwareProxy::InitializeAVCenter(const TransRole &transRole, int32_t &engineId) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("remote service is null"); + return ERR_DH_AVT_SERVICE_REMOTE_IS_NULL; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + DHLOGE("WriteInterfaceToken fail!"); + return ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL; + } + if (!data.WriteUint32((uint32_t)transRole)) { + DHLOGE("Write trans role failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::INIT_CTL_CEN), data, reply, option); + if (ret != NO_ERROR) { + DHLOGE("Send Request failed, ret: %d", ret); + return ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL; + } + engineId = reply.ReadInt32(); + + return reply.ReadInt32(); +} + +int32_t DistributedHardwareProxy::ReleaseAVCenter(int32_t engineId) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("remote service is null"); + return ERR_DH_AVT_SERVICE_REMOTE_IS_NULL; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option = { MessageOption::TF_ASYNC }; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + DHLOGE("WriteInterfaceToken fail!"); + return ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL; + } + if (!data.WriteInt32(engineId)) { + DHLOGE("Write engine id failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::RELEASE_CTL_CEN), data, reply, option); + if (ret != NO_ERROR) { + DHLOGE("Send Request failed, ret: %d", ret); + return ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL; + } + + return reply.ReadInt32(); +} + +int32_t DistributedHardwareProxy::CreateControlChannel(int32_t engineId, const std::string &peerDevId) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("remote service is null"); + return ERR_DH_AVT_SERVICE_REMOTE_IS_NULL; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option = { MessageOption::TF_ASYNC }; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + DHLOGE("WriteInterfaceToken fail!"); + return ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL; + } + if (!data.WriteInt32(engineId)) { + DHLOGE("Write engine id failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteString(peerDevId)) { + DHLOGE("Write peerDevId failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::CREATE_CTL_CEN_CHANNEL), + data, reply, option); + if (ret != NO_ERROR) { + DHLOGE("Send Request failed, ret: %d", ret); + return ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL; + } + + return reply.ReadInt32(); +} + +int32_t DistributedHardwareProxy::NotifyAVCenter(int32_t engineId, const AVTransEvent &event) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("remote service is null"); + return ERR_DH_AVT_SERVICE_REMOTE_IS_NULL; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option = { MessageOption::TF_ASYNC }; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + DHLOGE("WriteInterfaceToken fail!"); + return ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL; + } + if (!data.WriteInt32(engineId)) { + DHLOGE("Write engine id failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteUint32((uint32_t)event.type)) { + DHLOGE("Write event type failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteString(event.content)) { + DHLOGE("Write event content failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteString(event.peerDevId)) { + DHLOGE("Write event peerDevId failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::NOTIFY_AV_EVENT), data, reply, option); + if (ret != NO_ERROR) { + DHLOGE("Send Request failed, ret: %d", ret); + return ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL; + } + + return reply.ReadInt32(); +} + +int32_t DistributedHardwareProxy::RegisterCtlCenterCallback(int32_t engineId, + const sptr &callback) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("remote service is null"); + return ERR_DH_AVT_SERVICE_REMOTE_IS_NULL; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + DHLOGE("WriteInterfaceToken fail!"); + return ERR_DH_AVT_SERVICE_WRITE_TOKEN_FAIL; + } + if (!data.WriteInt32(engineId)) { + DHLOGE("Write engine id failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + if (!data.WriteRemoteObject(callback->AsObject())) { + DHLOGE("Write callback failed"); + return ERR_DH_AVT_SERVICE_WRITE_INFO_FAIL; + } + int32_t ret = remote->SendRequest(static_cast(DHMsgInterfaceCode::REGISTER_CTL_CEN_CALLBACK), + data, reply, option); + if (ret != NO_ERROR) { + DHLOGE("Send Request failed, ret: %d", ret); + return ERR_DH_AVT_SERVICE_IPC_SEND_REQUEST_FAIL; + } + + return reply.ReadInt32(); +} } // namespace DistributedHardware -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/src/ipc/publisher_listener_stub.cpp b/interfaces/inner_kits/src/ipc/publisher_listener_stub.cpp index 9296ad6a8a2434bf1ee2ee47ecb6af63e7f61456..db73fa8a6c3876d5174ca8f9d6f848910ab53e3d 100644 --- a/interfaces/inner_kits/src/ipc/publisher_listener_stub.cpp +++ b/interfaces/inner_kits/src/ipc/publisher_listener_stub.cpp @@ -39,8 +39,8 @@ int32_t PublisherListenerStub::OnRemoteRequest( IPublisherListener::Message msgCode = static_cast(code); switch (msgCode) { case IPublisherListener::Message::ON_MESSAGE: { - DHTopic topic = (DHTopic)data.ReadUint32(); - if (DHTopic::TOPIC_MIN > topic || topic > DHTopic::TOPIC_MAX) { + DHTopic topic = static_cast(data.ReadUint32()); + if (topic < DHTopic::TOPIC_MIN || topic > DHTopic::TOPIC_MAX) { DHLOGE("Topic is invalid!"); return ERR_INVALID_DATA; } diff --git a/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer/BUILD.gn b/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer/BUILD.gn index 815c6b4fbd180f211ba3a61b5fbb767bcbbb974e..68c2c5b60be03f69740e4ef97e8c8c08dd72c1db 100644 --- a/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer/BUILD.gn +++ b/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,12 +20,12 @@ import( ##############################fuzztest########################################## ohos_fuzztest("DistributedHardwareFwkKitFuzzTest") { module_out_path = "distributed_hardware_fwk/distributedhardwarefwkkit" - fuzz_config_file = "//foundation/distributedhardware/distributed_hardware_fwk/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer" + fuzz_config_file = + "${innerkits_path}/test/fuzztest/distributedhardwarefwkkit_fuzzer" include_dirs = [ + "${av_trans_path}/common/include", "include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", "${utils_path}/include", "${utils_path}/include/log", "${common_path}/utils/include", @@ -54,6 +54,7 @@ ohos_fuzztest("DistributedHardwareFwkKitFuzzTest") { external_deps = [ "c_utils:utils", "ipc:ipc_core", + "safwk:system_ability_fwk", ] } diff --git a/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer/distributedhardwarefwkkit_fuzzer.cpp b/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer/distributedhardwarefwkkit_fuzzer.cpp index 9834b50c5f38b7111580eded9c179973b4dd6b6a..7a5d1ac9c6848a3a28e302224133e501f46900b0 100644 --- a/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer/distributedhardwarefwkkit_fuzzer.cpp +++ b/interfaces/inner_kits/test/fuzztest/distributedhardwarefwkkit_fuzzer/distributedhardwarefwkkit_fuzzer.cpp @@ -48,7 +48,7 @@ void TestPublisherListener::OnMessage(const DHTopic topic, const std::string &me void DistributedHardwareFwkKitFuzzTest(const uint8_t *data, size_t size) { - if ((data == nullptr) || (size <= 0)) { + if ((data == nullptr) || (size == 0)) { return; } diff --git a/interfaces/inner_kits/test/unittest/BUILD.gn b/interfaces/inner_kits/test/unittest/BUILD.gn index 0e8c34a6509874b5b548c2a9a3769bd8ecfd978a..839dbd1faf0db5eba178a75bc31c523a4ea8a8de 100644 --- a/interfaces/inner_kits/test/unittest/BUILD.gn +++ b/interfaces/inner_kits/test/unittest/BUILD.gn @@ -14,6 +14,10 @@ group("kit_test") { testonly = true - deps = - [ "common/distributedhardwarefwkkit:distributed_hardware_fwk_kit_test" ] + deps = [ + "common/distributedhardwarefwkkit:distributed_hardware_fwk_kit_test", + "common/ipc/dhfwk_sa_manager:dhfwk_sa_manager_test", + "common/ipc/distributed_hardware_proxy:DistributedHardwareProxyTest", + "common/ipc/publisher_listener_stub:PublisherListenerStubTest", + ] } diff --git a/interfaces/inner_kits/test/unittest/common/distributedhardwarefwkkit/BUILD.gn b/interfaces/inner_kits/test/unittest/common/distributedhardwarefwkkit/BUILD.gn index 88a2f53a71de27102d6b7c971cc0bb39fb0f7cdf..38d5246dbc5df2f751b8fe507db1190c03b692fe 100644 --- a/interfaces/inner_kits/test/unittest/common/distributedhardwarefwkkit/BUILD.gn +++ b/interfaces/inner_kits/test/unittest/common/distributedhardwarefwkkit/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,9 +20,8 @@ module_out_path = "distributed_hardware_fwk/distributed_hardware_fwk_kit_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ + "${av_trans_path}/common/include", "include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", "${utils_path}/include", "${utils_path}/include/log", "${common_path}/utils/include", @@ -54,6 +53,7 @@ ohos_unittest("DistributedHardwareFwkKitTest") { external_deps = [ "c_utils:utils", "ipc:ipc_core", + "safwk:system_ability_fwk", ] } diff --git a/interfaces/inner_kits/test/unittest/common/distributedhardwarefwkkit/src/distributed_hardware_fwk_kit_test.cpp b/interfaces/inner_kits/test/unittest/common/distributedhardwarefwkkit/src/distributed_hardware_fwk_kit_test.cpp index ba667792bd226da12443a2d511674edfa43bf8a5..8157ea49bbce848c225c4c3b66836a23b6e96e94 100644 --- a/interfaces/inner_kits/test/unittest/common/distributedhardwarefwkkit/src/distributed_hardware_fwk_kit_test.cpp +++ b/interfaces/inner_kits/test/unittest/common/distributedhardwarefwkkit/src/distributed_hardware_fwk_kit_test.cpp @@ -20,12 +20,12 @@ #include #include -#include "iservice_registry.h" -#include "system_ability_definition.h" - +#include "distributed_hardware_errno.h" +#include "dhfwk_sa_manager.h" #include "distributed_hardware_fwk_kit.h" #include "distributed_hardware_log.h" -#include "distributed_hardware_errno.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" using OHOS::DistributedHardware::DHTopic; @@ -73,7 +73,13 @@ uint32_t DistributedHardwareFwkKitTest::TestPublisherListener::GetTopicMsgCnt(co return msgCnts_[topic]; } -HWTEST_F(DistributedHardwareFwkKitTest, RegisterListener01, testing::ext::TestSize.Level0) +/** + * @tc.name: RegisterPublisherListener_001 + * @tc.desc: Verify the RegisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, RegisterPublisherListener_001, testing::ext::TestSize.Level0) { sptr listener1 = new TestPublisherListener(); int32_t ret = dhfwkPtr_->RegisterPublisherListener(DHTopic::TOPIC_START_DSCREEN, listener1); @@ -103,5 +109,131 @@ HWTEST_F(DistributedHardwareFwkKitTest, RegisterListener01, testing::ext::TestSi ret = dhfwkPtr_->UnregisterPublisherListener(DHTopic::TOPIC_DEV_OFFLINE, listener4); EXPECT_EQ(DH_FWK_SUCCESS, ret); } + +/** + * @tc.name: PublishMessage_001 + * @tc.desc: Verify the PublishMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, PublishMessage_001, testing::ext::TestSize.Level0) +{ + uint32_t invalid = 7; + DHTopic topic = static_cast(invalid); + std::string message; + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, dhfwkPtr_->PublishMessage(topic, message)); +} + +/** + * @tc.name: PublishMessage_002 + * @tc.desc: Verify the PublishMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, PublishMessage_002, testing::ext::TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + std::string message; + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, dhfwkPtr_->PublishMessage(topic, message)); +} + +/** + * @tc.name: PublishMessage_003 + * @tc.desc: Verify the PublishMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, PublishMessage_003, testing::ext::TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + std::string message = "TOPIC_STOP_DSCREEN"; + EXPECT_EQ(ERR_DH_FWK_PUBLISH_MSG_FAILED, dhfwkPtr_->PublishMessage(topic, message)); +} + +/** + * @tc.name: PublishMessage_004 + * @tc.desc: Verify the PublishMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, PublishMessage_004, testing::ext::TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + std::string message; + uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024 + 10; + message.resize(MAX_MESSAGE_LEN); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, dhfwkPtr_->PublishMessage(topic, message)); +} + +/** + * @tc.name: OnDHFWKOnLine_001 + * @tc.desc: Verify the OnDHFWKOnLine function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, OnDHFWKOnLine_001, testing::ext::TestSize.Level0) +{ + bool isOnLine = true; + dhfwkPtr_->OnDHFWKOnLine(isOnLine); + EXPECT_EQ(nullptr, DHFWKSAManager::GetInstance().GetDHFWKProxy()); +} + +/** + * @tc.name: RegisterPublisherListener_002 + * @tc.desc: Verify the RegisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, RegisterPublisherListener_002, testing::ext::TestSize.Level0) +{ + uint32_t invalid = 8; + DHTopic topic = static_cast(invalid); + sptr listener = nullptr; + int32_t ret = dhfwkPtr_->RegisterPublisherListener(topic, listener); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + +/** + * @tc.name: RegisterPublisherListener_003 + * @tc.desc: Verify the RegisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, RegisterPublisherListener_003, testing::ext::TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + sptr listener = nullptr; + int32_t ret = dhfwkPtr_->RegisterPublisherListener(topic, listener); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: UnregisterPublisherListener_001 + * @tc.desc: Verify the UnregisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, UnregisterPublisherListener_001, testing::ext::TestSize.Level0) +{ + uint32_t invalid = 8; + DHTopic topic = static_cast(invalid); + sptr listener = nullptr; + int32_t ret = dhfwkPtr_->UnregisterPublisherListener(topic, listener); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + +/** + * @tc.name: UnregisterPublisherListener_002 + * @tc.desc: Verify the UnregisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareFwkKitTest, UnregisterPublisherListener_002, testing::ext::TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + sptr listener = nullptr; + int32_t ret = dhfwkPtr_->UnregisterPublisherListener(topic, listener); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/BUILD.gn b/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..63b7f2bdaf5910c2badf09d8835e75c3aee17328 --- /dev/null +++ b/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/dhfwk_sa_manager_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${av_trans_path}/common/include", + "include", + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "${common_path}/log/include", + "${innerkits_path}/include", + "${innerkits_path}/include/ipc", + "//third_party/json/include", + ] +} + +ohos_unittest("DhfwkSaManagerTest") { + module_out_path = module_out_path + + sources = [ "src/dhfwk_sa_manager_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${innerkits_path}:libdhfwk_sdk", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DhfwkSaManagerTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("dhfwk_sa_manager_test") { + testonly = true + deps = [ ":DhfwkSaManagerTest" ] +} diff --git a/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/include/dhfwk_sa_manager_test.h b/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/include/dhfwk_sa_manager_test.h new file mode 100644 index 0000000000000000000000000000000000000000..94ddc194520a6337f9fc0e7c6a7bbbc3ae18e4cb --- /dev/null +++ b/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/include/dhfwk_sa_manager_test.h @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DHFWK_SA_MANAGER_TEST_H +#define OHOS_DHFWK_SA_MANAGER_TEST_H + +#include +#include +#include + +#include + +#include "distributed_hardware_errno.h" +#include "idistributed_hardware.h" +#define private public +#include "dhfwk_sa_manager.h" +#undef private + +namespace OHOS { +namespace DistributedHardware { +class DHFWKSAManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp(); + virtual void TearDown(); +}; + +class MockIDistributedHardware : public IDistributedHardware { +public: +sptr AsObject() +{ + return nullptr; +} + +int32_t RegisterPublisherListener(const DHTopic topic, const sptr &listener) +{ + (void)topic; + (void)listener; + return DH_FWK_SUCCESS; +} + +int32_t UnregisterPublisherListener(const DHTopic topic, const sptr &listener) +{ + (void)topic; + (void)listener; + return DH_FWK_SUCCESS; +} + +int32_t PublishMessage(const DHTopic topic, const std::string &msg) +{ + (void)topic; + (void)msg; + return DH_FWK_SUCCESS; +} + +std::string QueryLocalSysSpec(QueryLocalSysSpecType spec) +{ + (void)spec; + return 0; +} + +int32_t InitializeAVCenter(const TransRole &transRole, int32_t &engineId) +{ + (void)transRole; + (void)engineId; + return DH_FWK_SUCCESS; +} + +int32_t ReleaseAVCenter(int32_t engineId) +{ + (void)engineId; + return DH_FWK_SUCCESS; +} + +int32_t CreateControlChannel(int32_t engineId, const std::string &peerDevId) +{ + (void)engineId; + (void)peerDevId; + return DH_FWK_SUCCESS; +} + +int32_t NotifyAVCenter(int32_t engineId, const AVTransEvent &event) +{ + (void)engineId; + (void)event; + return DH_FWK_SUCCESS; +} + +int32_t RegisterCtlCenterCallback(int32_t engineId, const sptr &callback) +{ + (void)engineId; + (void)callback; + return DH_FWK_SUCCESS; +} +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DHFWK_SA_MANAGER_TEST_H \ No newline at end of file diff --git a/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/src/dhfwk_sa_manager_test.cpp b/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/src/dhfwk_sa_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bcd5ac4bc175e4fad4445743fb151b988189e6cd --- /dev/null +++ b/interfaces/inner_kits/test/unittest/common/ipc/dhfwk_sa_manager/src/dhfwk_sa_manager_test.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dhfwk_sa_manager_test.h" + +#include "system_ability_definition.h" +#include "system_ability_status_change_stub.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void DHFWKSAManagerTest::SetUpTestCase() +{ +} + +void DHFWKSAManagerTest::TearDownTestCase() +{ +} + +void DHFWKSAManagerTest::SetUp() +{ +} + +void DHFWKSAManagerTest::TearDown() +{ +} + +void DHFWKSaStateCallback(bool callback) +{ +} + +/** + * @tc.name: RegisterAbilityListener_001 + * @tc.desc: Verify the RegisterAbilityListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, RegisterAbilityListener_001, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().isSubscribeDHFWKSAChangeListener.store(false); + DHFWKSAManager::GetInstance().saListener_ = nullptr; + DHFWKSAManager::GetInstance().RegisterAbilityListener(); + EXPECT_EQ(false, DHFWKSAManager::GetInstance().isSubscribeDHFWKSAChangeListener.load()); +} + +/** + * @tc.name: RegisterAbilityListener_002 + * @tc.desc: Verify the RegisterAbilityListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, RegisterAbilityListener_002, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().isSubscribeDHFWKSAChangeListener.store(true); + DHFWKSAManager::GetInstance().RegisterAbilityListener(); + EXPECT_EQ(true, DHFWKSAManager::GetInstance().isSubscribeDHFWKSAChangeListener.load()); +} + +/** + * @tc.name: GetDHFWKProxy_001 + * @tc.desc: Verify the GetDHFWKProxy function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, GetDHFWKProxy_001, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().isSubscribeDHFWKSAChangeListener.store(false); + DHFWKSAManager::GetInstance().dhfwkProxy_ = nullptr; + DHFWKSAManager::GetInstance().GetDHFWKProxy(); + EXPECT_EQ(nullptr, DHFWKSAManager::GetInstance().dhfwkProxy_); +} + +/** + * @tc.name: GetDHFWKProxy_002 + * @tc.desc: Verify the GetDHFWKProxy function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, GetDHFWKProxy_002, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().isSubscribeDHFWKSAChangeListener.store(true); + DHFWKSAManager::GetInstance().dhfwkProxy_ = new OHOS::DistributedHardware::MockIDistributedHardware(); + DHFWKSAManager::GetInstance().GetDHFWKProxy(); + EXPECT_NE(nullptr, DHFWKSAManager::GetInstance().dhfwkProxy_); +} + +/** + * @tc.name: RegisterSAStateCallback_001 + * @tc.desc: Verify the RegisterSAStateCallback function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, RegisterSAStateCallback_001, TestSize.Level0) +{ + DHFWKSAStateCb callback; + DHFWKSAManager::GetInstance().isSubscribeDHFWKSAChangeListener.store(true); + DHFWKSAManager::GetInstance().RegisterSAStateCallback(callback); + EXPECT_EQ(true, DHFWKSAManager::GetInstance().isSubscribeDHFWKSAChangeListener.load()); +} + +/** + * @tc.name: OnAddSystemAbility_001 + * @tc.desc: Verify the OnAddSystemAbility function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, OnAddSystemAbility_001, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().saListener_ = new DHFWKSAManager::SystemAbilityListener(); + int32_t systemAbilityId = 1; + std::string deviceId = "deviceId"; + DHFWKSAManager::GetInstance().saListener_->OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_NE(nullptr, DHFWKSAManager::GetInstance().saListener_); +} + +/** + * @tc.name: OnAddSystemAbility_002 + * @tc.desc: Verify the OnAddSystemAbility function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, OnAddSystemAbility_002, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().saListener_ = new DHFWKSAManager::SystemAbilityListener(); + int32_t systemAbilityId = DISTRIBUTED_HARDWARE_SA_ID; + std::string deviceId = "deviceId"; + DHFWKSAManager::GetInstance().saListener_->OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_NE(nullptr, DHFWKSAManager::GetInstance().saListener_); +} + +/** + * @tc.name: OnAddSystemAbility_003 + * @tc.desc: Verify the OnAddSystemAbility function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, OnAddSystemAbility_003, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().saListener_ = new DHFWKSAManager::SystemAbilityListener(); + int32_t systemAbilityId = DISTRIBUTED_HARDWARE_SA_ID; + std::string deviceId = "deviceId"; + DHFWKSAManager::GetInstance().dhfwkProxy_ = new MockIDistributedHardware(); + DHFWKSAManager::GetInstance().saStateCallback = DHFWKSaStateCallback; + DHFWKSAManager::GetInstance().saListener_->OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_NE(nullptr, DHFWKSAManager::GetInstance().saListener_); +} + +/** + * @tc.name: OnRemoveSystemAbility_001 + * @tc.desc: Verify the OnRemoveSystemAbility function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, OnRemoveSystemAbility_001, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().saListener_ = new DHFWKSAManager::SystemAbilityListener(); + int32_t systemAbilityId = 1; + std::string deviceId = "deviceId"; + DHFWKSAManager::GetInstance().saListener_->OnRemoveSystemAbility(systemAbilityId, deviceId); + EXPECT_NE(nullptr, DHFWKSAManager::GetInstance().saListener_); +} + +/** + * @tc.name: OnRemoveSystemAbility_002 + * @tc.desc: Verify the OnRemoveSystemAbility function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, OnRemoveSystemAbility_002, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().saListener_ = new DHFWKSAManager::SystemAbilityListener(); + int32_t systemAbilityId = DISTRIBUTED_HARDWARE_SA_ID; + std::string deviceId = "deviceId"; + DHFWKSAManager::GetInstance().saListener_->OnRemoveSystemAbility(systemAbilityId, deviceId); + EXPECT_NE(nullptr, DHFWKSAManager::GetInstance().saListener_); +} + +/** + * @tc.name: OnRemoveSystemAbility_003 + * @tc.desc: Verify the OnRemoveSystemAbility function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DHFWKSAManagerTest, OnRemoveSystemAbility_003, TestSize.Level0) +{ + DHFWKSAManager::GetInstance().saListener_ = new DHFWKSAManager::SystemAbilityListener(); + int32_t systemAbilityId = DISTRIBUTED_HARDWARE_SA_ID; + std::string deviceId = "deviceId"; + DHFWKSAManager::GetInstance().dhfwkProxy_ = new OHOS::DistributedHardware::MockIDistributedHardware(); + DHFWKSAManager::GetInstance().saStateCallback = DHFWKSaStateCallback; + DHFWKSAManager::GetInstance().saListener_->OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_NE(nullptr, DHFWKSAManager::GetInstance().saListener_); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/BUILD.gn b/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d613a9c5c1234d3c6d1bc9780b31b59e724a9bd2 --- /dev/null +++ b/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/distributed_hardware_proxy_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${av_trans_path}/common/include", + "include", + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "${common_path}/log/include", + "${innerkits_path}/include", + "${innerkits_path}/include/ipc", + "//third_party/json/include", + ] +} + +ohos_unittest("DistributedHardwareProxyTest") { + module_out_path = module_out_path + + sources = [ "src/distributed_hardware_proxy_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${innerkits_path}:libdhfwk_sdk", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DistributedHardwareProxyTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("distributed_hardware_proxy_test") { + testonly = true + deps = [ ":DistributedHardwareProxyTest" ] +} diff --git a/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/include/distributed_hardware_proxy_test.h b/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/include/distributed_hardware_proxy_test.h new file mode 100644 index 0000000000000000000000000000000000000000..f0b3b31de673060c5068e3c2425c097d824b62c7 --- /dev/null +++ b/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/include/distributed_hardware_proxy_test.h @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_PROXY_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_PROXY_TEST_H + +#include +#include +#include + +#include "device_type.h" +#include "distributed_hardware_errno.h" +#include "idistributed_hardware.h" +#define private public +#include "distributed_hardware_proxy.h" +#undef private + +namespace OHOS { +namespace DistributedHardware { +class DistributedHardwareProxyTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp(); + virtual void TearDown(); + + std::shared_ptr hardwareProxy_ = nullptr; +}; + +class MockIDistributedHardware : public IDistributedHardware { +public: + sptr AsObject() + { + return nullptr; + } + + int32_t RegisterPublisherListener(const DHTopic topic, const sptr &listener) + { + (void)topic; + (void)listener; + return DH_FWK_SUCCESS; + } + + int32_t UnregisterPublisherListener(const DHTopic topic, const sptr &listener) + { + (void)topic; + (void)listener; + return DH_FWK_SUCCESS; + } + + int32_t PublishMessage(const DHTopic topic, const std::string &msg) + { + (void)topic; + (void)msg; + return DH_FWK_SUCCESS; + } + + std::string QueryLocalSysSpec(QueryLocalSysSpecType spec) + { + (void)spec; + return 0; + } + + int32_t InitializeAVCenter(const TransRole &transRole, int32_t &engineId) + { + (void)transRole; + (void)engineId; + return DH_FWK_SUCCESS; + } + + int32_t ReleaseAVCenter(int32_t engineId) + { + (void)engineId; + return DH_FWK_SUCCESS; + } + + int32_t CreateControlChannel(int32_t engineId, const std::string &peerDevId) + { + (void)engineId; + (void)peerDevId; + return DH_FWK_SUCCESS; + } + + int32_t NotifyAVCenter(int32_t engineId, const AVTransEvent &event) + { + (void)engineId; + (void)event; + return DH_FWK_SUCCESS; + } + + int32_t RegisterCtlCenterCallback(int32_t engineId, const sptr &callback) + { + (void)engineId; + (void)callback; + return DH_FWK_SUCCESS; + } +}; + +class MockIPublisherListener : public IPublisherListener { +public: + sptr AsObject() + { + return nullptr; + } + + void OnMessage(const DHTopic topic, const std::string& message) + { + (void)topic; + (void)message; + } +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_PROXY_TEST_H \ No newline at end of file diff --git a/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/src/distributed_hardware_proxy_test.cpp b/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/src/distributed_hardware_proxy_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a154b73c1d0ee763fb3a3bbf47fe7318d866f508 --- /dev/null +++ b/interfaces/inner_kits/test/unittest/common/ipc/distributed_hardware_proxy/src/distributed_hardware_proxy_test.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "distributed_hardware_proxy_test.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void DistributedHardwareProxyTest::SetUpTestCase() +{ +} + +void DistributedHardwareProxyTest::TearDownTestCase() +{ +} + +void DistributedHardwareProxyTest::SetUp() +{ + sptr impl = nullptr; + hardwareProxy_ = std::make_shared(impl); +} + +void DistributedHardwareProxyTest::TearDown() +{ + hardwareProxy_ = nullptr; +} + +/** + * @tc.name: RegisterPublisherListener_001 + * @tc.desc: Verify the RegisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, RegisterPublisherListener_001, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + sptr listener = nullptr; + int32_t ret = hardwareProxy_->RegisterPublisherListener(topic, listener); + EXPECT_EQ(ERR_DH_FWK_PUBLISHER_LISTENER_IS_NULL, ret); +} + +/** + * @tc.name: RegisterAbilityListener_002 + * @tc.desc: Verify the RegisterAbilityListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, RegisterAbilityListener_002, TestSize.Level0) +{ + int32_t invalid = 7; + DHTopic topic = static_cast(invalid); + sptr listener = new MockIPublisherListener(); + int32_t ret = hardwareProxy_->RegisterPublisherListener(topic, listener); + EXPECT_EQ(ERR_DH_FWK_SERVICE_REMOTE_IS_NULL, ret); +} + +/** + * @tc.name: RegisterAbilityListener_003 + * @tc.desc: Verify the RegisterAbilityListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, RegisterAbilityListener_003, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + sptr listener = new MockIPublisherListener(); + int32_t ret = hardwareProxy_->RegisterPublisherListener(topic, listener); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: UnregisterPublisherListener_001 + * @tc.desc: Verify the UnregisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, UnregisterPublisherListener_001, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + sptr listener = nullptr; + int32_t ret = hardwareProxy_->UnregisterPublisherListener(topic, listener); + EXPECT_EQ(ERR_DH_FWK_PUBLISHER_LISTENER_IS_NULL, ret); +} + +/** + * @tc.name: UnregisterPublisherListener_002 + * @tc.desc: Verify the UnregisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, UnregisterPublisherListener_002, TestSize.Level0) +{ + int32_t invalid = 7; + DHTopic topic = static_cast(invalid); + sptr listener = new MockIPublisherListener(); + int32_t ret = hardwareProxy_->UnregisterPublisherListener(topic, listener); + EXPECT_EQ(ERR_DH_FWK_SERVICE_REMOTE_IS_NULL, ret); +} + +/** + * @tc.name: UnregisterPublisherListener_003 + * @tc.desc: Verify the UnregisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, UnregisterPublisherListener_003, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + sptr listener = new MockIPublisherListener(); + int32_t ret = hardwareProxy_->UnregisterPublisherListener(topic, listener); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: PublishMessage_001 + * @tc.desc: Verify the PublishMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, PublishMessage_001, TestSize.Level0) +{ + int32_t invalid = 7; + std::string msg; + DHTopic topic = static_cast(invalid); + int32_t ret = hardwareProxy_->PublishMessage(topic, msg); + EXPECT_EQ(ERR_DH_FWK_SERVICE_REMOTE_IS_NULL, ret); +} + +/** + * @tc.name: PublishMessage_002 + * @tc.desc: Verify the PublishMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, PublishMessage_002, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + std::string msg; + int32_t ret = hardwareProxy_->PublishMessage(topic, msg); + EXPECT_EQ(ERR_DH_FWK_SERVICE_REMOTE_IS_NULL, ret); +} + +/** + * @tc.name: PublishMessage_003 + * @tc.desc: Verify the PublishMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareProxyTest, PublishMessage_003, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_STOP_DSCREEN; + std::string msg = "msg"; + int32_t ret = hardwareProxy_->PublishMessage(topic, msg); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/BUILD.gn b/interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..809b2f689fef38f9a09fa4d4bc3916c24eed6397 --- /dev/null +++ b/interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/publisher_listener_stub_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${av_trans_path}/common/include", + "include", + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "${common_path}/log/include", + "${innerkits_path}/include", + "${innerkits_path}/include/ipc", + "//third_party/json/include", + ] +} + +ohos_unittest("PublisherListenerStubTest") { + module_out_path = module_out_path + + sources = [ "src/publisher_listener_stub_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${innerkits_path}:libdhfwk_sdk", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"PublisherListenerStubTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("publisher_listener_stub_test") { + testonly = true + deps = [ ":PublisherListenerStubTest" ] +} diff --git a/interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/include/publisher_listener_stub_test.h b/interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/include/publisher_listener_stub_test.h new file mode 100644 index 0000000000000000000000000000000000000000..5f32cdefa3cf53e2255ec2f5f8fc268782eafacd --- /dev/null +++ b/interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/include/publisher_listener_stub_test.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_PUBLISHER_LISTENER_STUB_TEST_H +#define OHOS_PUBLISHER_LISTENER_STUB_TEST_H + +#include +#include +#include + +#include + +#include "distributed_hardware_errno.h" +#include "ipublisher_listener.h" +#include "iremote_stub.h" +#include "idistributed_hardware.h" +#define private public +#include "publisher_listener_stub.h" +#undef private + +namespace OHOS { +namespace DistributedHardware { +class PublisherListenerStubTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp(); + virtual void TearDown(); + + std::shared_ptr listenerStub_ = nullptr; +}; + +class MockPublisherListenerStub : public PublisherListenerStub { +public: + void OnMessage(const DHTopic topic, const std::string& message) + { + (void)topic; + (void)message; + } +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_PUBLISHER_LISTENER_STUB_TEST_H \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/src/local_hardware_manager_test.cpp b/interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/src/publisher_listener_stub_test.cpp similarity index 44% rename from services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/src/local_hardware_manager_test.cpp rename to interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/src/publisher_listener_stub_test.cpp index deccf44c60c46e87ce0a841ff4da4b8e7ab33673..f0a63f64bd8b6c59e46e171ba7b0553c37483a71 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/src/local_hardware_manager_test.cpp +++ b/interfaces/inner_kits/test/unittest/common/ipc/publisher_listener_stub/src/publisher_listener_stub_test.cpp @@ -13,52 +13,43 @@ * limitations under the License. */ -#include "local_hardware_manager_test.h" - -#define private public -#include "capability_info_manager.h" -#include "component_loader.h" -#include "local_hardware_manager.h" -#undef private +#include "publisher_listener_stub_test.h" using namespace testing::ext; namespace OHOS { namespace DistributedHardware { -void LocalHardwareManagerTest::SetUpTestCase(void) +void PublisherListenerStubTest::SetUpTestCase() { - ComponentLoader::GetInstance().Init(); } -void LocalHardwareManagerTest::TearDownTestCase(void) +void PublisherListenerStubTest::TearDownTestCase() { - ComponentLoader::GetInstance().UnInit(); } -void LocalHardwareManagerTest::SetUp() {} - -void LocalHardwareManagerTest::TearDown() {} +void PublisherListenerStubTest::SetUp() +{ + listenerStub_ = std::make_shared(); +} -/** - * @tc.name: local_hardware_manager_test_001 - * @tc.desc: Verify the Init function. - * @tc.type: FUNC - * @tc.require: AR000GHSK3 - */ -HWTEST_F(LocalHardwareManagerTest, local_hardware_manager_test_001, TestSize.Level0) +void PublisherListenerStubTest::TearDown() { - LocalHardwareManager::GetInstance().Init(); + listenerStub_ = nullptr; } /** - * @tc.name: local_hardware_manager_test_002 - * @tc.desc: Verify the UnInit function. + * @tc.name: OnRemoteRequest_001 + * @tc.desc: Verify the OnRemoteRequest function * @tc.type: FUNC - * @tc.require: AR000GHSK3 + * @tc.require: AR000GHSJM */ -HWTEST_F(LocalHardwareManagerTest, local_hardware_manager_test_002, TestSize.Level0) +HWTEST_F(PublisherListenerStubTest, OnRemoteRequest_001, TestSize.Level0) { - LocalHardwareManager::GetInstance().UnInit(); + uint32_t code = 0; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_EQ(ERR_INVALID_DATA, listenerStub_->OnRemoteRequest(code, data, reply, option)); } } // namespace DistributedHardware } // namespace OHOS diff --git a/sa_profile/4801.json b/sa_profile/4801.json new file mode 100644 index 0000000000000000000000000000000000000000..0978d90f304944e33f73481c344c647706bdabbc --- /dev/null +++ b/sa_profile/4801.json @@ -0,0 +1,12 @@ +{ + "process": "dhardware", + "systemability": [ + { + "name": 4801, + "libpath": "libdistributedhardwarefwksvr.z.so", + "run-on-create": false, + "distributed": true, + "dump_level": 1 + } + ] +} \ No newline at end of file diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn index f30568c3209fe5ddf3c08f863870c5a7a06084d0..5605284504a0444e42fc665f946035ffe906b93c 100644 --- a/sa_profile/BUILD.gn +++ b/sa_profile/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos.gni") ohos_sa_profile("dhfwk_sa_profile") { - sources = [ "4801.xml" ] + sources = [ "4801.json" ] part_name = "distributed_hardware_fwk" } diff --git a/sa_profile/dhardware.cfg b/sa_profile/dhardware.cfg index d5b3be3d7ea009678addb553836d7fde155f06d5..633d25ded56dec9fa62864092396391d50b8bda8 100644 --- a/sa_profile/dhardware.cfg +++ b/sa_profile/dhardware.cfg @@ -9,12 +9,17 @@ ], "services" : [{ "name" : "dhardware", - "path" : ["/system/bin/sa_main", "/system/profile/dhardware.xml"], + "path" : ["/system/bin/sa_main", "/system/profile/dhardware.json"], "uid" : "dhardware", - "gid" : ["dhardware", "root", "input"], + "gid" : ["dhardware", "input"], "ondemand" : true, "apl" : "system_basic", - "permission" : ["ohos.permission.DISTRIBUTED_DATASYNC", "ohos.permission.CAMERA"], + "permission" : [ + "ohos.permission.DISTRIBUTED_DATASYNC", + "ohos.permission.DISTRIBUTED_SOFTBUS_CENTER", + "ohos.permission.CAMERA", + "ohos.permission.ACCESS_SERVICE_DM" + ], "jobs" : { "on-start" : "services:dhardware" }, diff --git a/services/distributedhardwarefwkservice/BUILD.gn b/services/distributedhardwarefwkservice/BUILD.gn index cafb1d866ce559cd8fbc08363cc5913b67c5d868..04442977af0dc5c073817b2817165f35854407a1 100644 --- a/services/distributedhardwarefwkservice/BUILD.gn +++ b/services/distributedhardwarefwkservice/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -18,19 +18,17 @@ import( ohos_shared_library("distributedhardwarefwksvr") { include_dirs = [ - "//base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include", - "//base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter", - "//commonlibrary/c_utils/base/include", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", - "//utils/system/safwk/native/include", "include", "include/accessmanager", + "${av_center_svc_path}/include", + "${av_center_svc_path}/include/ipc", + "${av_trans_path}/common/include", + "${av_trans_path}/interface", + "${innerkits_path}/include", "${common_path}/log/include", "${common_path}/utils/include", "${utils_path}/include/log", "${utils_path}/include", - "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include", - "//foundation/distributedhardware/device_manager/common/include", "//third_party/json/include", "include/componentloader", "include/versionmanager", @@ -43,9 +41,17 @@ ohos_shared_library("distributedhardwarefwksvr") { "include/hidumphelper", "include/ipc", "${utils_path}/include/eventbus", + "include/lowlatency", ] sources = [ + "${av_center_svc_path}/src/av_sync_manager.cpp", + "${av_center_svc_path}/src/av_trans_control_center.cpp", + "${av_center_svc_path}/src/ipc/av_trans_control_center_callback_proxy.cpp", + "${av_trans_path}/common/src/av_sync_utils.cpp", + "${av_trans_path}/common/src/av_trans_log.cpp", + "${av_trans_path}/common/src/av_trans_message.cpp", + "${av_trans_path}/common/src/softbus_channel_adapter.cpp", "src/accessmanager/access_manager.cpp", "src/componentloader/component_loader.cpp", "src/componentmanager/component_disable.cpp", @@ -61,6 +67,9 @@ ohos_shared_library("distributedhardwarefwksvr") { "src/ipc/publisher_listener_proxy.cpp", "src/localhardwaremanager/local_hardware_manager.cpp", "src/localhardwaremanager/plugin_listener_impl.cpp", + "src/lowlatency/low_latency.cpp", + "src/lowlatency/low_latency_listener.cpp", + "src/lowlatency/low_latency_timer.cpp", "src/publisher/publisher.cpp", "src/publisher/publisher_item.cpp", "src/resourcemanager/capability_info.cpp", @@ -79,14 +88,11 @@ ohos_shared_library("distributedhardwarefwksvr") { "src/task/task_executor.cpp", "src/task/task_factory.cpp", "src/utils/dh_context.cpp", + "src/utils/dh_timer.cpp", "src/versionmanager/version_manager.cpp", ] - deps = [ - "${utils_path}:distributedhardwareutils", - "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp:devicemanagersdk", - "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", - ] + deps = [ "${utils_path}:distributedhardwareutils" ] defines = [ "HI_LOG_ENABLE", @@ -94,12 +100,23 @@ ohos_shared_library("distributedhardwarefwksvr") { "LOG_DOMAIN=0xD004100", ] + if (dhardware_low_latency) { + defines += [ "DHARDWARE_LOW_LATENCY" ] + } + external_deps = [ "c_utils:utils", + "config_policy:configpolicy_util", + "device_manager:devicemanagersdk", + "dsoftbus:softbus_client", "eventhandler:libeventhandler", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", "kv_store:distributeddata_inner", + "resource_schedule_service:ressched_client", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/services/distributedhardwarefwkservice/include/componentloader/component_loader.h b/services/distributedhardwarefwkservice/include/componentloader/component_loader.h index 3ff04a4341a80a48465c26fc4cece6369feed032..1a45ec7f118bb29ff7e4f7fb1e7d9725f49820a0 100644 --- a/services/distributedhardwarefwkservice/include/componentloader/component_loader.h +++ b/services/distributedhardwarefwkservice/include/componentloader/component_loader.h @@ -39,8 +39,6 @@ struct CompHandler { int32_t sinkSaId; void *hardwareHandler; }; - -const std::string COMPONENTSLOAD_DISTRIBUTED_COMPONENTS = "distributed_components"; } struct CompConfig { diff --git a/services/distributedhardwarefwkservice/include/componentmanager/component_manager.h b/services/distributedhardwarefwkservice/include/componentmanager/component_manager.h index 6ec6d7e9bd5994f852a6c207335ce973fdcd2ab2..375f476c4aef28c4c11429cdad320abc4e7f7c9b 100644 --- a/services/distributedhardwarefwkservice/include/componentmanager/component_manager.h +++ b/services/distributedhardwarefwkservice/include/componentmanager/component_manager.h @@ -28,6 +28,8 @@ #include "idistributed_hardware.h" #include "idistributed_hardware_sink.h" #include "idistributed_hardware_source.h" +#include "low_latency_listener.h" +#include "monitor_task_timer.h" #include "version_info.h" namespace OHOS { @@ -87,7 +89,9 @@ private: std::map compSource_; std::map compSink_; std::map compSrcSaId_; - std::shared_ptr compMonitorPtr_; + std::shared_ptr compMonitorPtr_ = nullptr; + sptr lowLatencyListener_ = nullptr; + std::shared_ptr monitorTaskTimer_ = nullptr; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/include/componentmanager/component_monitor.h b/services/distributedhardwarefwkservice/include/componentmanager/component_monitor.h index 78fc5f815023d1aae1b1fbcf591c06793a21514f..5ff8fd2b87e90d6f7ee46738cf8a51b66b703fe1 100644 --- a/services/distributedhardwarefwkservice/include/componentmanager/component_monitor.h +++ b/services/distributedhardwarefwkservice/include/componentmanager/component_monitor.h @@ -39,6 +39,7 @@ public: public: class CompSystemAbilityListener : public SystemAbilityStatusChangeStub { public: + ~CompSystemAbilityListener() = default; void OnAddSystemAbility(int32_t saId, const std::string &deviceId) override; void OnRemoveSystemAbility(int32_t saId, const std::string &deviceId) override; }; diff --git a/services/distributedhardwarefwkservice/include/distributed_hardware_service.h b/services/distributedhardwarefwkservice/include/distributed_hardware_service.h index 373df81a51904ab5c4415af1d8f9a3574602de83..260aaebf5ab31c4b6ad6b33674f88424bfbe38ad 100644 --- a/services/distributedhardwarefwkservice/include/distributed_hardware_service.h +++ b/services/distributedhardwarefwkservice/include/distributed_hardware_service.h @@ -19,6 +19,8 @@ #include "system_ability.h" #include "ipc_object_stub.h" +#include "distributed_hardware_fwk_kit.h" +#include "distributed_hardware_fwk_kit_paras.h" #include "distributed_hardware_stub.h" #include "single_instance.h" @@ -37,14 +39,22 @@ public: int32_t RegisterPublisherListener(const DHTopic topic, const sptr &listener) override; int32_t UnregisterPublisherListener(const DHTopic topic, const sptr &listener) override; int32_t PublishMessage(const DHTopic topic, const std::string &msg) override; + std::string QueryLocalSysSpec(const QueryLocalSysSpecType spec) override; int Dump(int32_t fd, const std::vector& args) override; + int32_t InitializeAVCenter(const TransRole &transRole, int32_t &engineId) override; + int32_t ReleaseAVCenter(int32_t engineId) override; + int32_t CreateControlChannel(int32_t engineId, const std::string &peerDevId) override; + int32_t NotifyAVCenter(int32_t engineId, const AVTransEvent &event) override; + int32_t RegisterCtlCenterCallback(int32_t engineId, const sptr &callback) override; + protected: void OnStart() override; void OnStop() override; private: bool Init(); + std::string QueryDhSysSpec(const std::string &targetKey, std::string &attrs); private: bool registerToService_ = false; @@ -52,4 +62,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/include/distributed_hardware_stub.h b/services/distributedhardwarefwkservice/include/distributed_hardware_stub.h index cabb412e4255fc7acdb702bc2c8b331cfe9b172c..79d8a95b13f463cd2e796ba261fe32eb309d1804 100644 --- a/services/distributedhardwarefwkservice/include/distributed_hardware_stub.h +++ b/services/distributedhardwarefwkservice/include/distributed_hardware_stub.h @@ -30,7 +30,16 @@ private: int32_t RegisterPublisherListenerInner(MessageParcel &data, MessageParcel &reply); int32_t UnregisterPublisherListenerInner(MessageParcel &data, MessageParcel &reply); int32_t PublishMessageInner(MessageParcel &data, MessageParcel &reply); + int32_t QueryLocalSysSpecInner(MessageParcel &data, MessageParcel &reply); + + int32_t InitializeAVCenterInner(MessageParcel &data, MessageParcel &reply); + int32_t ReleaseAVCenterInner(MessageParcel &data, MessageParcel &reply); + int32_t CreateControlChannelInner(MessageParcel &data, MessageParcel &reply); + int32_t NotifyAVCenterInner(MessageParcel &data, MessageParcel &reply); + int32_t RegisterControlCenterCallbackInner(MessageParcel &data, MessageParcel &reply); + bool ValidTopic(uint32_t topic); + bool ValidQueryLocalSpec(uint32_t spec); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/include/localhardwaremanager/local_hardware_manager.h b/services/distributedhardwarefwkservice/include/localhardwaremanager/local_hardware_manager.h index 26008e273bd4974da2e0e32c683c90b54702f2fb..e1a118d94a200f29439cb8b00150c34fb7924915 100644 --- a/services/distributedhardwarefwkservice/include/localhardwaremanager/local_hardware_manager.h +++ b/services/distributedhardwarefwkservice/include/localhardwaremanager/local_hardware_manager.h @@ -27,11 +27,6 @@ namespace OHOS { namespace DistributedHardware { -namespace { - constexpr int32_t QUERY_INTERVAL_TIME = 1000 * 1000; // 1s - constexpr int32_t QUERY_RETRY_MAX_TIMES = 30; -} - class LocalHardwareManager { DECLARE_SINGLE_INSTANCE_BASE(LocalHardwareManager); diff --git a/services/distributedhardwarefwkservice/include/lowlatency/low_latency.h b/services/distributedhardwarefwkservice/include/lowlatency/low_latency.h new file mode 100644 index 0000000000000000000000000000000000000000..f5942bf570ce241e27280bf70bbfaf282842002b --- /dev/null +++ b/services/distributedhardwarefwkservice/include/lowlatency/low_latency.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_H +#define OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_H + +#include +#include + +#include "device_type.h" +#include "dh_timer.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class LowLatency { +DECLARE_SINGLE_INSTANCE_BASE(LowLatency); +public: + void EnableLowLatency(DHType dhType); + void DisableLowLatency(DHType dhType); + void CloseLowLatency(); + +private: + LowLatency(); + ~LowLatency(); + +private: + std::unordered_set lowLatencySwitchSet_; + std::mutex lowLatencyMutex_; + std::shared_ptr lowLatencyTimer_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/include/lowlatency/low_latency_listener.h b/services/distributedhardwarefwkservice/include/lowlatency/low_latency_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..b69e1b7feac19e343a6a5e3ff4e13b0b0602825d --- /dev/null +++ b/services/distributedhardwarefwkservice/include/lowlatency/low_latency_listener.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_LISTENER_H +#define OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_LISTENER_H + +#include "ipublisher_listener.h" +#include "low_latency.h" + +namespace OHOS { +namespace DistributedHardware { +class LowLatencyListener : public IPublisherListener { +public: + LowLatencyListener(); + ~LowLatencyListener() override; + void OnMessage(const DHTopic topic, const std::string& message) override; + sptr AsObject() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/include/lowlatency/low_latency_timer.h b/services/distributedhardwarefwkservice/include/lowlatency/low_latency_timer.h new file mode 100644 index 0000000000000000000000000000000000000000..1df43a9b400da7193cb524ed754d5104f0f87698 --- /dev/null +++ b/services/distributedhardwarefwkservice/include/lowlatency/low_latency_timer.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_TIMER_H +#define OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_TIMER_H + +#include "dh_timer.h" + +namespace OHOS { +namespace DistributedHardware { +class LowLatencyTimer : public DHTimer { +public: + LowLatencyTimer(std::string timerId, int32_t delayTimeMs); + ~LowLatencyTimer() override; + void ExecuteInner() override; + void HandleStopTimer() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/include/resourcemanager/capability_info_manager.h b/services/distributedhardwarefwkservice/include/resourcemanager/capability_info_manager.h index 8958acc3ba72bbd7656a42d3b536315ad157ea10..47d1a8818ca47358e158439d86e13e84598b4b6f 100644 --- a/services/distributedhardwarefwkservice/include/resourcemanager/capability_info_manager.h +++ b/services/distributedhardwarefwkservice/include/resourcemanager/capability_info_manager.h @@ -35,9 +35,6 @@ class DBAdapter; namespace OHOS { namespace DistributedHardware { -namespace { - constexpr int32_t MANUAL_SYNC_TIMEOUT = 1; -} class CapabilityInfoManager : public std::enable_shared_from_this, public EventSender, public DistributedKv::KvStoreObserver, diff --git a/services/distributedhardwarefwkservice/include/resourcemanager/db_adapter.h b/services/distributedhardwarefwkservice/include/resourcemanager/db_adapter.h index f2d052d1f267c6ff8d8f7f09814e7fb57bc40b81..6d09605b4bd8d781e944be528f8db05f5acd466f 100644 --- a/services/distributedhardwarefwkservice/include/resourcemanager/db_adapter.h +++ b/services/distributedhardwarefwkservice/include/resourcemanager/db_adapter.h @@ -31,14 +31,6 @@ namespace OHOS { namespace DistributedHardware { -namespace { -constexpr int32_t MAX_INIT_RETRY_TIMES = 20; -constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms -constexpr int32_t MANUAL_SYNC_TIMES = 6; -constexpr int32_t MANUAL_SYNC_INTERVAL = 100 * 1000; // 100ms -constexpr int32_t DIED_CHECK_MAX_TIMES = 300; -constexpr int32_t DIED_CHECK_INTERVAL = 100 * 1000; // 100ms -} class DBAdapter : public std::enable_shared_from_this, public EventSender, public DistributedKv::KvStoreSyncCallback, diff --git a/services/distributedhardwarefwkservice/include/task/monitor_task_timer.h b/services/distributedhardwarefwkservice/include/task/monitor_task_timer.h index c3942035177ee86b6811f018672817b165567bea..703da1b916fd7bc7d85ab201cddaf9bab068a051 100644 --- a/services/distributedhardwarefwkservice/include/task/monitor_task_timer.h +++ b/services/distributedhardwarefwkservice/include/task/monitor_task_timer.h @@ -13,40 +13,21 @@ * limitations under the License. */ -#ifndef DISTRIBUTED_HARDWARE_FWK_MONITOR_TASK_TIMER_H -#define DISTRIBUTED_HARDWARE_FWK_MONITOR_TASK_TIMER_H +#ifndef OHOS_DISTRIBUTED_HARDWARE_MONITOR_TASK_TIMER_H +#define OHOS_DISTRIBUTED_HARDWARE_MONITOR_TASK_TIMER_H -#include -#include -#include -#include -#include - -#include "event_handler.h" - -#include "single_instance.h" +#include "dh_timer.h" namespace OHOS { namespace DistributedHardware { -class MonitorTaskTimer { -DECLARE_SINGLE_INSTANCE_BASE(MonitorTaskTimer); +class MonitorTaskTimer : public DHTimer { public: - ~MonitorTaskTimer(); - void StartTimer(); - void StopTimer(); - void StartEventRunner(); - -private: - MonitorTaskTimer(); - void Execute(const std::shared_ptr eventHandler); - void InitTimer(); - void ReleaseTimer(); + MonitorTaskTimer(std::string timerId, int32_t delayTimerMs); + ~MonitorTaskTimer() override; private: - std::thread eventHandlerThread_; - std::mutex monitorTaskTimerMutex_; - std::condition_variable monitorTaskTimerCond_; - std::shared_ptr eventHandler_; + void ExecuteInner() override; + void HandleStopTimer() override; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/include/task/task_board.h b/services/distributedhardwarefwkservice/include/task/task_board.h index 39976467b8b88aeea8562d8316de36b7211aa449..1e978c1c4072d18ec2978d8fdf835ebe4f6acfc1 100644 --- a/services/distributedhardwarefwkservice/include/task/task_board.h +++ b/services/distributedhardwarefwkservice/include/task/task_board.h @@ -36,7 +36,7 @@ public: int32_t WaitForALLTaskFinish(); void SaveEnabledDevice(const std::string &enabledDeviceKey, const TaskParam &taskParam); void RemoveEnabledDevice(const std::string &enabledDeviceKey); - const std::unordered_map& GetEnabledDevice(); + const std::unordered_map GetEnabledDevice(); void DumpAllTasks(std::vector &taskInfos); diff --git a/services/distributedhardwarefwkservice/include/utils/dh_timer.h b/services/distributedhardwarefwkservice/include/utils/dh_timer.h new file mode 100644 index 0000000000000000000000000000000000000000..79e6cb28936b51ec3057192ff99c3cda0a65ad30 --- /dev/null +++ b/services/distributedhardwarefwkservice/include/utils/dh_timer.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DH_TIMER_H +#define OHOS_DISTRIBUTED_HARDWARE_DH_TIMER_H + +#include +#include +#include +#include +#include + +#include "event_handler.h" + +namespace OHOS { +namespace DistributedHardware { +class DHTimer { +public: + DHTimer(std::string timerId, int32_t delayTimeMs); + virtual ~DHTimer(); + void StartTimer(); + void StopTimer(); + +private: + virtual void ExecuteInner() = 0; + virtual void HandleStopTimer() = 0; + void InitTimer(); + void ReleaseTimer(); + void Execute(); + void StartEventRunner(); + +private: + std::thread eventHandlerThread_; + std::mutex timerMutex_; + std::condition_variable timerCond_; + std::shared_ptr eventHandler_; + std::string timerId_; + int32_t delayTimeMs_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp b/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp index cf11db69ed6e084b7469a4758270d1f986c405ac..349dd8a6bd783efbd10db6ec43c12f3bb7512228 100644 --- a/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp +++ b/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp @@ -130,7 +130,7 @@ void AccessManager::OnDeviceOffline(const DmDeviceInfo &deviceInfo) DHLOGI("start, networkId = %s, deviceName = %s, deviceTypeId = %d", GetAnonyString(deviceInfo.deviceId).c_str(), GetAnonyString(deviceInfo.deviceName).c_str(), deviceInfo.deviceTypeId); - auto networkId = std::string(deviceInfo.deviceId); // deviceId of DM actually is networkId + auto networkId = std::string(deviceInfo.networkId); if (networkId.size() == 0 || networkId.size() > MAX_ID_LEN) { DHLOGE("NetworkId is invalid!"); return; @@ -157,7 +157,7 @@ void AccessManager::OnDeviceReady(const DmDeviceInfo &deviceInfo) DHLOGI("start, networkId = %s, deviceName = %s, deviceTypeId = %d", GetAnonyString(deviceInfo.deviceId).c_str(), GetAnonyString(deviceInfo.deviceName).c_str(), deviceInfo.deviceTypeId); - auto networkId = std::string(deviceInfo.deviceId); + auto networkId = std::string(deviceInfo.networkId); if (networkId.size() == 0 || networkId.size() > MAX_ID_LEN) { DHLOGE("NetworkId is invalid!"); return; @@ -188,7 +188,7 @@ void AccessManager::SendTrustedDeviceOnline() return; } for (const auto &deviceInfo : deviceList) { - const auto networkId = std::string(deviceInfo.deviceId); + const auto networkId = std::string(deviceInfo.networkId); const auto uuid = GetUUIDBySoftBus(networkId); DHLOGI("Send trusted device online, networkId = %s, uuid = %s", GetAnonyString(networkId).c_str(), GetAnonyString(uuid).c_str()); diff --git a/services/distributedhardwarefwkservice/src/componentloader/component_loader.cpp b/services/distributedhardwarefwkservice/src/componentloader/component_loader.cpp index d4cc5c3709abae0e1044b914b4a4ff3255513242..afaba3487f8e98aaf149fcfebd8b5ee3c17f6139 100644 --- a/services/distributedhardwarefwkservice/src/componentloader/component_loader.cpp +++ b/services/distributedhardwarefwkservice/src/componentloader/component_loader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,12 +20,14 @@ #include #include +#include "config_policy_utils.h" #include "nlohmann/json.hpp" #include "constants.h" #include "dh_context.h" #include "dh_utils_hitrace.h" #include "dh_utils_hisysevent.h" +#include "dh_utils_tool.h" #include "hidump_helper.h" #include "distributed_hardware_log.h" #include "version_info.h" @@ -55,6 +57,8 @@ const std::string COMP_SINK_LOC = "comp_sink_loc"; const std::string COMP_SINK_VERSION = "comp_sink_version"; const std::string COMP_SINK_SA_ID = "comp_sink_sa_id"; +const std::string COMPONENTSLOAD_DISTRIBUTED_COMPONENTS = "distributed_components"; + const std::string DEFAULT_NAME = ""; const std::string DEFAULT_TYPE = "UNKNOWN"; const std::string DEFAULT_LOC = ""; @@ -101,18 +105,85 @@ std::vector ComponentLoader::GetAllCompTypes() return DHTypeALL; } +int32_t ParseComponent(const nlohmann::json &json, CompConfig &cfg) +{ + if (!IsString(json, COMP_NAME)) { + DHLOGE("COMP_NAME is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.name = json.at(COMP_NAME).get(); + if (!IsString(json, COMP_TYPE)) { + DHLOGE("COMP_TYPE is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.type = g_mapDhTypeName[json.at(COMP_TYPE).get()]; + if (!IsString(json, COMP_HANDLER_LOC)) { + DHLOGE("COMP_HANDLER_LOC is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.compHandlerLoc = json.at(COMP_HANDLER_LOC).get(); + if (!IsString(json, COMP_HANDLER_VERSION)) { + DHLOGE("COMP_HANDLER_VERSION is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.compHandlerVersion = json.at(COMP_HANDLER_VERSION).get(); + return DH_FWK_SUCCESS; +} + +int32_t ParseSource(const nlohmann::json &json, CompConfig &cfg) +{ + if (!IsString(json, COMP_SOURCE_LOC)) { + DHLOGE("COMP_SOURCE_LOC is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.compSourceLoc = json.at(COMP_SOURCE_LOC).get(); + if (!IsString(json, COMP_SOURCE_VERSION)) { + DHLOGE("COMP_SOURCE_VERSION is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.compSourceVersion = json.at(COMP_SOURCE_VERSION).get(); + if (!IsInt32(json, COMP_SOURCE_SA_ID)) { + DHLOGE("COMP_SOURCE_SA_ID is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.compSourceSaId = json.at(COMP_SOURCE_SA_ID).get(); + return DH_FWK_SUCCESS; +} + +int32_t ParseSink(const nlohmann::json &json, CompConfig &cfg) +{ + if (!IsString(json, COMP_SINK_LOC)) { + DHLOGE("COMP_SINK_LOC is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.compSinkLoc = json.at(COMP_SINK_LOC).get(); + if (!IsString(json, COMP_SINK_VERSION)) { + DHLOGE("COMP_SINK_VERSION is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.compSinkVersion = json.at(COMP_SINK_VERSION).get(); + if (!IsInt32(json, COMP_SINK_SA_ID)) { + DHLOGE("COMP_SINK_SA_ID is invalid"); + return ERR_DH_FWK_JSON_PARSE_FAILED; + } + cfg.compSinkSaId = json.at(COMP_SINK_SA_ID).get(); + return DH_FWK_SUCCESS; +} + void from_json(const nlohmann::json &json, CompConfig &cfg) { - cfg.name = json.value(COMP_NAME, DEFAULT_NAME); - cfg.type = g_mapDhTypeName[json.value(COMP_TYPE, DEFAULT_TYPE)]; - cfg.compHandlerLoc = json.value(COMP_HANDLER_LOC, DEFAULT_LOC); - cfg.compHandlerVersion = json.value(COMP_HANDLER_VERSION, DEFAULT_VERSION); - cfg.compSourceLoc = json.value(COMP_SOURCE_LOC, DEFAULT_LOC); - cfg.compSourceVersion = json.value(COMP_SOURCE_VERSION, DEFAULT_VERSION); - cfg.compSourceSaId = json.value(COMP_SOURCE_SA_ID, DEFAULT_SA_ID); - cfg.compSinkLoc = json.value(COMP_SINK_LOC, DEFAULT_LOC); - cfg.compSinkVersion = json.value(COMP_SINK_VERSION, DEFAULT_VERSION); - cfg.compSinkSaId = json.value(COMP_SINK_SA_ID, DEFAULT_SA_ID); + if (ParseComponent(json, cfg) != DH_FWK_SUCCESS) { + DHLOGE("ParseComponent is failed"); + return; + } + if (ParseSource(json, cfg) != DH_FWK_SUCCESS) { + DHLOGE("ParseSource is failed"); + return; + } + if (ParseSink(json, cfg) != DH_FWK_SUCCESS) { + DHLOGE("ParseSink is failed"); + return; + } } CompVersion ComponentLoader::GetCompVersionFromComConfig(const CompConfig& cCfg) @@ -306,7 +377,19 @@ int32_t ComponentLoader::ParseConfig() std::map dhtypeMap; int32_t ret; DHLOGI("ParseConfig start"); - std::string jsonStr = Readfile(COMPONENTSLOAD_PROFILE_PATH); + char buf[MAX_PATH_LEN] = {0}; + char path[PATH_MAX + 1] = {0x00}; + char *profilePath = GetOneCfgFile(COMPONENTSLOAD_PROFILE_PATH, buf, MAX_PATH_LEN); + if (profilePath == nullptr) { + DHLOGE("profilePath is null."); + return ERR_DH_FWK_LOADER_PROFILE_PATH_IS_NULL; + } + if (strlen(profilePath) == 0 || strlen(profilePath) > PATH_MAX || realpath(profilePath, path) == nullptr) { + DHLOGE("File connicailization failed."); + return ERR_DH_FWK_LOADER_PROFILE_PATH_IS_NULL; + } + std::string componentProfilePath(path); + std::string jsonStr = Readfile(componentProfilePath); if (jsonStr.length() == 0 || jsonStr.size() > MAX_MESSAGE_LEN) { DHLOGE("ConfigJson size is invalid!"); return ERR_DH_FWK_LOADER_CONFIG_JSON_INVALID; diff --git a/services/distributedhardwarefwkservice/src/componentmanager/component_manager.cpp b/services/distributedhardwarefwkservice/src/componentmanager/component_manager.cpp index c53739b6aa220cb7cf975f8544c1affee4e2499e..78c773345475e915ab6b2b6d1c73cda5d955c990 100644 --- a/services/distributedhardwarefwkservice/src/componentmanager/component_manager.cpp +++ b/services/distributedhardwarefwkservice/src/componentmanager/component_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,7 @@ #include #include +#include #include #include @@ -37,7 +38,8 @@ #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" #include "enabled_comps_dump.h" -#include "monitor_task_timer.h" +#include "low_latency.h" +#include "publisher.h" #include "task_executor.h" #include "task_factory.h" #include "version_info_manager.h" @@ -51,14 +53,17 @@ namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(ComponentManager); namespace { - constexpr int32_t ENABLE_RETRY_MAX_TIMES = 30; - constexpr int32_t DISABLE_RETRY_MAX_TIMES = 30; + constexpr int32_t ENABLE_RETRY_MAX_TIMES = 3; + constexpr int32_t DISABLE_RETRY_MAX_TIMES = 3; constexpr int32_t ENABLE_PARAM_RETRY_TIME = 500 * 1000; - const int32_t INVALID_SA_ID = -1; + constexpr int32_t INVALID_SA_ID = -1; + constexpr int32_t MONITOR_TASK_DELAY_MS = 5 * 1000; + const std::string MONITOR_TASK_TIMER_ID = "monitor_task_timer_id"; } ComponentManager::ComponentManager() : compSource_({}), compSink_({}), compSrcSaId_({}), - compMonitorPtr_(std::make_shared()) + compMonitorPtr_(std::make_shared()), lowLatencyListener_(new(std::nothrow) LowLatencyListener), + monitorTaskTimer_(std::make_shared(MONITOR_TASK_TIMER_ID, MONITOR_TASK_DELAY_MS)) { DHLOGI("Ctor ComponentManager"); } @@ -66,6 +71,9 @@ ComponentManager::ComponentManager() : compSource_({}), compSink_({}), compSrcSa ComponentManager::~ComponentManager() { DHLOGD("Dtor ComponentManager"); + compMonitorPtr_.reset(); + compMonitorPtr_ = nullptr; + lowLatencyListener_ = nullptr; } int32_t ComponentManager::Init() @@ -108,7 +116,12 @@ int32_t ComponentManager::Init() HiSysEventWriteMsg(DHFWK_INIT_FAIL, OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, "dhfwk start sink failed."); } - MonitorTaskTimer::GetInstance().StartTimer(); + if (monitorTaskTimer_ != nullptr) { + monitorTaskTimer_->StartTimer(); + } +#ifdef DHARDWARE_LOW_LATENCY + Publisher::GetInstance().RegisterListener(DHTopic::TOPIC_LOW_LATENCY, lowLatencyListener_); +#endif DHLOGI("Init component success"); DHTraceEnd(); return DH_FWK_SUCCESS; @@ -140,7 +153,13 @@ int32_t ComponentManager::UnInit() compSource_.clear(); compSink_.clear(); - MonitorTaskTimer::GetInstance().StopTimer(); + if (monitorTaskTimer_ != nullptr) { + monitorTaskTimer_->StopTimer(); + } +#ifdef DHARDWARE_LOW_LATENCY + Publisher::GetInstance().UnregisterListener(DHTopic::TOPIC_LOW_LATENCY, lowLatencyListener_); + LowLatency::GetInstance().CloseLowLatency(); +#endif DHLOGI("Release component success"); return DH_FWK_SUCCESS; } @@ -339,10 +358,6 @@ int32_t ComponentManager::Enable(const std::string &networkId, const std::string } auto compEnable = std::make_shared(); - if (compEnable == nullptr) { - DHLOGE("compEnable is null"); - return ERR_DH_FWK_POINTER_IS_NULL; - } auto result = compEnable->Enable(networkId, dhId, param, find->second); if (result != DH_FWK_SUCCESS) { for (int32_t retryCount = 0; retryCount < ENABLE_RETRY_MAX_TIMES; retryCount++) { @@ -376,10 +391,6 @@ int32_t ComponentManager::Disable(const std::string &networkId, const std::strin } auto compDisable = std::make_shared(); - if (compDisable == nullptr) { - DHLOGE("compDisable is null"); - return ERR_DH_FWK_POINTER_IS_NULL; - } auto result = compDisable->Disable(networkId, dhId, find->second); if (result != DH_FWK_SUCCESS) { for (int32_t retryCount = 0; retryCount < DISABLE_RETRY_MAX_TIMES; retryCount++) { @@ -521,6 +532,10 @@ void ComponentManager::Recover(DHType dhType) void ComponentManager::DoRecover(DHType dhType) { + int32_t ret = pthread_setname_np(pthread_self(), DO_RECOVER); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("DoRecover setname failed."); + } // step1: restart sa process ReStartSA(dhType); // step2: recover distributed hardware virtual driver diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp index 1ed0dfd802cfb0db5e949def129045f4e0d2cc32..3b461b4712fe20b4d54ce7fb6eb177625386b690 100644 --- a/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -33,6 +34,8 @@ #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" #include "distributed_hardware_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" namespace OHOS { namespace DistributedHardware { @@ -76,13 +79,24 @@ void DistributedHardwareManagerFactory::CheckExitSAOrNot() HiSysEventWriteMsg(DHFWK_EXIT_END, OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "dhfwk sa exit end."); - _Exit(0); + auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityMgr == nullptr) { + DHLOGE("systemAbilityMgr is null"); + return; + } + int32_t ret = systemAbilityMgr->UnloadSystemAbility(DISTRIBUTED_HARDWARE_SA_ID); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("systemAbilityMgr UnLoadSystemAbility failed, ret: %d", ret); + return; + } + DHLOGI("systemAbilityMgr UnLoadSystemAbility success"); + return; } DHLOGI("After uninit, DM report devices online, reinit"); Init(); for (const auto &deviceInfo : deviceList) { - const auto networkId = std::string(deviceInfo.deviceId); + const auto networkId = std::string(deviceInfo.networkId); const auto uuid = GetUUIDBySoftBus(networkId); DHLOGI("Send trusted device online, networkId = %s, uuid = %s", GetAnonyString(networkId).c_str(), GetAnonyString(uuid).c_str()); @@ -99,6 +113,10 @@ bool DistributedHardwareManagerFactory::IsInit() int32_t DistributedHardwareManagerFactory::SendOnLineEvent(const std::string &networkId, const std::string &uuid, uint16_t deviceType) { + int32_t ret = pthread_setname_np(pthread_self(), SEND_ONLINE); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("SendOnLineEvent setname failed."); + } if (networkId.size() == 0 || networkId.size() > MAX_ID_LEN || uuid.size() == 0 || uuid.size() > MAX_ID_LEN) { DHLOGE("NetworkId or uuid is invalid"); return ERR_DH_FWK_PARA_INVALID; diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp index ab92ed6e775ea2ec121c870a47188f7abdd02efe..24cb7a2e33204745cfa2acc49290cf02a8a4394b 100644 --- a/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp @@ -15,15 +15,23 @@ #include "distributed_hardware_service.h" +#include + #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "ipc_types.h" #include "iservice_registry.h" +#include "nlohmann/json.hpp" #include "string_ex.h" #include "system_ability_definition.h" #include "access_manager.h" +#include "av_trans_control_center.h" +#include "capability_info_manager.h" +#include "dh_context.h" +#include "dh_utils_tool.h" #include "dh_utils_hisysevent.h" +#include "distributed_hardware_fwk_kit_paras.h" #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" #include "distributed_hardware_manager_factory.h" @@ -109,10 +117,101 @@ int32_t DistributedHardwareService::PublishMessage(const DHTopic topic, const st return DH_FWK_SUCCESS; } +std::string DistributedHardwareService::QueryLocalSysSpec(const QueryLocalSysSpecType spec) +{ + DeviceInfo localDevInfo = DHContext::GetInstance().GetDeviceInfo(); + std::vector> resInfos; + CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(localDevInfo.deviceId, resInfos); + DHType targetDhType = DHType::UNKNOWN; + std::string targetKey = ""; + switch (spec) { + case QueryLocalSysSpecType::HISTREAMER_AUDIO_ENCODER: + targetKey = KEY_HISTREAMER_AUDIO_ENCODER; + targetDhType = DHType::AUDIO; + break; + case QueryLocalSysSpecType::HISTREAMER_AUDIO_DECODER: + targetKey = KEY_HISTREAMER_AUDIO_DECODER; + targetDhType = DHType::AUDIO; + break; + case QueryLocalSysSpecType::HISTREAMER_VIDEO_ENCODER: + targetKey = KEY_HISTREAMER_VIDEO_ENCODER; + targetDhType = DHType::SCREEN; + break; + case QueryLocalSysSpecType::HISTREAMER_VIDEO_DECODER: + targetKey = KEY_HISTREAMER_VIDEO_DECODER; + targetDhType = DHType::SCREEN; + break; + default: + break; + } + + DHLOGE("QueryLocalSysSpec targetKey: %s, targetDhType: %" PRIu32, targetKey.c_str(), (uint32_t)targetDhType); + if (targetDhType == DHType::UNKNOWN) { + DHLOGE("Can not find matched dhtype"); + return ""; + } + + std::string attrs = ""; + for (const auto &cap : resInfos) { + if (cap->GetDHType() != targetDhType) { + continue; + } + attrs = cap->GetDHAttrs(); + break; + } + if (attrs.empty()) { + DHLOGE("Can not find dh attrs"); + return ""; + } + + return QueryDhSysSpec(targetKey, attrs); +} + +std::string DistributedHardwareService::QueryDhSysSpec(const std::string &targetKey, std::string &attrs) +{ + nlohmann::json attrJson = nlohmann::json::parse(attrs, nullptr, false); + if (attrJson.is_discarded()) { + DHLOGE("attrs json is invalid, attrs: %s", attrs.c_str()); + return ""; + } + + if (!IsString(attrJson, targetKey)) { + DHLOGE("Attrs Json not contains key: %s", targetKey.c_str()); + return ""; + } + return attrJson.at(targetKey).get(); +} + +int32_t DistributedHardwareService::InitializeAVCenter(const TransRole &transRole, int32_t &engineId) +{ + return AVTransControlCenter::GetInstance().InitializeAVCenter(transRole, engineId); +} + +int32_t DistributedHardwareService::ReleaseAVCenter(int32_t engineId) +{ + return AVTransControlCenter::GetInstance().ReleaseAVCenter(engineId); +} + +int32_t DistributedHardwareService::CreateControlChannel(int32_t engineId, const std::string &peerDevId) +{ + return AVTransControlCenter::GetInstance().CreateControlChannel(engineId, peerDevId); +} + +int32_t DistributedHardwareService::NotifyAVCenter(int32_t engineId, const AVTransEvent &event) +{ + return AVTransControlCenter::GetInstance().NotifyAVCenter(engineId, event); +} + +int32_t DistributedHardwareService::RegisterCtlCenterCallback(int32_t engineId, + const sptr &callback) +{ + return AVTransControlCenter::GetInstance().RegisterCtlCenterCallback(engineId, callback); +} + int DistributedHardwareService::Dump(int32_t fd, const std::vector& args) { DHLOGI("DistributedHardwareService Dump."); - + std::vector argsStr {}; for (auto item : args) { argsStr.emplace_back(Str16ToStr8(item)); diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_stub.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_stub.cpp index adaade8789b3191f0eb059b29f063068cb0aae0e..6a268097f5821843f2817bc6e8415ae15b9e55c4 100644 --- a/services/distributedhardwarefwkservice/src/distributed_hardware_stub.cpp +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,9 +21,10 @@ #include "anonymous_string.h" #include "constants.h" -#include "publisher_listener_proxy.h" +#include "dhardware_ipc_interface_code.h" #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" +#include "publisher_listener_proxy.h" namespace OHOS { namespace DistributedHardware { @@ -35,15 +36,33 @@ int32_t DistributedHardwareStub::OnRemoteRequest(uint32_t code, MessageParcel &d return ERR_INVALID_DATA; } switch (code) { - case (uint32_t)IDistributedHardware::Message::REG_PUBLISHER_LISTNER: { + case static_cast(DHMsgInterfaceCode::REG_PUBLISHER_LISTNER): { return RegisterPublisherListenerInner(data, reply); } - case (uint32_t)IDistributedHardware::Message::UNREG_PUBLISHER_LISTENER: { + case static_cast(DHMsgInterfaceCode::UNREG_PUBLISHER_LISTENER): { return UnregisterPublisherListenerInner(data, reply); } - case (uint32_t)IDistributedHardware::Message::PUBLISH_MESSAGE: { + case static_cast(DHMsgInterfaceCode::PUBLISH_MESSAGE): { return PublishMessageInner(data, reply); } + case static_cast(DHMsgInterfaceCode::INIT_CTL_CEN): { + return InitializeAVCenterInner(data, reply); + } + case static_cast(DHMsgInterfaceCode::RELEASE_CTL_CEN): { + return ReleaseAVCenterInner(data, reply); + } + case static_cast(DHMsgInterfaceCode::CREATE_CTL_CEN_CHANNEL): { + return CreateControlChannelInner(data, reply); + } + case static_cast(DHMsgInterfaceCode::NOTIFY_AV_EVENT): { + return NotifyAVCenterInner(data, reply); + } + case static_cast(DHMsgInterfaceCode::REGISTER_CTL_CEN_CALLBACK): { + return RegisterControlCenterCallbackInner(data, reply); + } + case static_cast(DHMsgInterfaceCode::QUERY_LOCAL_SYS_SPEC): { + return QueryLocalSysSpecInner(data, reply); + } default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } @@ -111,6 +130,93 @@ int32_t DistributedHardwareStub::PublishMessageInner(MessageParcel &data, Messag return DH_FWK_SUCCESS; } +int32_t DistributedHardwareStub::QueryLocalSysSpecInner(MessageParcel &data, MessageParcel &reply) +{ + uint32_t specInt = data.ReadUint32(); + if (!ValidQueryLocalSpec(specInt)) { + DHLOGE("Spec invalid: %" PRIu32, specInt); + reply.WriteInt32(ERR_DH_FWK_PARA_INVALID); + return ERR_DH_FWK_PARA_INVALID; + } + + QueryLocalSysSpecType spec = (QueryLocalSysSpecType)specInt; + DHLOGI("Query Local Sys Spec: %" PRIu32, (uint32_t)spec); + std::string res = QueryLocalSysSpec(spec); + DHLOGI("Get Local spec: %s", res.c_str()); + reply.WriteString(res); + return DH_FWK_SUCCESS; +} + +int32_t DistributedHardwareStub::InitializeAVCenterInner(MessageParcel &data, MessageParcel &reply) +{ + TransRole transRole = (TransRole)(data.ReadUint32()); + int32_t engineId = 0; + int32_t ret = InitializeAVCenter(transRole, engineId); + if (!reply.WriteInt32(engineId)) { + DHLOGE("Write engine id failed"); + return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; + } + if (!reply.WriteInt32(ret)) { + DHLOGE("Write ret code failed"); + return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; + } + return DH_FWK_SUCCESS; +} + +int32_t DistributedHardwareStub::ReleaseAVCenterInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t engineId = data.ReadInt32(); + int32_t ret = ReleaseAVCenter(engineId); + if (!reply.WriteInt32(ret)) { + DHLOGE("Write ret code failed"); + return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; + } + return DH_FWK_SUCCESS; +} + +int32_t DistributedHardwareStub::CreateControlChannelInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t engineId = data.ReadInt32(); + std::string peerDevId = data.ReadString(); + int32_t ret = CreateControlChannel(engineId, peerDevId); + if (!reply.WriteInt32(ret)) { + DHLOGE("Write ret code failed"); + return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; + } + return DH_FWK_SUCCESS; +} + +int32_t DistributedHardwareStub::NotifyAVCenterInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t engineId = data.ReadInt32(); + uint32_t type = data.ReadUint32(); + std::string content = data.ReadString(); + std::string peerDevId = data.ReadString(); + int32_t ret = NotifyAVCenter(engineId, AVTransEvent{ (EventType)type, content, peerDevId }); + if (!reply.WriteInt32(ret)) { + DHLOGE("Write ret code failed"); + return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; + } + return DH_FWK_SUCCESS; +} + +int32_t DistributedHardwareStub::RegisterControlCenterCallbackInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t engineId = data.ReadInt32(); + sptr callback = iface_cast(data.ReadRemoteObject()); + if (callback == nullptr) { + DHLOGE("Input av control center callback is null"); + return ERR_DH_FWK_PARA_INVALID; + } + + int32_t ret = RegisterCtlCenterCallback(engineId, callback); + if (!reply.WriteInt32(ret)) { + DHLOGE("Write ret code failed"); + return ERR_DH_FWK_SERVICE_WRITE_INFO_FAIL; + } + return DH_FWK_SUCCESS; +} + bool DistributedHardwareStub::ValidTopic(uint32_t topic) { if (topic <= (uint32_t)DHTopic::TOPIC_MIN || topic >= (uint32_t)DHTopic::TOPIC_MAX) { @@ -118,5 +224,13 @@ bool DistributedHardwareStub::ValidTopic(uint32_t topic) } return true; } + +bool DistributedHardwareStub::ValidQueryLocalSpec(uint32_t spec) +{ + if (spec <= (uint32_t)QueryLocalSysSpecType::MIN || spec >= (uint32_t)QueryLocalSysSpecType::MAX) { + return false; + } + return true; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/src/ipc/publisher_listener_proxy.cpp b/services/distributedhardwarefwkservice/src/ipc/publisher_listener_proxy.cpp index d76ecf842bc798042143b3364b8c34c9e70e5c05..2dc55ec9abbb7a7149ae76ee542be043bc61d77b 100644 --- a/services/distributedhardwarefwkservice/src/ipc/publisher_listener_proxy.cpp +++ b/services/distributedhardwarefwkservice/src/ipc/publisher_listener_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -35,7 +35,7 @@ void PublisherListenerProxy::OnMessage(const DHTopic topic, const std::string& m DHLOGE("Get Remote IRemoteObject failed"); return; } - if (DHTopic::TOPIC_MIN > topic || topic > DHTopic::TOPIC_MAX) { + if (topic < DHTopic::TOPIC_MIN || topic > DHTopic::TOPIC_MAX) { DHLOGE("Topic is invalid!"); return; } @@ -62,7 +62,7 @@ void PublisherListenerProxy::OnMessage(const DHTopic topic, const std::string& m return; } int32_t ret = remote->SendRequest( - static_cast(IPublisherListener::Message::ON_MESSAGE), data, reply, option); + static_cast(IPublisherListener::Message::ON_MESSAGE), data, reply, option); if (ret != 0) { DHLOGE("PublisherListenerProxy send requeset failed, ret: %d", ret); return; diff --git a/services/distributedhardwarefwkservice/src/localhardwaremanager/local_hardware_manager.cpp b/services/distributedhardwarefwkservice/src/localhardwaremanager/local_hardware_manager.cpp index 52faf9f42be820af601561f7319b8e8613b7dc43..44af131803868adacae73618e5e88837974a69ff 100644 --- a/services/distributedhardwarefwkservice/src/localhardwaremanager/local_hardware_manager.cpp +++ b/services/distributedhardwarefwkservice/src/localhardwaremanager/local_hardware_manager.cpp @@ -28,6 +28,10 @@ namespace OHOS { namespace DistributedHardware { +namespace { + constexpr int32_t QUERY_INTERVAL_TIME = 1000 * 1000; // 1s + constexpr int32_t QUERY_RETRY_MAX_TIMES = 3; +} #undef DH_LOG_TAG #define DH_LOG_TAG "LocalHardwareManager" diff --git a/services/distributedhardwarefwkservice/src/lowlatency/low_latency.cpp b/services/distributedhardwarefwkservice/src/lowlatency/low_latency.cpp new file mode 100644 index 0000000000000000000000000000000000000000..048999a885dd0beb60c06f1f4edc5e01109d2709 --- /dev/null +++ b/services/distributedhardwarefwkservice/src/lowlatency/low_latency.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "low_latency.h" + +#include + +#include "res_sched_client.h" +#include "res_type.h" + +#include "constants.h" +#include "distributed_hardware_log.h" +#include "low_latency_timer.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "LowLatency" +IMPLEMENT_SINGLE_INSTANCE(LowLatency); +namespace { + const std::string LOW_LATENCY_TIMER_ID = "low_latency_timer_id"; + constexpr int32_t LOW_LATENCY_DELAY_MS = 50 * 1000; +} + +LowLatency::LowLatency() : lowLatencyTimer_(std::make_shared(LOW_LATENCY_TIMER_ID, + LOW_LATENCY_DELAY_MS)) +{ + DHLOGI("LowLatency ctor!"); +} + +LowLatency::~LowLatency() +{ + DHLOGI("LowLatency dtor!"); +} + +void LowLatency::EnableLowLatency(DHType dhType) +{ + DHLOGI("Start EnableLowLatency dhType: %#X", dhType); + if (dhType <= DHType::UNKNOWN || dhType >= DHType::MAX_DH) { + DHLOGE("DHType is invalid, dhType: %" PRIu32, (uint32_t)dhType); + return; + } + std::lock_guard lock(lowLatencyMutex_); + DHLOGI("lowLatencySwitchSet size: %d", lowLatencySwitchSet_.size()); + if (lowLatencySwitchSet_.empty() && lowLatencyTimer_ != nullptr) { + DHLOGD("Open LowLatency dhType: %#X", dhType); + lowLatencyTimer_->StartTimer(); + } + if (lowLatencySwitchSet_.size() >= MAX_SWITCH_SIZE) { + DHLOGE("lowLatencySwitchSet_ is oversize"); + return; + } + lowLatencySwitchSet_.insert(dhType); + DHLOGI("End EnableLowLatency dhType: %#X", dhType); +} + +void LowLatency::DisableLowLatency(DHType dhType) +{ + DHLOGI("Start DisableLowLatency dhType: %#X", dhType); + if (dhType <= DHType::UNKNOWN || dhType >= DHType::MAX_DH) { + DHLOGE("DHType is invalid, dhType: %" PRIu32, (uint32_t)dhType); + return; + } + std::lock_guard lock(lowLatencyMutex_); + lowLatencySwitchSet_.erase(dhType); + if (lowLatencySwitchSet_.empty() && lowLatencyTimer_ != nullptr) { + DHLOGD("Close LowLatency dhType: %#X", dhType); + lowLatencyTimer_->StopTimer(); + } + DHLOGI("End DisableLowLatency dhType: %#X", dhType); +} + +void LowLatency::CloseLowLatency() +{ + DHLOGI("Shutdown LowLatency"); + std::lock_guard lock(lowLatencyMutex_); + lowLatencySwitchSet_.clear(); + auto &rssClient = OHOS::ResourceSchedule::ResSchedClient::GetInstance(); + // to restore normal latency mode: value = 1 + rssClient.ReportData(OHOS::ResourceSchedule::ResType::RES_TYPE_NETWORK_LATENCY_REQUEST, MODE_DISABLE, + {{LOW_LATENCY_KEY, DH_FWK_PKG_NAME}}); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/src/lowlatency/low_latency_listener.cpp b/services/distributedhardwarefwkservice/src/lowlatency/low_latency_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec0bd52d660318f83d45f36e4f3d3e4c3e998251 --- /dev/null +++ b/services/distributedhardwarefwkservice/src/lowlatency/low_latency_listener.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "constants.h" +#include "dh_utils_tool.h" +#include "distributed_hardware_errno.h" +#include "distributed_hardware_log.h" +#include "low_latency_listener.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "LowLatencyListener" + +LowLatencyListener::LowLatencyListener() +{ + DHLOGI("LowLatencyListener ctor!"); +} + +LowLatencyListener::~LowLatencyListener() +{ + DHLOGI("LowLatencyListener dtor!"); +} + +void LowLatencyListener::OnMessage(const DHTopic topic, const std::string& message) +{ + (void) topic; + (void) message; +#ifdef DHARDWARE_LOW_LATENCY + if (topic <= DHTopic::TOPIC_MIN || topic >= DHTopic::TOPIC_MAX) { + DHLOGE("Topic is invalid, topic: %" PRIu32, (uint32_t)topic); + return; + } + if (message.size() == 0 || message.size() > MAX_MESSAGE_LEN) { + DHLOGE("Message is invalid"); + return; + } + nlohmann::json jsonObj = nlohmann::json::parse(message, nullptr, false); + if (jsonObj.is_discarded()) { + DHLOGE("jsonStr parse failed"); + return; + } + if (!IsUInt32(jsonObj, DH_TYPE)) { + DHLOGE("The DH_TYPE key is invalid"); + return; + } + if (!IsBool(jsonObj, LOW_LATENCY_ENABLE)) { + DHLOGE("The LOW_LATENCY_ENABLE key is invalid"); + return; + } + DHType dhType = jsonObj[DH_TYPE]; + bool isEnable = jsonObj[LOW_LATENCY_ENABLE]; + if (isEnable) { + LowLatency::GetInstance().EnableLowLatency(dhType); + } else { + LowLatency::GetInstance().DisableLowLatency(dhType); + } +#endif +} + +sptr LowLatencyListener::AsObject() +{ + return nullptr; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/src/lowlatency/low_latency_timer.cpp b/services/distributedhardwarefwkservice/src/lowlatency/low_latency_timer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddac02509c9da66d0de3c24193d84b2ce15cbfd4 --- /dev/null +++ b/services/distributedhardwarefwkservice/src/lowlatency/low_latency_timer.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "low_latency_timer.h" + +#include "res_sched_client.h" +#include "res_type.h" + +#include "constants.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "LowLatencyTimer" + +LowLatencyTimer::LowLatencyTimer(std::string timerId, int32_t delayTimeMs) : DHTimer(timerId, delayTimeMs) +{ + DHLOGI("LowLatencyTimer ctor!"); +} + +LowLatencyTimer::~LowLatencyTimer() +{ + DHLOGI("LowLatencyTimer dtor!"); +} + +void LowLatencyTimer::ExecuteInner() +{ + DHLOGD("ExecuteInner"); + auto &rssClient = OHOS::ResourceSchedule::ResSchedClient::GetInstance(); + // to enable low latency mode: value = 0 + rssClient.ReportData(OHOS::ResourceSchedule::ResType::RES_TYPE_NETWORK_LATENCY_REQUEST, MODE_ENABLE, + {{LOW_LATENCY_KEY, DH_FWK_PKG_NAME}}); +} + +void LowLatencyTimer::HandleStopTimer() +{ + DHLOGI("HandleStopTimer!"); + auto &rssClient = OHOS::ResourceSchedule::ResSchedClient::GetInstance(); + // to restore normal latency mode: value = 1 + rssClient.ReportData(OHOS::ResourceSchedule::ResType::RES_TYPE_NETWORK_LATENCY_REQUEST, MODE_DISABLE, + {{LOW_LATENCY_KEY, DH_FWK_PKG_NAME}}); +} +} +} diff --git a/services/distributedhardwarefwkservice/src/publisher/publisher.cpp b/services/distributedhardwarefwkservice/src/publisher/publisher.cpp index 0ce8172be924b8c01544ba91a243c28729dc6b48..199637b75bfd46fe45b4476bf3ed71789a72f823 100644 --- a/services/distributedhardwarefwkservice/src/publisher/publisher.cpp +++ b/services/distributedhardwarefwkservice/src/publisher/publisher.cpp @@ -23,7 +23,8 @@ Publisher::Publisher() : publisherItems_({ { DHTopic::TOPIC_SINK_PROJECT_WINDOW_INFO, std::make_shared(DHTopic::TOPIC_SINK_PROJECT_WINDOW_INFO) }, { DHTopic::TOPIC_STOP_DSCREEN, std::make_shared(DHTopic::TOPIC_STOP_DSCREEN) }, - { DHTopic::TOPIC_DEV_OFFLINE, std::make_shared(DHTopic::TOPIC_DEV_OFFLINE) } + { DHTopic::TOPIC_DEV_OFFLINE, std::make_shared(DHTopic::TOPIC_DEV_OFFLINE) }, + { DHTopic::TOPIC_LOW_LATENCY, std::make_shared(DHTopic::TOPIC_LOW_LATENCY) }, }) { } diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/capability_info.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/capability_info.cpp index fb2783f03a4f3bb97baa11bc8e4ce4d64485f45c..74601f83a19c14e03521b66b1141e5f520115898 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/capability_info.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/capability_info.cpp @@ -21,6 +21,7 @@ #include "anonymous_string.h" #include "constants.h" +#include "dh_utils_tool.h" #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" @@ -167,24 +168,36 @@ void ToJson(nlohmann::json &jsonObject, const CapabilityInfo &capability) void FromJson(const nlohmann::json &jsonObject, CapabilityInfo &capability) { - if (jsonObject.find(DH_ID) != jsonObject.end()) { - capability.SetDHId(jsonObject.at(DH_ID).get()); + if (!IsString(jsonObject, DH_ID)) { + DHLOGE("DH_ID is invalid!"); + return; } - if (jsonObject.find(DEV_ID) != jsonObject.end()) { - capability.SetDeviceId(jsonObject.at(DEV_ID).get()); + capability.SetDHId(jsonObject.at(DH_ID).get()); + if (!IsString(jsonObject, DEV_ID)) { + DHLOGE("DEV_ID is invalid!"); + return; } - if (jsonObject.find(DEV_NAME) != jsonObject.end()) { - capability.SetDeviceName(jsonObject.at(DEV_NAME).get()); + capability.SetDeviceId(jsonObject.at(DEV_ID).get()); + if (!IsString(jsonObject, DEV_NAME)) { + DHLOGE("DEV_NAME is invalid!"); + return; } - if (jsonObject.find(DEV_TYPE) != jsonObject.end()) { - capability.SetDeviceType(jsonObject.at(DEV_TYPE).get()); + capability.SetDeviceName(jsonObject.at(DEV_NAME).get()); + if (!IsUInt16(jsonObject, DEV_TYPE)) { + DHLOGE("DEV_TYPE is invalid!"); + return; } - if (jsonObject.find(DH_TYPE) != jsonObject.end()) { - capability.SetDHType(jsonObject.at(DH_TYPE).get()); + capability.SetDeviceType(jsonObject.at(DEV_TYPE).get()); + if (!IsUInt32(jsonObject, DH_TYPE)) { + DHLOGE("DH_TYPE is invalid!"); + return; } - if (jsonObject.find(DH_ATTRS) != jsonObject.end()) { - capability.SetDHAttrs(jsonObject.at(DH_ATTRS).get()); + capability.SetDHType(jsonObject.at(DH_TYPE).get()); + if (!IsString(jsonObject, DH_ATTRS)) { + DHLOGE("DH_ATTRS is invalid!"); + return; } + capability.SetDHAttrs(jsonObject.at(DH_ATTRS).get()); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/capability_utils.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/capability_utils.cpp index 19d5d29273b33fabf3aa728df1687ba6e686097d..33c429ab3826932c4e80c6799fe7b8c4f586a21d 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/capability_utils.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/capability_utils.cpp @@ -28,10 +28,6 @@ namespace DistributedHardware { int32_t CapabilityUtils::GetCapabilityByValue(const std::string &value, std::shared_ptr &capPtr) { capPtr = std::make_shared(); - if (capPtr == nullptr) { - DHLOGE("capPtr is null"); - return ERR_DH_FWK_RESOURCE_CAPINFO_POINTER_NULL; - } return capPtr->FromJsonString(value); } diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/db_adapter.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/db_adapter.cpp index bc69c925ba69e769657ab43302e75e90d2032583..942c48da2fa621e1ff7f963509c12d7bdd3e888b 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/db_adapter.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/db_adapter.cpp @@ -32,7 +32,13 @@ namespace DistributedHardware { #define DH_LOG_TAG "DBAdapter" namespace { -const std::string DATABASE_DIR = "/data/service/el1/public/database/"; + constexpr int32_t MAX_INIT_RETRY_TIMES = 20; + constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms + constexpr int32_t MANUAL_SYNC_TIMES = 6; + constexpr int32_t MANUAL_SYNC_INTERVAL = 100 * 1000; // 100ms + constexpr int32_t DIED_CHECK_MAX_TIMES = 300; + constexpr int32_t DIED_CHECK_INTERVAL = 100 * 1000; // 100ms + const std::string DATABASE_DIR = "/data/service/el1/public/database/"; } DBAdapter::DBAdapter(const std::string &appId, const std::string &storeId, @@ -360,7 +366,7 @@ void DBAdapter::UnRegisterManualSyncListener() void DBAdapter::OnRemoteDied() { DHLOGI("OnRemoteDied, recover db begin"); - auto ReInitTask = [this] { + auto reInitTask = [this] { int32_t times = 0; while (times < DIED_CHECK_MAX_TIMES) { // init kvStore. @@ -375,7 +381,7 @@ void DBAdapter::OnRemoteDied() usleep(DIED_CHECK_INTERVAL); } }; - DHContext::GetInstance().GetEventBus()->PostTask(ReInitTask, "ReInitTask", 0); + DHContext::GetInstance().GetEventBus()->PostTask(reInitTask, "reInitTask", 0); DHLOGI("OnRemoteDied, recover db end"); } diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/version_info.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/version_info.cpp index 01e14e44527ff3d73f8b433cae4cd4c0fd4e87ee..45193a1335c3d1f327ee613407c81aab18035da2 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/version_info.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/version_info.cpp @@ -51,7 +51,6 @@ void ToJson(nlohmann::json &jsonObject, const VersionInfo &versionInfo) { jsonObject[DEV_ID] = versionInfo.deviceId; jsonObject[DH_VER] = versionInfo.dhVersion; - nlohmann::json compVers; for (const auto &compVersion : versionInfo.compVersions) { nlohmann::json compVer; @@ -62,7 +61,6 @@ void ToJson(nlohmann::json &jsonObject, const VersionInfo &versionInfo) compVer[SINK_VER] = compVersion.second.sinkVersion; compVers.push_back(compVer); } - jsonObject[COMP_VER] = compVers; } diff --git a/services/distributedhardwarefwkservice/src/task/disable_task.cpp b/services/distributedhardwarefwkservice/src/task/disable_task.cpp index 3a4831ab0d879c0452e40a293d84f2aebc28954b..3584fda1ffbedef18dc82dadb1d37f8a7bd0dbf2 100644 --- a/services/distributedhardwarefwkservice/src/task/disable_task.cpp +++ b/services/distributedhardwarefwkservice/src/task/disable_task.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,9 +15,12 @@ #include "disable_task.h" +#include + #include "anonymous_string.h" #include "capability_utils.h" #include "component_manager.h" +#include "constants.h" #include "dh_utils_hitrace.h" #include "dh_utils_tool.h" #include "distributed_hardware_errno.h" @@ -50,6 +53,10 @@ void DisableTask::DoTask() void DisableTask::DoTaskInner() { + int32_t ret = pthread_setname_np(pthread_self(), DISABLE_TASK_INNER); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("DoTaskInner setname failed."); + } DHLOGD("id = %s, uuid = %s, dhId = %s", GetId().c_str(), GetAnonyString(GetUUID()).c_str(), GetAnonyString(GetDhId()).c_str()); SetTaskState(TaskState::RUNNING); diff --git a/services/distributedhardwarefwkservice/src/task/enable_task.cpp b/services/distributedhardwarefwkservice/src/task/enable_task.cpp index 87f3f824573503df34deea8864f33d7f1defc1fc..6d5c346a60c0ef716094796277aeb45b9c726147 100644 --- a/services/distributedhardwarefwkservice/src/task/enable_task.cpp +++ b/services/distributedhardwarefwkservice/src/task/enable_task.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,9 +15,12 @@ #include "enable_task.h" +#include + #include "anonymous_string.h" #include "capability_utils.h" #include "component_manager.h" +#include "constants.h" #include "dh_utils_hitrace.h" #include "dh_utils_tool.h" #include "distributed_hardware_errno.h" @@ -49,6 +52,10 @@ void EnableTask::DoTask() void EnableTask::DoTaskInner() { + int32_t ret = pthread_setname_np(pthread_self(), ENABLE_TASK_INNER); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("DoTaskInner setname failed."); + } DHLOGD("id = %s, uuid = %s, dhId = %s", GetId().c_str(), GetAnonyString(GetUUID()).c_str(), GetAnonyString(GetDhId()).c_str()); SetTaskState(TaskState::RUNNING); @@ -56,7 +63,6 @@ void EnableTask::DoTaskInner() auto state = (result == DH_FWK_SUCCESS) ? TaskState::SUCCESS : TaskState::FAIL; SetTaskState(state); DHLOGD("finish enable task, remove it, id = %s", GetId().c_str()); - TaskBoard::GetInstance().RemoveTask(GetId()); if (result == DH_FWK_SUCCESS) { TaskParam taskParam = { .networkId = GetNetworkId(), @@ -67,6 +73,7 @@ void EnableTask::DoTaskInner() std::string enabledDeviceKey = CapabilityUtils::GetCapabilityKey(GetDeviceIdByUUID(GetUUID()), GetDhId()); TaskBoard::GetInstance().SaveEnabledDevice(enabledDeviceKey, taskParam); } + TaskBoard::GetInstance().RemoveTask(GetId()); } int32_t EnableTask::RegisterHardware() diff --git a/services/distributedhardwarefwkservice/src/task/monitor_task_timer.cpp b/services/distributedhardwarefwkservice/src/task/monitor_task_timer.cpp index d6c0d9b00921c54ffe10b46dff4079bbb87891b8..1dd5d720d8effaeb7acbf20633adfcb78ffc3856 100644 --- a/services/distributedhardwarefwkservice/src/task/monitor_task_timer.cpp +++ b/services/distributedhardwarefwkservice/src/task/monitor_task_timer.cpp @@ -15,114 +15,35 @@ #include "monitor_task_timer.h" -#include "anonymous_string.h" +#include "capability_info.h" #include "capability_info_manager.h" #include "distributed_hardware_errno.h" -#include "distributed_hardware_log.h" +#include "dh_timer.h" #include "task_board.h" #include "task_executor.h" #include "task_factory.h" namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(MonitorTaskTimer); -namespace { - const std::string MONITOR_TASK_TIMER_ID = "monitor_task_timer_id"; - constexpr int32_t DELAY_TIME_MS = 5000; -} #undef DH_LOG_TAG #define DH_LOG_TAG "MonitorTaskTimer" - -MonitorTaskTimer::MonitorTaskTimer() +MonitorTaskTimer::MonitorTaskTimer(std::string timerId, int32_t delayTimeMs) : DHTimer(timerId, delayTimeMs) { - DHLOGI("MonitorTaskTimer construction"); + DHLOGI("MonitorTaskTimer ctor!"); } MonitorTaskTimer::~MonitorTaskTimer() { - DHLOGI("MonitorTaskTimer destruction"); - ReleaseTimer(); -} - -void MonitorTaskTimer::InitTimer() -{ - DHLOGI("start"); - std::unique_lock lock(monitorTaskTimerMutex_); - if (eventHandler_ == nullptr) { - eventHandlerThread_ = std::thread(&MonitorTaskTimer::StartEventRunner, this); - monitorTaskTimerCond_.wait(lock, [this] { - return eventHandler_ != nullptr; - }); - } - DHLOGI("end"); -} - -void MonitorTaskTimer::ReleaseTimer() -{ - DHLOGI("start"); - StopTimer(); - DHLOGI("end"); -} - -void MonitorTaskTimer::StartEventRunner() -{ - DHLOGI("start"); - auto busRunner = AppExecFwk::EventRunner::Create(false); - if (busRunner == nullptr) { - DHLOGE("busRunner is nullptr!"); - return; - } - - { - std::lock_guard lock(monitorTaskTimerMutex_); - eventHandler_ = std::make_shared(busRunner); - } - monitorTaskTimerCond_.notify_all(); - busRunner->Run(); - DHLOGI("end"); + DHLOGI("MonitorTaskTimer dtor!"); } -void MonitorTaskTimer::StartTimer() +void MonitorTaskTimer::ExecuteInner() { - DHLOGI("start"); - InitTimer(); - std::lock_guard lock(monitorTaskTimerMutex_); - if (eventHandler_ == nullptr) { - DHLOGE("eventHandler is nullptr!"); - return; - } - auto monitorTaskTimer = [this] {Execute(eventHandler_);}; - eventHandler_->PostTask(monitorTaskTimer, MONITOR_TASK_TIMER_ID, DELAY_TIME_MS); -} - -void MonitorTaskTimer::StopTimer() -{ - DHLOGI("start"); - std::lock_guard lock(monitorTaskTimerMutex_); - if (eventHandler_ != nullptr) { - eventHandler_->RemoveTask(MONITOR_TASK_TIMER_ID); - if (eventHandler_->GetEventRunner() != nullptr) { - eventHandler_->GetEventRunner()->Stop(); - } - } - if (eventHandlerThread_.joinable()) { - eventHandlerThread_.join(); - } - eventHandler_ = nullptr; - DHLOGI("end"); -} - -void MonitorTaskTimer::Execute(const std::shared_ptr eventHandler) -{ - DHLOGI("start"); - if (eventHandler == nullptr) { - DHLOGE("eventHandler is nullptr!"); - return; - } + DHLOGD("ExecuteInner!"); auto enabledDevices = TaskBoard::GetInstance().GetEnabledDevice(); - std::string capabilityKey; std::shared_ptr capInfoPtr = nullptr; TaskParam taskParam; + std::string capabilityKey; for (auto item : enabledDevices) { capabilityKey = item.first; taskParam = item.second; @@ -137,8 +58,11 @@ void MonitorTaskTimer::Execute(const std::shared_ptrPostTask(monitorTaskTimer, MONITOR_TASK_TIMER_ID, DELAY_TIME_MS); +} + +void MonitorTaskTimer::HandleStopTimer() +{ + DHLOGI("HandleStopTimer!"); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/src/task/offline_task.cpp b/services/distributedhardwarefwkservice/src/task/offline_task.cpp index d73ae1f4fa7bbca9571c1e0618968b743b7261a1..dcfdaa79859639a49d11928f02b2a53e2d23ccc4 100644 --- a/services/distributedhardwarefwkservice/src/task/offline_task.cpp +++ b/services/distributedhardwarefwkservice/src/task/offline_task.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,10 +15,12 @@ #include "offline_task.h" +#include #include #include "anonymous_string.h" #include "capability_info_manager.h" +#include "constants.h" #include "dh_utils_tool.h" #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" @@ -52,9 +54,13 @@ void OffLineTask::DoTask() void OffLineTask::DoTaskInner() { + int32_t ret = pthread_setname_np(pthread_self(), OFFLINE_TASK_INNER); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("DoTaskInner setname failed."); + } DHLOGD("start offline task, id = %s, uuid = %s", GetId().c_str(), GetAnonyString(GetUUID()).c_str()); this->SetTaskState(TaskState::RUNNING); - for (auto& step : this->GetTaskSteps()) { + for (const auto& step : this->GetTaskSteps()) { switch (step) { case TaskStep::UNREGISTER_OFFLINE_DISTRIBUTED_HARDWARE: { CreateDisableTask(); diff --git a/services/distributedhardwarefwkservice/src/task/online_task.cpp b/services/distributedhardwarefwkservice/src/task/online_task.cpp index 8f65bb3699528d823f684a60c7147e0c994ac710..b5475d40ae5d1f3c77c9846d3e22cfc6d92c40bf 100644 --- a/services/distributedhardwarefwkservice/src/task/online_task.cpp +++ b/services/distributedhardwarefwkservice/src/task/online_task.cpp @@ -47,7 +47,7 @@ void OnLineTask::DoTask() { DHLOGD("start online task, id = %s, uuid = %s", GetId().c_str(), GetAnonyString(GetUUID()).c_str()); this->SetTaskState(TaskState::RUNNING); - for (auto& step : this->GetTaskSteps()) { + for (const auto& step : this->GetTaskSteps()) { switch (step) { case TaskStep::SYNC_ONLINE_INFO: { DoSyncInfo(); diff --git a/services/distributedhardwarefwkservice/src/task/task_board.cpp b/services/distributedhardwarefwkservice/src/task/task_board.cpp index f11e9698ae7443a29e899b4ef72bbde5e4724ea9..9fd27e986c276dd7a59f224d9e59eaf077082656 100644 --- a/services/distributedhardwarefwkservice/src/task/task_board.cpp +++ b/services/distributedhardwarefwkservice/src/task/task_board.cpp @@ -117,7 +117,7 @@ void TaskBoard::RemoveEnabledDevice(const std::string &enabledDeviceKey) enabledDevices_.erase(enabledDeviceKey); } -const std::unordered_map& TaskBoard::GetEnabledDevice() +const std::unordered_map TaskBoard::GetEnabledDevice() { std::lock_guard lock(enabledDevicesMutex_); if (enabledDevices_.empty()) { diff --git a/services/distributedhardwarefwkservice/src/task/task_executor.cpp b/services/distributedhardwarefwkservice/src/task/task_executor.cpp index 0d8a649e29974859bec1c64e9fc44a23e45f07ad..a6bb34127c5eec15b4ee6ad76c1bd03d1476892c 100644 --- a/services/distributedhardwarefwkservice/src/task/task_executor.cpp +++ b/services/distributedhardwarefwkservice/src/task/task_executor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,8 +15,10 @@ #include "task_executor.h" +#include #include +#include "constants.h" #include "dh_context.h" #include "distributed_hardware_log.h" #include "event_bus.h" @@ -79,6 +81,10 @@ std::shared_ptr TaskExecutor::PopTask() void TaskExecutor::TriggerTask() { + int32_t ret = pthread_setname_np(pthread_self(), TRIGGER_TASK); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("TriggerTask setname failed."); + } while (taskThreadFlag_) { std::shared_ptr task = PopTask(); if (task == nullptr) { diff --git a/services/distributedhardwarefwkservice/src/utils/dh_timer.cpp b/services/distributedhardwarefwkservice/src/utils/dh_timer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1eb3e4179b80240cc16c6e4aca558be0fd2e2b43 --- /dev/null +++ b/services/distributedhardwarefwkservice/src/utils/dh_timer.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dh_timer.h" + +#include + +#include "anonymous_string.h" +#include "constants.h" +#include "distributed_hardware_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "DHTimer" + +DHTimer::DHTimer(std::string timerId, int32_t delayTimeMs) : timerId_(timerId), delayTimeMs_(delayTimeMs) +{ + DHLOGI("DHTimer ctor!"); +} + +DHTimer::~DHTimer() +{ + DHLOGI("DHTimer dtor!"); + ReleaseTimer(); +} + +void DHTimer::InitTimer() +{ + DHLOGI("start"); + std::unique_lock lock(timerMutex_); + if (eventHandler_ == nullptr) { + eventHandlerThread_ = std::thread(&DHTimer::StartEventRunner, this); + timerCond_.wait(lock, [this] { return eventHandler_ != nullptr; }); + } + DHLOGI("end"); +} + +void DHTimer::ReleaseTimer() +{ + DHLOGI("start"); + std::lock_guard lock(timerMutex_); + if (eventHandler_ != nullptr) { + eventHandler_->RemoveTask(timerId_); + if (eventHandler_->GetEventRunner() != nullptr) { + eventHandler_->GetEventRunner()->Stop(); + } + } + if (eventHandlerThread_.joinable()) { + eventHandlerThread_.join(); + } + eventHandler_ = nullptr; + DHLOGI("end"); +} + +void DHTimer::StartEventRunner() +{ + DHLOGI("start"); + int32_t ret = pthread_setname_np(pthread_self(), EVENT_RUN); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("StartEventRunner setname failed."); + } + auto busRunner = AppExecFwk::EventRunner::Create(false); + if (busRunner == nullptr) { + DHLOGE("busRunner is nullptr!"); + return; + } + { + std::lock_guard lock(timerMutex_); + eventHandler_ = std::make_shared(busRunner); + } + timerCond_.notify_all(); + busRunner->Run(); + DHLOGI("end"); +} + +void DHTimer::StartTimer() +{ + DHLOGI("start"); + InitTimer(); + std::lock_guard lock(timerMutex_); + if (eventHandler_ == nullptr) { + DHLOGE("eventHandler is nullptr"); + return; + } + auto executeFunc = [this] { Execute(); }; + eventHandler_->PostTask(executeFunc, timerId_, delayTimeMs_); +} + +void DHTimer::StopTimer() +{ + DHLOGI("start"); + ReleaseTimer(); + HandleStopTimer(); + DHLOGI("end"); +} + +void DHTimer::Execute() +{ + DHLOGI("start"); + if (eventHandler_ == nullptr) { + DHLOGE("eventHandler is nullptr!"); + return; + } + ExecuteInner(); + auto executeInnerFunc = [this] { Execute(); }; + eventHandler_->PostTask(executeInnerFunc, timerId_, delayTimeMs_); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/fuzztest/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/BUILD.gn index 8de46bca31df81236d969bf394a93d242a3d96ba..4065d2492c4371666496c9151550a42321e75079 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/fuzztest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -16,8 +16,16 @@ group("fuzztest") { deps = [ "accessmanager_fuzzer:fuzztest", + "accessmanageroffline_fuzzer:fuzztest", + "capabilityinfomanager_fuzzer:fuzztest", + "componentdisable_fuzzer:fuzztest", + "componentenable_fuzzer:fuzztest", "componentloader_fuzzer:fuzztest", "componentmanager_fuzzer:fuzztest", + "dhmanagerfactory_fuzzer:fuzztest", + "enabledcompsdump_fuzzer:fuzztest", + "publisher_fuzzer:fuzztest", + "publisheritem_fuzzer:fuzztest", "resourcemanager_fuzzer:fuzztest", "task_fuzzer:fuzztest", "versioninfomanager_fuzzer:fuzztest", diff --git a/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer/BUILD.gn index abe2abd4e52446cd46a0efb825ecc59d9b0a9788..90bbee60b6116cf62535d1eda5bd44604871e679 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,13 +20,9 @@ import( ##############################fuzztest########################################## ohos_fuzztest("AccessmanagerFuzzTest") { module_out_path = "distributed_hardware_fwk/accessmanager" - fuzz_config_file = "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer" include_dirs = [ - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", - "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include", - "//foundation/distributedhardware/device_manager/common/include", "${utils_path}/include", "${utils_path}/include/log", "${common_path}/utils/include", @@ -42,7 +38,9 @@ ohos_fuzztest("AccessmanagerFuzzTest") { ] sources = [ "accessmanager_fuzzer.cpp" ] - deps = [ "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr" ] + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] defines = [ "HI_LOG_ENABLE", @@ -50,7 +48,12 @@ ohos_fuzztest("AccessmanagerFuzzTest") { "LOG_DOMAIN=0xD004100", ] - external_deps = [ "init:libbegetutil" ] + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "init:libbegetutil", + "safwk:system_ability_fwk", + ] } ############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer/accessmanager_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer/accessmanager_fuzzer.cpp index 68c7338674b79de73e307cdb94815e1c85c899b8..c36190d597fd4194b9a145fb55160bcd715084ad 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer/accessmanager_fuzzer.cpp +++ b/services/distributedhardwarefwkservice/test/fuzztest/accessmanager_fuzzer/accessmanager_fuzzer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -29,21 +30,23 @@ namespace OHOS { namespace DistributedHardware { namespace { - constexpr uint16_t TEST_DEV_TYPE_PAD = 0x11; constexpr uint32_t SLEEP_TIME_US = 10 * 1000; } void AccessManagerFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size <= 0)) { + if ((data == nullptr) || (size > DM_MAX_DEVICE_ID_LEN)) { return; } - std::string networkId(reinterpret_cast(data), size); - std::string uuid(reinterpret_cast(data), size); + AccessManager::GetInstance()->Init(); + DmDeviceInfo deviceInfo; + int32_t ret = memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, (reinterpret_cast(data)), size); + if (ret != EOK) { + return; + } + AccessManager::GetInstance()->OnDeviceReady(deviceInfo); - DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent( - networkId, uuid, TEST_DEV_TYPE_PAD); usleep(SLEEP_TIME_US); } } diff --git a/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..83e1ba2dd454abd6c3a29366ec291789107eddd9 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../../distributedhardwarefwk.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AccessManagerOfflineFuzzTest") { + module_out_path = "distributed_hardware_fwk/accessmanageroffline" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "${common_path}/log/include", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/accessmanager", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "accessmanageroffline_fuzzer.cpp" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"AccessManagerOfflineFuzzTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "init:libbegetutil", + "safwk:system_ability_fwk", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":AccessManagerOfflineFuzzTest" ] +} +############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/accessmanageroffline_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/accessmanageroffline_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f110b8390b406a6bc287b63ecc33c80c89b3ce97 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/accessmanageroffline_fuzzer.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accessmanageroffline_fuzzer.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "access_manager.h" +#include "distributed_hardware_errno.h" +#include "distributed_hardware_manager_factory.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + constexpr uint32_t SLEEP_TIME_US = 10 * 1000; +} + +void AccessManagerOfflineFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size > DM_MAX_DEVICE_ID_LEN)) { + return; + } + + AccessManager::GetInstance()->Init(); + DmDeviceInfo deviceInfo; + int32_t ret = memcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, (reinterpret_cast(data)), size); + if (ret != EOK) { + return; + } + AccessManager::GetInstance()->OnDeviceOffline(deviceInfo); + + usleep(SLEEP_TIME_US); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::AccessManagerOfflineFuzzTest(data, size); + return 0; +} + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/accessmanageroffline_fuzzer.h b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/accessmanageroffline_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..70ba50432209459230d572b07d0941ebcedaf412 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/accessmanageroffline_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_ACCESSMANAGEROFFLINE_FUZZER_H +#define TEST_ACCESSMANAGEROFFLINE_FUZZER_H + +#define FUZZ_PROJECT_NAME "accessmanageroffline_fuzzer" + +#endif + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/corpus/init b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..2b595da0c26af63ffb2d5f4132c086b2e5986fce --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/project.xml b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..4fdbc407f205680885fa42663163b5c987f123a6 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/accessmanageroffline_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..53d96b88b42d7c62e749ac34059fb9d3afedc8b9 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../../distributedhardwarefwk.gni") + +##############################fuzztest########################################## +ohos_fuzztest("CapabilityInfoManagerFuzzTest") { + module_out_path = "distributed_hardware_fwk/capabilityinfomanager" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/eventbus", + "${utils_path}/include/log", + "${common_path}/log/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/resourcemanager", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "capabilityinfomanager_fuzzer.cpp" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"CapabilityInfoManagerFuzzTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "init:libbegetutil", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":CapabilityInfoManagerFuzzTest" ] +} +############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/capabilityinfomanager_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/capabilityinfomanager_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf754c4bf6fc6818d274fd9ec91ea60604f434f7 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/capabilityinfomanager_fuzzer.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "capabilityinfomanager_fuzzer.h" + +#include "capability_info_manager.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { + +void CapabilityInfoManagerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size <= sizeof(DistributedKv::ChangeNotification))) { + return; + } + + DistributedKv::Entry insert, update, del; + insert.key = std::string(reinterpret_cast(data), size); + update.key = std::string(reinterpret_cast(data), size); + del.key = std::string(reinterpret_cast(data), size); + insert.value = std::string(reinterpret_cast(data), size); + update.value = std::string(reinterpret_cast(data), size); + del.value = std::string(reinterpret_cast(data), size); + std::vector inserts, updates, deleteds; + inserts.push_back(insert); + updates.push_back(update); + deleteds.push_back(del); + std::string deviceId(reinterpret_cast(data), size); + + DistributedKv::ChangeNotification changeIn(std::move(inserts), std::move(updates), std::move(deleteds), + deviceId, true); + CapabilityInfoManager::GetInstance()->OnChange(changeIn); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::CapabilityInfoManagerFuzzTest(data, size); + return 0; +} + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/capabilityinfomanager_fuzzer.h b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/capabilityinfomanager_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..7765bca2190e2619df9469ca2393e48633a58f41 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/capabilityinfomanager_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_CAPABILITYINFOMANAGER_FUZZER_H +#define TEST_CAPABILITYINFOMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "capabilityinfomanager_fuzzer" + +#endif + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/corpus/init b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..2b595da0c26af63ffb2d5f4132c086b2e5986fce --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/project.xml b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..4fdbc407f205680885fa42663163b5c987f123a6 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/capabilityinfomanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8b703261050510356c22d8ffbd36a3b81777dc45 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../../distributedhardwarefwk.gni") + +##############################fuzztest########################################## +ohos_fuzztest("ComponentDisableFuzzTest") { + module_out_path = "distributed_hardware_fwk/componentdisable" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/eventbus", + "${utils_path}/include/log", + "${common_path}/log/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/componentdisable", + "${services_path}/distributedhardwarefwkservice/include/componentmanager", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "componentdisable_fuzzer.cpp" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"ComponentDisableFuzzTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "init:libbegetutil", + "safwk:system_ability_fwk", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":ComponentDisableFuzzTest" ] +} +############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/componentdisable_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/componentdisable_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46d2158d24c15106561da5300e6c74dd3e973011 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/componentdisable_fuzzer.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "componentdisable_fuzzer.h" + +#include "component_disable.h" +#include "distributed_hardware_errno.h" + +namespace OHOS { +namespace DistributedHardware { + +void ComponentDisableFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + + auto compDisable = std::make_shared(); + std::string uuid(reinterpret_cast(data), size); + std::string dhId(reinterpret_cast(data), size); + int32_t status = DH_FWK_SUCCESS; + std::string disableData(reinterpret_cast(data), size); + compDisable->OnUnregisterResult(uuid, dhId, status, disableData); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::ComponentDisableFuzzTest(data, size); + return 0; +} + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/componentdisable_fuzzer.h b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/componentdisable_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..2e3cc0c24317554bc268b146cb26ac502a9de6ce --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/componentdisable_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_COMPONENTDISABLE_FUZZER_H +#define TEST_COMPONENTDISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "componentdisable_fuzzer" + +#endif + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/corpus/init b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..2b595da0c26af63ffb2d5f4132c086b2e5986fce --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/project.xml b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..4fdbc407f205680885fa42663163b5c987f123a6 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentdisable_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..da3a5914f179396b10bf555a207e10d35493d0b9 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../../distributedhardwarefwk.gni") + +##############################fuzztest########################################## +ohos_fuzztest("ComponentEnableFuzzTest") { + module_out_path = "distributed_hardware_fwk/componentenable" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/eventbus", + "${utils_path}/include/log", + "${common_path}/log/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/componentenable", + "${services_path}/distributedhardwarefwkservice/include/componentmanager", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "componentenable_fuzzer.cpp" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"ComponentEnableFuzzTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "init:libbegetutil", + "safwk:system_ability_fwk", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":ComponentEnableFuzzTest" ] +} +############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/componentenable_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/componentenable_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8943f0ba77d4f05d11cef0cbb24848fd8078e1be --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/componentenable_fuzzer.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "componentenable_fuzzer.h" + +#include "component_enable.h" +#include "distributed_hardware_errno.h" + +namespace OHOS { +namespace DistributedHardware { + +void ComponentEnableFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + + auto compEnable = std::make_shared(); + std::string uuid(reinterpret_cast(data), size); + std::string dhId(reinterpret_cast(data), size); + int32_t status = DH_FWK_SUCCESS; + std::string enableData(reinterpret_cast(data), size); + compEnable->OnRegisterResult(uuid, dhId, status, enableData); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::ComponentEnableFuzzTest(data, size); + return 0; +} + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/componentenable_fuzzer.h b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/componentenable_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..9fa3cb91551574ce125bdab35a2e650a32aa7e1f --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/componentenable_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_COMPONENTENABLE_FUZZER_H +#define TEST_COMPONENTENABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "componentenable_fuzzer" + +#endif + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/corpus/init b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..2b595da0c26af63ffb2d5f4132c086b2e5986fce --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/project.xml b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..4fdbc407f205680885fa42663163b5c987f123a6 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentenable_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer/BUILD.gn index 7eb1b468da89f491c4a4676e40ad10ab6b615c88..295c568696b2521488ee0e5a284dcaac6f80bb5a 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,7 +20,7 @@ import( ##############################fuzztest########################################## ohos_fuzztest("ComponentloaderFuzzTest") { module_out_path = "distributed_hardware_fwk/componentloader" - fuzz_config_file = "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer" include_dirs = [ "include", @@ -44,7 +44,9 @@ ohos_fuzztest("ComponentloaderFuzzTest") { ] sources = [ "componentloader_fuzzer.cpp" ] - deps = [ "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr" ] + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] defines = [ "HI_LOG_ENABLE", diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer/componentloader_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer/componentloader_fuzzer.cpp index 8615305233c2537f5da01272dfaec9a8905732b3..f1d7b904ef2ef59bbfbf58105097cc121ed3b92b 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer/componentloader_fuzzer.cpp +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentloader_fuzzer/componentloader_fuzzer.cpp @@ -35,7 +35,7 @@ const DHType dhTypeFuzz[DH_TYPE_SIZE] = { void ComponentManagerFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size <= 0)) { + if ((data == nullptr) || (size == 0)) { return; } diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer/BUILD.gn index c7981ec701e837345433368b9caa933df90a0a5c..ab54f1c7c41d03f5df767846858f84a95d74f2b7 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,20 +20,22 @@ import( ##############################fuzztest########################################## ohos_fuzztest("ComponentmanagerFuzzTest") { module_out_path = "distributed_hardware_fwk/componentmanager" - fuzz_config_file = "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer" include_dirs = [ + "${av_trans_path}/common/include", + "${innerkits_path}/include", "${utils_path}/include", "${utils_path}/include/log", "${services_path}/distributedhardwarefwkservice/include", "${services_path}/distributedhardwarefwkservice/include/componentmanager", + "${services_path}/distributedhardwarefwkservice/include/lowlatency", "${services_path}/distributedhardwarefwkservice/include/resourcemanager", "${services_path}/distributedhardwarefwkservice/include/utils", + "${services_path}/distributedhardwarefwkservice/include/task", "${common_path}/utils/include", "${common_path}/log/include", "//third_party/json/include", - "//commonlibrary/c_utils/base/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", ] cflags = [ "-g", @@ -43,7 +45,14 @@ ohos_fuzztest("ComponentmanagerFuzzTest") { ] sources = [ "componentmanager_fuzzer.cpp" ] - deps = [ "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr" ] + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_single", + ] defines = [ "HI_LOG_ENABLE", diff --git a/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer/componentmanager_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer/componentmanager_fuzzer.cpp index 1ead2ed89d1af330c90f1c522abf66857dc07cdb..fae73bcf4146949a0d20c4990caf10a1f19bd16c 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer/componentmanager_fuzzer.cpp +++ b/services/distributedhardwarefwkservice/test/fuzztest/componentmanager_fuzzer/componentmanager_fuzzer.cpp @@ -36,7 +36,7 @@ namespace { } void ComponentManagerFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size <= 0)) { + if ((data == nullptr) || (size == 0)) { return; } diff --git a/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..99c1510f37c9394bfe5c69391093e8b26dd38f6c --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +##############################fuzztest########################################## +ohos_fuzztest("DhManagerFactoryFuzzTest") { + module_out_path = "distributed_hardware_fwk/dhmanagerfactory" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "${common_path}/log/include", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/accessmanager", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "dhmanagerfactory_fuzzer.cpp" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DhManagerFactoryFuzzTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "init:libbegetutil", + "safwk:system_ability_fwk", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":DhManagerFactoryFuzzTest" ] +} +############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/corpus/init b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..8eb5a7d6eb6b7d71f0c70c244e5768d62bee6ac5 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/dhmanagerfactory_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/dhmanagerfactory_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b59a509716e3065454ffccabc1a15a6e7e511aa8 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/dhmanagerfactory_fuzzer.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dhmanagerfactory_fuzzer.h" + +#include +#include +#include +#include +#include +#include + +#include "access_manager.h" +#include "distributed_hardware_errno.h" +#include "distributed_hardware_manager_factory.h" + +namespace OHOS { +namespace DistributedHardware { + +void DhManagerFactoryFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + + DHType dhType = DHType::CAMERA; + std::string str(reinterpret_cast(data), size); + std::unordered_map versionMap; + versionMap.insert(std::make_pair(dhType, str)); + DistributedHardwareManagerFactory::GetInstance().GetComponentVersion(versionMap); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::DhManagerFactoryFuzzTest(data, size); + return 0; +} + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/dhmanagerfactory_fuzzer.h b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/dhmanagerfactory_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..d4ca1e17cf086a2ed4b32ea246cb72ad2dedcdc3 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/dhmanagerfactory_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_DHMANAGER_FACTORY_FUZZER_H +#define TEST_DHMANAGER_FACTORY_FUZZER_H + +#define FUZZ_PROJECT_NAME "dhmanagerfactory_fuzzer" + +#endif + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/project.xml b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/dhmanagerfactory_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..63977aecf2a3a348430b8915ff77511b89dcbe18 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +##############################fuzztest########################################## +ohos_fuzztest("EnabledCompsDumpFuzzTest") { + module_out_path = "distributed_hardware_fwk/enabledcompsdump" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "${common_path}/log/include", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/hidumphelper", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "enabledcompsdump_fuzzer.cpp" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"EnabledCompsDumpFuzzTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "init:libbegetutil", + "safwk:system_ability_fwk", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":EnabledCompsDumpFuzzTest" ] +} +############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/corpus/init b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..8eb5a7d6eb6b7d71f0c70c244e5768d62bee6ac5 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/enabledcompsdump_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/enabledcompsdump_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da8996db235a6543604576d4a5c5390d42335fbf --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/enabledcompsdump_fuzzer.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "enabledcompsdump_fuzzer.h" + +#include +#include +#include +#include +#include +#include + +#include "distributed_hardware_errno.h" +#include "enabled_comps_dump.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const uint32_t DH_TYPE_SIZE = 10; + const DHType dhTypeFuzz[DH_TYPE_SIZE] = { + DHType::CAMERA, DHType::AUDIO, DHType::SCREEN, DHType::VIRMODEM_MIC, + DHType::INPUT, DHType::A2D, DHType::GPS, DHType::HFP, DHType::VIRMODEM_SPEAKER + }; +} + +void EnableedCompsDumpFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + + std::string networkId(reinterpret_cast(data), size); + std::string dhId(reinterpret_cast(data), size); + DHType dhType = dhTypeFuzz[data[0] % DH_TYPE_SIZE]; + + std::set compInfoSet {}; + EnabledCompsDump::GetInstance().DumpEnabledComp(networkId, dhType, dhId); + EnabledCompsDump::GetInstance().Dump(compInfoSet); + EnabledCompsDump::GetInstance().DumpDisabledComp(networkId, dhType, dhId); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::EnableedCompsDumpFuzzTest(data, size); + return 0; +} + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/enabledcompsdump_fuzzer.h b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/enabledcompsdump_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..7d6e0a890a406bd6bd8d5dec7fabbd8a1297ab01 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/enabledcompsdump_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_ENABLEEDCOMPSDUMP_FUZZER_H +#define TEST_ENABLEEDCOMPSDUMP_FUZZER_H + +#define FUZZ_PROJECT_NAME "enableedcompsdump_fuzzer" + +#endif + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/project.xml b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/enabledcompsdump_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6f2f7a1eee2cb73d982a3188198f7c62fe40939d --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +##############################fuzztest########################################## +ohos_fuzztest("PublisherFuzzTest") { + module_out_path = "distributed_hardware_fwk/publisher" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "${common_path}/log/include", + "${innerkits_path}/include", + "${innerkits_path}/include/ipc", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/utils", + "${services_path}/distributedhardwarefwkservice/include/publisher", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "publisher_fuzzer.cpp" ] + + deps = [ + "${innerkits_path}:libdhfwk_sdk", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"PublisherFuzzTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "eventhandler:libeventhandler", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":PublisherFuzzTest" ] +} +############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/corpus/init b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..8eb5a7d6eb6b7d71f0c70c244e5768d62bee6ac5 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/project.xml b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/publisher_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/publisher_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf29fd5a949c26a4cd2c2509126e2c8e54a3c3aa --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/publisher_fuzzer.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "publisher_fuzzer.h" + +#include +#include +#include +#include +#include +#include + +#include "distributed_hardware_errno.h" +#include "publisher.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const uint32_t TOPIC_SIZE = 4; + const DHTopic topicFuzz[TOPIC_SIZE] = { + DHTopic::TOPIC_START_DSCREEN, DHTopic::TOPIC_SINK_PROJECT_WINDOW_INFO, + DHTopic::TOPIC_STOP_DSCREEN, DHTopic::TOPIC_DEV_OFFLINE + }; +} + +void MockPublisherListener::OnMessage(const DHTopic topic, const std::string &message) +{ + (void)topic; + (void)message; +} + +int32_t MockPublisherListener::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + (void)code; + (void)data; + (void)reply; + (void)option; + return DH_FWK_SUCCESS; +} + +void PublisherListenerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + + DHTopic topic = topicFuzz[data[0] % TOPIC_SIZE]; + sptr listener = new MockPublisherListener(); + std::string message(reinterpret_cast(data), size); + + Publisher::GetInstance().RegisterListener(topic, listener); + Publisher::GetInstance().PublishMessage(topic, message); + Publisher::GetInstance().UnregisterListener(topic, listener); +} +} // namespace DistributedHardware +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::PublisherListenerFuzzTest(data, size); + return 0; +} + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/publisher_fuzzer.h b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/publisher_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..92e46232cdf64299f38da083a55fc8be6e09e156 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisher_fuzzer/publisher_fuzzer.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_PUBLISHER_FUZZER_H +#define TEST_PUBLISHER_FUZZER_H + +#define FUZZ_PROJECT_NAME "publisher_fuzzer" + +#include + +#include "iremote_stub.h" + +#include "ipublisher_listener.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { + +#define REMOVE_NO_USE_CONSTRUCTOR(className) \ +private: \ + className(const className&) = delete; \ + className& operator= (const className&) = delete; \ + className(className&&) = delete; \ + className& operator= (className&&) = delete; \ + +class MockPublisherListener : public IRemoteStub { +public: + MockPublisherListener() = default; + virtual ~MockPublisherListener() = default; + void OnMessage(const DHTopic topic, const std::string &message) override; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2020a84f8231c34ffce9dde7293e59686312d91f --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +##############################fuzztest########################################## +ohos_fuzztest("PublisherItemFuzzTest") { + module_out_path = "distributed_hardware_fwk/publisheritem" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "${common_path}/log/include", + "${innerkits_path}/include", + "${innerkits_path}/include/ipc", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/publisher", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "publisheritem_fuzzer.cpp" ] + + deps = [ + "${innerkits_path}:libdhfwk_sdk", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"PublisherItemFuzzTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "eventhandler:libeventhandler", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":PublisherItemFuzzTest" ] +} +############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/corpus/init b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..8eb5a7d6eb6b7d71f0c70c244e5768d62bee6ac5 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/project.xml b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/publisheritem_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/publisheritem_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0929a48f9dec66097cc89148d9e3d49ec54b6e21 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/publisheritem_fuzzer.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "publisheritem_fuzzer.h" + +#include +#include +#include +#include +#include +#include + +#include "publisher_item.h" +#include "distributed_hardware_errno.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const uint32_t TOPIC_SIZE = 4; + const DHTopic topicFuzz[TOPIC_SIZE] = { + DHTopic::TOPIC_START_DSCREEN, DHTopic::TOPIC_SINK_PROJECT_WINDOW_INFO, + DHTopic::TOPIC_STOP_DSCREEN, DHTopic::TOPIC_DEV_OFFLINE + }; +} + +void MockPublisherItemListener::OnMessage(const DHTopic topic, const std::string &message) +{ + (void)topic; + (void)message; +} + +int32_t MockPublisherItemListener::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + (void)code; + (void)data; + (void)reply; + (void)option; + return DH_FWK_SUCCESS; +} + +void PublisherItemFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + + DHTopic topic = topicFuzz[data[0] % TOPIC_SIZE]; + sptr listener = new MockPublisherItemListener(); + std::string message(reinterpret_cast(data), size); + + PublisherItem publisherItem(topic); + + publisherItem.AddListener(listener); + publisherItem.PublishMessage(message); + publisherItem.RemoveListener(listener); +} +} // namespace DistributedHardware +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::PublisherItemFuzzTest(data, size); + return 0; +} + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/publisheritem_fuzzer.h b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/publisheritem_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..cbfb552d445b70b5f1a5afed3131bd079843d8f0 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/fuzztest/publisheritem_fuzzer/publisheritem_fuzzer.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_PUBLISHER_ITEM_FUZZER_H +#define TEST_PUBLISHER_ITEM_FUZZER_H + +#define FUZZ_PROJECT_NAME "publisheritem_fuzzer" + +#include + +#include "iremote_stub.h" + +#include "ipublisher_listener.h" + +namespace OHOS { +namespace DistributedHardware { + +#define REMOVE_NO_USE_CONSTRUCTOR(className) \ +private: \ + className(const className&) = delete; \ + className& operator= (const className&) = delete; \ + className(className&&) = delete; \ + className& operator= (className&&) = delete; \ + +class MockPublisherItemListener : public IRemoteStub { +public: + MockPublisherItemListener() = default; + virtual ~MockPublisherItemListener() = default; + void OnMessage(const DHTopic topic, const std::string &message) override; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif + diff --git a/services/distributedhardwarefwkservice/test/fuzztest/resourcemanager_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/resourcemanager_fuzzer/BUILD.gn index cd2bba4110632edf5349a5c2fd6d1d24bd677685..14e3b3b8a03a9e0a664170b8ffa828cbae234634 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/resourcemanager_fuzzer/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/fuzztest/resourcemanager_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -31,12 +31,7 @@ ohos_fuzztest("ResourcemanagerFuzzTest") { "${services_path}/distributedhardwarefwkservice/include/utils", "${common_path}/utils/include", "${common_path}/log/include", - "//base/notification/eventhandler/interfaces/inner_api", - "//commonlibrary/c_utils/base/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", "//third_party/json/include", - "//utils/system/safwk/native/include", ] cflags = [ "-g", @@ -46,7 +41,9 @@ ohos_fuzztest("ResourcemanagerFuzzTest") { ] sources = [ "resourcemanager_fuzzer.cpp" ] - deps = [ "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr" ] + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] defines = [ "HI_LOG_ENABLE", @@ -54,7 +51,12 @@ ohos_fuzztest("ResourcemanagerFuzzTest") { "LOG_DOMAIN=0xD004100", ] - external_deps = [ "c_utils:utils" ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "ipc:ipc_single", + "kv_store:distributeddata_inner", + ] } ############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer/BUILD.gn index 30dd02cb398b98fba39fda40089e185b0026303b..8573c335301d8135d66e9c711e94c1d8068aa49d 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,7 +20,8 @@ import( ##############################fuzztest########################################## ohos_fuzztest("TaskFuzzTest") { module_out_path = "distributed_hardware_fwk/task" - fuzz_config_file = "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer" + fuzz_config_file = + "${services_path}/distributedhardwarefwkservice/test/fuzztest/task_fuzzer" include_dirs = [ "include", @@ -32,7 +33,6 @@ ohos_fuzztest("TaskFuzzTest") { "${services_path}/distributedhardwarefwkservice/include/utils", "${common_path}/utils/include", "${common_path}/log/include", - "//commonlibrary/c_utils/base/include", ] cflags = [ "-g", @@ -42,7 +42,11 @@ ohos_fuzztest("TaskFuzzTest") { ] sources = [ "task_fuzzer.cpp" ] - deps = [ "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr" ] + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] + + external_deps = [ "c_utils:utils" ] defines = [ "HI_LOG_ENABLE", diff --git a/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer/task_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer/task_fuzzer.cpp index 22f17590b8ed3b756dfc34f4fa8eefee2989eb8c..1d2e1216c999658bf2f8da6f57bb2f4b1299ca1b 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer/task_fuzzer.cpp +++ b/services/distributedhardwarefwkservice/test/fuzztest/task_fuzzer/task_fuzzer.cpp @@ -42,7 +42,7 @@ namespace { void TaskFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size <= 0)) { + if ((data == nullptr) || (size == 0)) { return; } diff --git a/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer/BUILD.gn b/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer/BUILD.gn index 9b71d23db24a9c6a17ce06c391e0fa59df5ddb86..1ff3955da5c699b8b55738997f7e8802f7196063 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,11 +20,9 @@ import( ##############################fuzztest########################################## ohos_fuzztest("VersioninfoManagerFuzzTest") { module_out_path = "distributed_hardware_fwk/versioninfomanager" - fuzz_config_file = "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer" + fuzz_config_file = "${services_path}/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer" include_dirs = [ - "//base/notification/eventhandler/interfaces/inner_api", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", "${utils_path}/include", "${utils_path}/include/log", "${utils_path}/include/eventbus", @@ -34,8 +32,6 @@ ohos_fuzztest("VersioninfoManagerFuzzTest") { "${common_path}/utils/include", "${common_path}/log/include", "//third_party/json/include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", ] cflags = [ "-g", @@ -45,7 +41,9 @@ ohos_fuzztest("VersioninfoManagerFuzzTest") { ] sources = [ "versioninfomanager_fuzzer.cpp" ] - deps = [ "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr" ] + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + ] defines = [ "HI_LOG_ENABLE", @@ -53,7 +51,11 @@ ohos_fuzztest("VersioninfoManagerFuzzTest") { "LOG_DOMAIN=0xD004100", ] - external_deps = [ "c_utils:utils" ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "kv_store:distributeddata_inner", + ] } ############################################################################### diff --git a/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer/versioninfomanager_fuzzer.cpp b/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer/versioninfomanager_fuzzer.cpp index 264e442167b48992eacee4fbdea2ffa94659e39f..a42e3c7cdec8bae8a52c496fa4b1eaa293c35222 100644 --- a/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer/versioninfomanager_fuzzer.cpp +++ b/services/distributedhardwarefwkservice/test/fuzztest/versioninfomanager_fuzzer/versioninfomanager_fuzzer.cpp @@ -39,7 +39,7 @@ namespace { void VersioninfoManagerFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size <= 0)) { + if ((data == nullptr) || (size == 0)) { return; } diff --git a/services/distributedhardwarefwkservice/test/unittest/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/BUILD.gn index eb44ec1b2828ec989195af6e00761070263fc733..38fc2303bc3286c8fc03a1f53afa446743c25541 100644 --- a/services/distributedhardwarefwkservice/test/unittest/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/BUILD.gn @@ -17,14 +17,24 @@ group("test") { deps = [ "common/accessmanager:AccessManagerTest", "common/componentloader:component_loader_test", - "common/componentmanager:component_manager_test", + "common/componentmanager/component_manager:component_manager_test", + "common/componentmanager/component_monitior:component_monitor_test", "common/dbadapter:db_adapter_test", "common/distributedhardwaremanager:distributed_hardware_manager_test", "common/distributedhardwareservice:distributed_hardware_service_test", - "common/localhardwaremanager:local_hardware_manager_test", + "common/distributedhardwarestub:distributed_hardware_stub_test", + "common/hidumphelper/enabledcompsdump:enabled_comps_dump_test", + "common/hidumphelper/hidumphelper:hidump_helper_test", + "common/ipc:publisher_listener_proxy_test", + "common/localhardwaremanager/localhardwaremanager:local_hardware_manager_test", + "common/localhardwaremanager/pluginlistenerimpl:plugin_listener_impl_test", + "common/lowlatency/lowlatency:low_latency_test", + "common/lowlatency/lowlatencylistener:low_latency_listener_test", + "common/publisher:publisher_item_test", "common/resourcemanager:resource_manager_test", "common/task:dh_task_test", - "common/versioninfomanager:versioninfo_manager_test", + "common/versioninfomanager/versioninfo:version_info_test", + "common/versioninfomanager/versioninfomanager:versioninfo_manager_test", "common/versionmanager:version_manager_test", ] } diff --git a/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/BUILD.gn index 212af2c63f5f234b3972e867f354bab2e92e300e..490c99d5ed3a309a65c0f0fcc669120856cc74b0 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -19,13 +19,7 @@ module_out_path = "distributed_hardware_fwk/access_manager_test" config("module_private_config") { include_dirs = [ - "//base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include", - "//base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter", - "//base/notification/eventhandler/interfaces/inner_api", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", - "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include", - "//foundation/distributedhardware/device_manager/common/include", + "//third_party/json/include", "${utils_path}/include", "${utils_path}/include/log", "${common_path}/utils/include", @@ -50,9 +44,8 @@ ohos_unittest("AccessManagerTest") { configs = [ ":module_private_config" ] deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", "${utils_path}:distributedhardwareutils", - "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp:devicemanagersdk", - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", "//third_party/googletest:gtest_main", ] defines = [ @@ -61,7 +54,16 @@ ohos_unittest("AccessManagerTest") { "LOG_DOMAIN=0xD004100", ] - external_deps = [ "init:libbegetutil" ] + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "eventhandler:libeventhandler", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] } group("unittest") { diff --git a/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/access_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/access_manager_test.cpp index 49e18d06c57663990a400b1a8e74fc6c178098eb..8955b0750b27d20a446eb981b707be3db147515a 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/access_manager_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/access_manager_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,14 +15,18 @@ #include #include +#include #include #include #include "gtest/gtest.h" +#define private public #include "access_manager.h" -#include "distributed_hardware_errno.h" #include "distributed_hardware_manager_factory.h" +#undef private +#include "dm_device_info.h" +#include "distributed_hardware_errno.h" using namespace testing::ext; namespace OHOS { @@ -33,7 +37,6 @@ enum class Status : uint32_t { DEVICE_OFFLINE = 1, }; -constexpr int32_t INTERVAL_TIME_MS = 100; constexpr uint16_t TEST_DEV_TYPE_PAD = 0x11; /* save networkId and uuid */ @@ -51,24 +54,14 @@ public: static void TearDownTestCase(void); void SetUp(); void TearDown(); - std::mutex testAccessMutex_; }; void AccessManagerTest::SetUp() { - // at last one device online, ensure sa not exit - std::string networkId = "00000000000000000000000000000000"; - std::string uuid = "99999999999999999999999999999999"; - DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(networkId, uuid, TEST_DEV_TYPE_PAD); + DistributedHardwareManagerFactory::GetInstance().isInit = true; } -void AccessManagerTest::TearDown() -{ - // clear all the online devices - for (const auto &dev : TEST_DEVICES) { - DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(dev.first, dev.second, TEST_DEV_TYPE_PAD); - } -} +void AccessManagerTest::TearDown() {} void AccessManagerTest::SetUpTestCase() {} @@ -126,7 +119,7 @@ HWTEST_F(AccessManagerTest, SendOffLineEvent_001, TestSize.Level1) for (const auto &dev : TEST_DEVICES) { auto ret = DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(dev.first, dev.second, TEST_DEV_TYPE_PAD); - ASSERT_EQ(DH_FWK_SUCCESS, ret); + ASSERT_NE(DH_FWK_SUCCESS, ret); ASSERT_TRUE(DistributedHardwareManagerFactory::GetInstance().IsInit()); } @@ -135,7 +128,7 @@ HWTEST_F(AccessManagerTest, SendOffLineEvent_001, TestSize.Level1) DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(dev.first, dev.second, TEST_DEV_TYPE_PAD); ASSERT_EQ(DH_FWK_SUCCESS, ret); } - ASSERT_TRUE(DistributedHardwareManagerFactory::GetInstance().IsInit()); + ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit()); } /** @@ -161,80 +154,265 @@ HWTEST_F(AccessManagerTest, SendOffLineEvent_002, TestSize.Level1) /** * @tc.name: SendOffLineEvent_003 - * @tc.desc: Verify the SendOnLineEvent for Multi-thread + * @tc.desc: Verify the SendOffLineEvent function * @tc.type: FUNC * @tc.require: AR000GHSJM */ HWTEST_F(AccessManagerTest, SendOffLineEvent_003, TestSize.Level0) { - auto handler = [this](Status status, std::string networkId, std::string uuid, int32_t expect) { - if (status == Status::DEVICE_ONLINE) { - std::lock_guard lock(testAccessMutex_); - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - auto onlineResult = - DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(networkId, uuid, TEST_DEV_TYPE_PAD); - EXPECT_EQ(expect, onlineResult); - } else { - std::lock_guard lock(testAccessMutex_); - std::this_thread::sleep_for(std::chrono::milliseconds(90)); - auto offlineResult = - DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(networkId, uuid, TEST_DEV_TYPE_PAD); - EXPECT_EQ(expect, offlineResult); - } - }; + ASSERT_TRUE(DistributedHardwareManagerFactory::GetInstance().IsInit()); + uint32_t maxIdLen = 257; + std::string networkId; + std::string networkId1; + networkId1.resize(maxIdLen); + std::string networkId2 = "networkId3"; + std::string uuid; + std::string uuid1; + uuid1.resize(maxIdLen); + std::string uuid2 = "uuid3"; + uint16_t deviceType = 1; + int32_t ret = DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(networkId, uuid, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); + + int32_t ret1 = DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(networkId1, uuid, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret1); + + int32_t ret2 = DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(networkId2, uuid, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret2); + + int32_t ret3 = DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(networkId2, uuid1, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret3); + + int32_t ret4 = DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(networkId2, uuid2, deviceType); + EXPECT_EQ(ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_OFFLINE, ret4); +} - std::vector threadVec; - threadVec.emplace_back( - std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[0].first, TEST_DEVICES[0].second, DH_FWK_SUCCESS)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: Init_001 + * @tc.desc: Verify the Init function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, Init_001, TestSize.Level0) +{ + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} - threadVec.emplace_back( - std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[1].first, TEST_DEVICES[1].second, DH_FWK_SUCCESS)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: OnRemoteDied_001 + * @tc.desc: Verify the OnRemoteDied function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnRemoteDied_001, TestSize.Level0) +{ + AccessManager::GetInstance()->OnRemoteDied(); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} - threadVec.emplace_back(std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[0].first, TEST_DEVICES[0].second, - ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_ONLINE)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: OnDeviceOnline_001 + * @tc.desc: Verify the OnDeviceOnline function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnDeviceOnline_001, TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + AccessManager::GetInstance()->OnDeviceOnline(deviceInfo); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} - threadVec.emplace_back( - std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[2].first, TEST_DEVICES[2].second, DH_FWK_SUCCESS)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: OnDeviceOffline_001 + * @tc.desc: Verify the OnDeviceOffline function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnDeviceOffline_001, TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + AccessManager::GetInstance()->OnDeviceOffline(deviceInfo); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} - threadVec.emplace_back( - std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[3].first, TEST_DEVICES[3].second, DH_FWK_SUCCESS)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: OnDeviceOffline_002 + * @tc.desc: Verify the OnDeviceOffline function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnDeviceOffline_002, TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + std::string devId = "000001"; + int32_t ret = memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, devId.c_str(), devId.length()); + if (ret != EOK) { + return; + } + AccessManager::GetInstance()->OnDeviceOffline(deviceInfo); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} - threadVec.emplace_back( - std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[3].first, TEST_DEVICES[3].second, DH_FWK_SUCCESS)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: OnDeviceOffline_003 + * @tc.desc: Verify the OnDeviceOffline function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnDeviceOffline_003, TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + std::string devId = "000001"; + int32_t ret = memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, devId.c_str(), devId.length()); + if (ret != EOK) { + return; + } + std::string netId = "000002"; + ret = memcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, netId.c_str(), netId.length()); + if (ret != EOK) { + return; + } + AccessManager::GetInstance()->OnDeviceOffline(deviceInfo); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} - threadVec.emplace_back(std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[3].first, TEST_DEVICES[3].second, - ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_OFFLINE)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: OnDeviceReady_001 + * @tc.desc: Verify the OnDeviceReady function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnDeviceReady_001, TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + AccessManager::GetInstance()->OnDeviceReady(deviceInfo); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} + +/** + * @tc.name: OnDeviceReady_002 + * @tc.desc: Verify the OnDeviceReady function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnDeviceReady_002, TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + std::string devId = "000001"; + int32_t ret = memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, devId.c_str(), devId.length()); + if (ret != EOK) { + return; + } + AccessManager::GetInstance()->OnDeviceReady(deviceInfo); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} + +/** + * @tc.name: OnDeviceReady_003 + * @tc.desc: Verify the OnDeviceReady function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnDeviceReady_003, TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + std::string devId = "000001"; + int32_t ret = memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, devId.c_str(), devId.length()); + if (ret != EOK) { + return; + } + std::string netId = "000002"; + ret = memcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, netId.c_str(), netId.length()); + if (ret != EOK) { + return; + } + AccessManager::GetInstance()->OnDeviceReady(deviceInfo); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} + +/** + * @tc.name: OnDeviceChanged_001 + * @tc.desc: Verify the OnDeviceChanged function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, OnDeviceChanged_001, TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + AccessManager::GetInstance()->OnDeviceChanged(deviceInfo); + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); +} + +/** + * @tc.name: UnInit_001 + * @tc.desc: Verify the UnInit function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, UnInit_001, TestSize.Level0) +{ + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->UnInit()); +} - threadVec.emplace_back( - std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[1].first, TEST_DEVICES[1].second, DH_FWK_SUCCESS)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: UnInit_002 + * @tc.desc: Verify the Init function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, UnInit_002, TestSize.Level0) +{ + DistributedHardwareManagerFactory::GetInstance().UnInit(); + bool ret = DistributedHardwareManagerFactory::GetInstance().IsInit(); + EXPECT_EQ(false, ret); +} - threadVec.emplace_back( - std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[0].first, TEST_DEVICES[0].second, DH_FWK_SUCCESS)); - std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS)); +/** + * @tc.name: RegisterDevStateCallback_001 + * @tc.desc: Verify the RegisterDevStateCallback function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, RegisterDevStateCallback_001, TestSize.Level0) +{ + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->RegisterDevStateCallback()); +} - threadVec.emplace_back( - std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[2].first, TEST_DEVICES[2].second, DH_FWK_SUCCESS)); +/** + * @tc.name: UnRegisterDevStateCallback_001 + * @tc.desc: Verify the UnRegisterDevStateCallback function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, UnRegisterDevStateCallback_001, TestSize.Level0) +{ + EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->UnRegisterDevStateCallback()); +} - for_each(threadVec.begin(), threadVec.end(), [](std::thread &t) { t.join(); }); +/** + * @tc.name: GetComponentVersion_001 + * @tc.desc: Verify the GetComponentVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(AccessManagerTest, GetComponentVersion_001, TestSize.Level0) +{ + std::unordered_map versionMap; + int32_t ret = DistributedHardwareManagerFactory::GetInstance().GetComponentVersion(versionMap); + EXPECT_NE(DH_FWK_SUCCESS, ret); } /** - * @tc.name: AccessManagerInit - * @tc.desc: Verify the Init function + * @tc.name: CheckExitSAOrNot_001 + * @tc.desc: Verify the CheckExitSAOrNot function * @tc.type: FUNC * @tc.require: AR000GHSJM */ -HWTEST_F(AccessManagerTest, AccessManagerInit, TestSize.Level0) +HWTEST_F(AccessManagerTest, CheckExitSAOrNot_001, TestSize.Level0) { - EXPECT_EQ(DH_FWK_SUCCESS, AccessManager::GetInstance()->Init()); + DistributedHardwareManagerFactory::GetInstance().CheckExitSAOrNot(); + ASSERT_TRUE(DistributedHardwareManagerFactory::GetInstance().IsInit()); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentloader/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/componentloader/BUILD.gn index 55056e875c9ec4d555568ce47e33f0beb93a6b9e..35a03a685bccf5d775128c9faf6ae3320f43f282 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/componentloader/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentloader/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -25,10 +25,12 @@ config("module_private_config") { "${utils_path}/include/eventbus", "${utils_path}/include/log", "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/hidumphelper", "${services_path}/distributedhardwarefwkservice/include/versionmanager", "${services_path}/distributedhardwarefwkservice/include/resourcemanager", "${services_path}/distributedhardwarefwkservice/include/componentloader", "${services_path}/distributedhardwarefwkservice/include/utils", + "${services_path}/distributedhardwarefwkservice/src", "${common_path}/utils/include", "${common_path}/log/include", "//third_party/json/include", @@ -43,10 +45,17 @@ ohos_unittest("ComponentLoaderTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", "//third_party/googletest:gtest_main", ] + external_deps = [ + "config_policy:configpolicy_util", + "hitrace:hitrace_meter", + "kv_store:distributeddata_inner", + ] + defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"ComponentLoaderTest\"", diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentloader/include/component_loader_test.h b/services/distributedhardwarefwkservice/test/unittest/common/componentloader/include/component_loader_test.h index a606eca7859a2c9ad5bb898b42a37cb339808e34..d0d847d835cb70edb1a80ebe2eccc5fc449101a2 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/componentloader/include/component_loader_test.h +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentloader/include/component_loader_test.h @@ -17,7 +17,9 @@ #define OHOS_DISTRIBUTED_HARDWARE_COMPONENT_LOADER_TEST_H #include - +#define private public +#include "componentloader/component_loader.cpp" +#undef private namespace OHOS { namespace DistributedHardware { class ComponentLoaderTest : public testing::Test { diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentloader/src/component_loader_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/componentloader/src/component_loader_test.cpp index 7838556d0c6294349c6a13ea90677f705f28f816..e18cd4420354115ebd26d74ed1831f33d6bbef34 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/componentloader/src/component_loader_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentloader/src/component_loader_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,11 @@ #define private public #include "component_loader.h" #undef private +#include "distributed_hardware_log.h" +#include "hitrace_meter.h" +#include "hidump_helper.h" +#include "kvstore_observer.h" +#include "nlohmann/json.hpp" #include "versionmanager/version_manager.h" using namespace testing::ext; @@ -41,6 +46,7 @@ void ComponentLoaderTest::TearDown() { ComponentLoader::GetInstance().UnInit(); g_compHandlerMap.clear(); + ComponentLoader::GetInstance().compHandlerMap_.clear(); } /** @@ -74,11 +80,42 @@ HWTEST_F(ComponentLoaderTest, component_loader_test_002, TestSize.Level0) /** * @tc.name: component_loader_test_003 - * @tc.desc: Verify the GetSource function. + * @tc.desc: Verify the GetHardwareHandler function. * @tc.type: FUNC * @tc.require: AR000GHSK3 */ HWTEST_F(ComponentLoaderTest, component_loader_test_003, TestSize.Level0) +{ + ComponentLoader::GetInstance().compHandlerMap_.clear(); + DHType dhType = DHType::AUDIO; + IHardwareHandler *hardwareHandlerPtr = nullptr; + auto ret = ComponentLoader::GetInstance().GetHardwareHandler(dhType, hardwareHandlerPtr); + EXPECT_EQ(ERR_DH_FWK_LOADER_HANDLER_IS_NULL, ret); +} + +/** + * @tc.name: component_loader_test_004 + * @tc.desc: Verify the GetHardwareHandler function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_004, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + CompHandler compHandler; + IHardwareHandler *hardwareHandlerPtr = nullptr; + ComponentLoader::GetInstance().compHandlerMap_[DHType::CAMERA] = compHandler; + auto ret = ComponentLoader::GetInstance().GetHardwareHandler(dhType, hardwareHandlerPtr); + EXPECT_EQ(ERR_DH_FWK_LOADER_HANDLER_IS_NULL, ret); +} + +/** + * @tc.name: component_loader_test_005 + * @tc.desc: Verify the GetSource function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_005, TestSize.Level0) { for (const auto &iter : g_compHandlerMap) { IDistributedHardwareSource *sourcePtr = nullptr; @@ -89,12 +126,43 @@ HWTEST_F(ComponentLoaderTest, component_loader_test_003, TestSize.Level0) } /** - * @tc.name: component_loader_test_004 + * @tc.name: component_loader_test_006 + * @tc.desc: Verify the GetSource function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_006, TestSize.Level0) +{ + ComponentLoader::GetInstance().compHandlerMap_.clear(); + DHType dhType = DHType::AUDIO; + IDistributedHardwareSource *sourcePtr = nullptr; + auto ret = ComponentLoader::GetInstance().GetSource(dhType, sourcePtr); + EXPECT_EQ(ERR_DH_FWK_LOADER_HANDLER_IS_NULL, ret); +} + +/** + * @tc.name: component_loader_test_007 + * @tc.desc: Verify the GetSource function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_007, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + CompHandler compHandler; + IDistributedHardwareSource *sourcePtr = nullptr; + ComponentLoader::GetInstance().compHandlerMap_[DHType::CAMERA] = compHandler; + auto ret = ComponentLoader::GetInstance().GetSource(dhType, sourcePtr); + EXPECT_EQ(ERR_DH_FWK_LOADER_HANDLER_IS_NULL, ret); +} + +/** + * @tc.name: component_loader_test_008 * @tc.desc: Verify the GetSink function. * @tc.type: FUNC * @tc.require: AR000GHSK3 */ -HWTEST_F(ComponentLoaderTest, component_loader_test_004, TestSize.Level0) +HWTEST_F(ComponentLoaderTest, component_loader_test_008, TestSize.Level0) { for (const auto &iter : g_compHandlerMap) { IDistributedHardwareSink *sinkPtr = nullptr; @@ -105,12 +173,43 @@ HWTEST_F(ComponentLoaderTest, component_loader_test_004, TestSize.Level0) } /** - * @tc.name: component_loader_test_005 + * @tc.name: component_loader_test_009 + * @tc.desc: Verify the GetSink function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_009, TestSize.Level0) +{ + ComponentLoader::GetInstance().compHandlerMap_.clear(); + DHType dhType = DHType::AUDIO; + IDistributedHardwareSink *sinkPtr = nullptr; + auto ret = ComponentLoader::GetInstance().GetSink(dhType, sinkPtr); + EXPECT_EQ(ERR_DH_FWK_LOADER_HANDLER_IS_NULL, ret); +} + +/** + * @tc.name: component_loader_test_010 + * @tc.desc: Verify the GetSink function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_010, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + CompHandler compHandler; + IDistributedHardwareSink *sinkPtr = nullptr; + ComponentLoader::GetInstance().compHandlerMap_[DHType::CAMERA] = compHandler; + auto ret = ComponentLoader::GetInstance().GetSink(dhType, sinkPtr); + EXPECT_EQ(ERR_DH_FWK_LOADER_HANDLER_IS_NULL, ret); +} + +/** + * @tc.name: component_loader_test_011 * @tc.desc: Verify the ReleaseHardwareHandler function. * @tc.type: FUNC * @tc.require: AR000GHSK3 */ -HWTEST_F(ComponentLoaderTest, component_loader_test_005, TestSize.Level0) +HWTEST_F(ComponentLoaderTest, component_loader_test_011, TestSize.Level0) { for (const auto &iter : g_compHandlerMap) { auto ret = ComponentLoader::GetInstance().ReleaseHardwareHandler(iter.first); @@ -120,12 +219,12 @@ HWTEST_F(ComponentLoaderTest, component_loader_test_005, TestSize.Level0) } /** - * @tc.name: component_loader_test_006 + * @tc.name: component_loader_test_012 * @tc.desc: Verify the ReleaseSource function. * @tc.type: FUNC * @tc.require: AR000GHSK3 */ -HWTEST_F(ComponentLoaderTest, component_loader_test_006, TestSize.Level0) +HWTEST_F(ComponentLoaderTest, component_loader_test_012, TestSize.Level0) { for (const auto &iter : g_compHandlerMap) { auto ret = ComponentLoader::GetInstance().ReleaseSource(iter.first); @@ -135,12 +234,12 @@ HWTEST_F(ComponentLoaderTest, component_loader_test_006, TestSize.Level0) } /** - * @tc.name: component_loader_test_007 + * @tc.name: component_loader_test_013 * @tc.desc: Verify the ReleaseSink function. * @tc.type: FUNC * @tc.require: AR000GHSK3 */ -HWTEST_F(ComponentLoaderTest, component_loader_test_007, TestSize.Level0) +HWTEST_F(ComponentLoaderTest, component_loader_test_013, TestSize.Level0) { for (const auto &iter : g_compHandlerMap) { auto ret = ComponentLoader::GetInstance().ReleaseSink(iter.first); @@ -150,15 +249,435 @@ HWTEST_F(ComponentLoaderTest, component_loader_test_007, TestSize.Level0) } /** - * @tc.name: component_loader_test_008 + * @tc.name: component_loader_test_014 * @tc.desc: Verify the GetAllCompTypes function. * @tc.type: FUNC * @tc.require: AR000GHSK3 */ -HWTEST_F(ComponentLoaderTest, component_loader_test_008, TestSize.Level0) +HWTEST_F(ComponentLoaderTest, component_loader_test_014, TestSize.Level0) { auto vec = ComponentLoader::GetInstance().GetAllCompTypes(); EXPECT_EQ(vec.size(), ComponentLoader::GetInstance().compHandlerMap_.size()); } + +/** + * @tc.name: component_loader_test_015 + * @tc.desc: Verify the GetHandler function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_015, TestSize.Level0) +{ + std::string soNameEmpty = ""; + auto handler = ComponentLoader::GetInstance().GetHandler(soNameEmpty); + EXPECT_EQ(nullptr, handler); +} + +/** + * @tc.name: component_loader_test_016 + * @tc.desc: Verify the GetHandler function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_016, TestSize.Level0) +{ + std::string soName = "NON_EXISTENT_SO"; + auto handler = ComponentLoader::GetInstance().GetHandler(soName); + EXPECT_EQ(nullptr, handler); +} + +/** + * @tc.name: component_loader_test_017 + * @tc.desc: Verify the GetCompPathAndVersion function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_017, TestSize.Level0) +{ + std::string jsonStr = ""; + std::map dhtypeMap; + int32_t ret = ComponentLoader::GetInstance().GetCompPathAndVersion(jsonStr, dhtypeMap); + EXPECT_EQ(ERR_DH_FWK_JSON_PARSE_FAILED, ret); +} + +/** + * @tc.name: component_loader_test_018 + * @tc.desc: Verify the GetCompPathAndVersion function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_018, TestSize.Level0) +{ + std::string NAME = "NAME"; + std::string TYPE = "TYPE"; + std::string PATH = "PATH"; + nlohmann::json json0bject; + nlohmann::json compVers; + compVers[NAME] = "name"; + compVers[TYPE] = 1111; + json0bject[PATH] = compVers; + std::string jsonStr = json0bject.dump(); + std::map dhtypeMap; + int32_t ret = ComponentLoader::GetInstance().GetCompPathAndVersion(jsonStr, dhtypeMap); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + +/** + * @tc.name: component_loader_test_019 + * @tc.desc: Verify the StoreLocalDHVersionInDB function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_019, TestSize.Level0) +{ + ComponentLoader::GetInstance().isLocalVersionInit_.store(false); + ComponentLoader::GetInstance().StoreLocalDHVersionInDB(); + EXPECT_EQ(false, ComponentLoader::GetInstance().isLocalVersionInit_.load()); +} + +/** + * @tc.name: component_loader_test_020 + * @tc.desc: Verify the IsDHTypeExist function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_020, TestSize.Level0) +{ + bool ret = ComponentLoader::GetInstance().IsDHTypeExist(DHType::CAMERA); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: component_loader_test_021 + * @tc.desc: Verify the GetSourceSaId function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_021, TestSize.Level0) +{ + const int32_t INVALID_SA_ID = -1; + int32_t ret = ComponentLoader::GetInstance().GetSourceSaId(DHType::UNKNOWN); + EXPECT_EQ(INVALID_SA_ID, ret); +} + +/** + * @tc.name: component_loader_test_022 + * @tc.desc: Verify the ParseConfig function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_022, TestSize.Level0) +{ + int32_t ret = ComponentLoader::GetInstance().ParseConfig(); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: component_loader_test_023 + * @tc.desc: Verify the ReleaseHandler function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_023, TestSize.Level0) +{ + void *handler = nullptr; + int32_t ret = ComponentLoader::GetInstance().ReleaseHandler(handler); + EXPECT_EQ(ERR_DH_FWK_LOADER_HANDLER_IS_NULL, ret); +} + +/** + * @tc.name: component_loader_test_024 + * @tc.desc: Verify the ReleaseHardwareHandler function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_024, TestSize.Level0) +{ + DHType dhType = DHType::GPS; + int32_t ret = ComponentLoader::GetInstance().ReleaseHardwareHandler(dhType); + EXPECT_EQ(ERR_DH_FWK_TYPE_NOT_EXIST, ret); +} + +/** + * @tc.name: component_loader_test_025 + * @tc.desc: Verify the ReleaseSource function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_025, TestSize.Level0) +{ + DHType dhType = DHType::GPS; + int32_t ret = ComponentLoader::GetInstance().ReleaseSource(dhType); + EXPECT_EQ(ERR_DH_FWK_TYPE_NOT_EXIST, ret); +} + +/** + * @tc.name: component_loader_test_026 + * @tc.desc: Verify the ReleaseSink function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_026, TestSize.Level0) +{ + DHType dhType = DHType::GPS; + int32_t ret = ComponentLoader::GetInstance().ReleaseSink(dhType); + EXPECT_EQ(ERR_DH_FWK_TYPE_NOT_EXIST, ret); +} + +/** + * @tc.name: component_loader_test_027 + * @tc.desc: Verify the ReleaseSink function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_027, TestSize.Level0) +{ + DHType dhType = DHType::GPS; + bool ret = ComponentLoader::GetInstance().IsDHTypeExist(dhType); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: component_loader_test_028 + * @tc.desc: Verify the GetDHTypeBySrcSaId function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_028, TestSize.Level0) +{ + int32_t saId = 4801; + DHType dhType = ComponentLoader::GetInstance().GetDHTypeBySrcSaId(saId); + EXPECT_EQ(dhType, DHType::UNKNOWN); +} + +/** + * @tc.name: component_loader_test_029 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_029, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = 4801; + + from_json(json, cfg); + EXPECT_EQ(true, cfg.name.empty()); +} + +/** + * @tc.name: component_loader_test_030 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_030, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = 0x02; + + from_json(json, cfg); + EXPECT_NE(DHType::AUDIO, cfg.type); +} + +/** + * @tc.name: component_loader_test_031 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_031, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = 4801; + + from_json(json, cfg); + EXPECT_EQ(true, cfg.compHandlerLoc.empty()); +} + +/** + * @tc.name: component_loader_test_032 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_032, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = "comp_handler_loc"; + json[COMP_HANDLER_VERSION] = 4801; + + from_json(json, cfg); + EXPECT_EQ(true, cfg.compHandlerVersion.empty()); +} + +/** + * @tc.name: component_loader_test_033 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_033, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = "comp_handler_loc"; + json[COMP_HANDLER_VERSION] = "comp_handler_version"; + json[COMP_SOURCE_LOC] = 4801; + + from_json(json, cfg); + EXPECT_EQ(true, cfg.compSourceLoc.empty()); +} + +/** + * @tc.name: component_loader_test_034 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_034, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = "comp_handler_loc"; + json[COMP_HANDLER_VERSION] = "comp_handler_version"; + json[COMP_SOURCE_LOC] = "comp_source_loc"; + json[COMP_SOURCE_VERSION] = 4801; + + from_json(json, cfg); + EXPECT_EQ(true, cfg.compSourceVersion.empty()); +} + +/** + * @tc.name: component_loader_test_035 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_035, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = "comp_handler_loc"; + json[COMP_HANDLER_VERSION] = "comp_handler_version"; + json[COMP_SOURCE_LOC] = "comp_source_loc"; + json[COMP_SOURCE_VERSION] = "comp_source_version"; + json[COMP_SOURCE_SA_ID] = "comp_source_sa_id"; + + from_json(json, cfg); + EXPECT_NE(4801, cfg.compSourceSaId); +} + +/** + * @tc.name: component_loader_test_036 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_036, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = "comp_handler_loc"; + json[COMP_HANDLER_VERSION] = "comp_handler_version"; + json[COMP_SOURCE_LOC] = "comp_source_loc"; + json[COMP_SOURCE_VERSION] = "comp_source_version"; + json[COMP_SOURCE_SA_ID] = 4801; + json[COMP_SINK_LOC] = 4802; + + from_json(json, cfg); + EXPECT_EQ(true, cfg.compSinkLoc.empty()); +} + +/** + * @tc.name: component_loader_test_037 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_037, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = "comp_handler_loc"; + json[COMP_HANDLER_VERSION] = "comp_handler_version"; + json[COMP_SOURCE_LOC] = "comp_source_loc"; + json[COMP_SOURCE_VERSION] = "comp_source_version"; + json[COMP_SOURCE_SA_ID] = 4801; + json[COMP_SINK_LOC] = "comp_sink_loc"; + json[COMP_SINK_VERSION] = 4802; + + from_json(json, cfg); + EXPECT_EQ(true, cfg.compSinkVersion.empty()); +} + +/** + * @tc.name: component_loader_test_038 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_038, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = "comp_handler_loc"; + json[COMP_HANDLER_VERSION] = "comp_handler_version"; + json[COMP_SOURCE_LOC] = "comp_source_loc"; + json[COMP_SOURCE_VERSION] = "comp_source_version"; + json[COMP_SOURCE_SA_ID] = 4801; + json[COMP_SINK_LOC] = "comp_sink_loc"; + json[COMP_SINK_VERSION] = "comp_sink_version"; + json[COMP_SINK_SA_ID] = "4802"; + + from_json(json, cfg); + EXPECT_NE(4802, cfg.compSinkSaId); +} + +/** + * @tc.name: component_loader_test_039 + * @tc.desc: Verify the from_json function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(ComponentLoaderTest, component_loader_test_039, TestSize.Level0) +{ + CompConfig cfg; + nlohmann::json json; + json[COMP_NAME] = "name"; + json[COMP_TYPE] = "DHType::AUDIO"; + json[COMP_HANDLER_LOC] = "comp_handler_loc"; + json[COMP_HANDLER_VERSION] = "comp_handler_version"; + json[COMP_SOURCE_LOC] = "comp_source_loc"; + json[COMP_SOURCE_VERSION] = "comp_source_version"; + json[COMP_SOURCE_SA_ID] = 4801; + json[COMP_SINK_LOC] = "comp_sink_loc"; + json[COMP_SINK_VERSION] = "comp_sink_version"; + json[COMP_SINK_SA_ID] = 4802; + + from_json(json, cfg); + EXPECT_EQ(4802, cfg.compSinkSaId); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/BUILD.gn similarity index 78% rename from services/distributedhardwarefwkservice/test/unittest/common/componentmanager/BUILD.gn rename to services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/BUILD.gn index ac41e4393966126cbeb8feeea26f980b24e27fcd..ea095956f1be7dfe231dc3c273a6e411e26a85c9 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,23 +20,23 @@ module_out_path = "distributed_hardware_fwk/component_manager_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//base/notification/eventhandler/interfaces/inner_api", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", + "${av_trans_path}/common/include", "include", + "${innerkits_path}/include", "${utils_path}/include", "${utils_path}/include/log", "${utils_path}/include/eventbus", "${services_path}/distributedhardwarefwkservice/include", "${services_path}/distributedhardwarefwkservice/include/componentloader", "${services_path}/distributedhardwarefwkservice/include/componentmanager", + "${services_path}/distributedhardwarefwkservice/include/lowlatency", "${services_path}/distributedhardwarefwkservice/include/resourcemanager", "${services_path}/distributedhardwarefwkservice/include/versionmanager", "${services_path}/distributedhardwarefwkservice/include/utils", + "${services_path}/distributedhardwarefwkservice/include/task", "${common_path}/utils/include", "${common_path}/log/include", "//third_party/json/include", - "//commonlibrary/c_utils/base/include", ] } @@ -48,12 +48,19 @@ ohos_unittest("ComponentManagerTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", - "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "ipc:ipc_single", + "kv_store:distributeddata_inner", + ] + defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"ComponentManagerTest\"", diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/include/component_manager_test.h b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/include/component_manager_test.h similarity index 100% rename from services/distributedhardwarefwkservice/test/unittest/common/componentmanager/include/component_manager_test.h rename to services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/include/component_manager_test.h diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/include/mock_idistributed_hardware_sink.h b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/include/mock_idistributed_hardware_sink.h similarity index 100% rename from services/distributedhardwarefwkservice/test/unittest/common/componentmanager/include/mock_idistributed_hardware_sink.h rename to services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/include/mock_idistributed_hardware_sink.h diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/include/mock_idistributed_hardware_source.h b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/include/mock_idistributed_hardware_source.h similarity index 100% rename from services/distributedhardwarefwkservice/test/unittest/common/componentmanager/include/mock_idistributed_hardware_source.h rename to services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/include/mock_idistributed_hardware_source.h diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/src/component_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/src/component_manager_test.cpp similarity index 58% rename from services/distributedhardwarefwkservice/test/unittest/common/componentmanager/src/component_manager_test.cpp rename to services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/src/component_manager_test.cpp index a09736fa7048bfe2009a2d9814c98ff9b5d12ae5..f22b244cd9f75fdfb72755e7f6e8af2a7025561b 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/src/component_manager_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/src/component_manager_test.cpp @@ -89,7 +89,11 @@ void ComponentManagerTest::SetUp() ComponentManager::GetInstance().compSink_.clear(); } -void ComponentManagerTest::TearDown() {} +void ComponentManagerTest::TearDown() +{ + ComponentManager::GetInstance().compSource_.clear(); + ComponentManager::GetInstance().compSink_.clear(); +} int32_t ComponentManagerTest::Enable(int32_t timeout, int32_t status) { @@ -309,6 +313,22 @@ HWTEST_F(ComponentManagerTest, enable_test_004, TestSize.Level0) thread6.join(); } +/** + * @tc.name: enable_test_005 + * @tc.desc: Verify the Enable for Multi-thread + * @tc.type: FUNC + * @tc.require: AR000GHSK7 + */ +HWTEST_F(ComponentManagerTest, Enable_test_005, TestSize.Level0) +{ + std::string networkId = ""; + std::string uuid = ""; + std::string dhId = ""; + ComponentManager::GetInstance().compSource_.clear(); + auto ret = ComponentManager::GetInstance().Enable(networkId, uuid, dhId, DHType::CAMERA); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + /** * @tc.name: disable_test_001 * @tc.desc: Verify the Disable success @@ -376,6 +396,22 @@ HWTEST_F(ComponentManagerTest, disable_test_004, TestSize.Level0) thread6.join(); } +/** + * @tc.name: disable_test_005 + * @tc.desc: Verify the Disable for Multi-thread + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(ComponentManagerTest, Disable_test_005, TestSize.Level0) +{ + std::string networkId = ""; + std::string uuid = ""; + std::string dhId = ""; + ComponentManager::GetInstance().compSource_.clear(); + auto ret = ComponentManager::GetInstance().Disable(networkId, uuid, dhId, DHType::CAMERA); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + /** * @tc.name: init_compSource_test_001 * @tc.desc: Verify the InitCompSource @@ -436,7 +472,7 @@ HWTEST_F(ComponentManagerTest, get_enableparam_test_001, TestSize.Level0) EnableParam param; auto ret = ComponentManager::GetInstance().GetEnableParam(NETWORK_TEST, UUID_TEST, DH_ID_1, DHType::CAMERA, param); - EXPECT_EQ(ret, DH_FWK_SUCCESS); + EXPECT_EQ(DH_FWK_SUCCESS, ret); } /** @@ -462,7 +498,373 @@ HWTEST_F(ComponentManagerTest, get_sinkversion_fromvermgr_test_001, TestSize.Lev VersionManager::GetInstance().AddDHVersion(UUID_TEST, dhVersion); std::string sinkVersion; auto ret = ComponentManager::GetInstance().GetSinkVersionFromVerMgr(UUID_TEST, DHType::CAMERA, sinkVersion); - EXPECT_EQ(ret, DH_FWK_SUCCESS); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: GetDHType_test_001 + * @tc.desc: Verify the GetDHType + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(ComponentManagerTest, GetDHType_test_001, TestSize.Level0) +{ + std::string uuid = "distribueted_111222333"; + std::string dhId = "camera_1234567489"; + auto ret = ComponentManager::GetInstance().GetDHType(uuid, dhId); + EXPECT_EQ(DHType::UNKNOWN, ret); +} + +/** + * @tc.name: UnInit_001 + * @tc.desc: Verify the UnInit function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, UnInit_001, TestSize.Level0) +{ + ComponentManager::GetInstance().compMonitorPtr_ = nullptr; + int32_t ret = ComponentManager::GetInstance().UnInit(); + EXPECT_EQ(ERR_DH_FWK_COMPONENT_MONITOR_NULL, ret); +} + +/** + * @tc.name: StartSource_001 + * @tc.desc: Verify the StartSource function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, StartSource_001, TestSize.Level0) +{ + auto ret = ComponentManager::GetInstance().StartSource(); + EXPECT_EQ(true, ret.empty()); +} + +/** + * @tc.name: StartSource_002 + * @tc.desc: Verify the StartSource function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, StartSource_002, TestSize.Level0) +{ + DHType dhType = DHType::AUDIO; + auto ret = ComponentManager::GetInstance().StartSource(dhType); + EXPECT_EQ(true, ret.empty()); +} + +/** + * @tc.name: StartSink_001 + * @tc.desc: Verify the StartSink function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, StartSink_001, TestSize.Level0) +{ + auto ret = ComponentManager::GetInstance().StartSink(); + EXPECT_EQ(true, ret.empty()); +} + +/** + * @tc.name: StartSink_002 + * @tc.desc: Verify the StartSink function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, StartSink_002, TestSize.Level0) +{ + DHType dhType = DHType::AUDIO; + auto ret = ComponentManager::GetInstance().StartSink(dhType); + EXPECT_EQ(true, ret.empty()); +} + +/** + * @tc.name: StopSource_001 + * @tc.desc: Verify the StopSource function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, StopSource_001, TestSize.Level0) +{ + auto ret = ComponentManager::GetInstance().StopSource(); + EXPECT_EQ(true, ret.empty()); +} + +/** + * @tc.name: StopSink_001 + * @tc.desc: Verify the StopSink function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, StopSink_001, TestSize.Level0) +{ + auto ret = ComponentManager::GetInstance().StopSink(); + EXPECT_EQ(true, ret.empty()); +} + +/** + * @tc.name: WaitForResult_001 + * @tc.desc: Verify the WaitForResult function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, WaitForResult_001, TestSize.Level0) +{ + ComponentManager::Action action = ComponentManager::Action::START_SINK; + ActionResult actionsResult; + bool ret = ComponentManager::GetInstance().WaitForResult(action, actionsResult); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: InitCompSource_001 + * @tc.desc: Verify the InitCompSource function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, InitCompSource_001, TestSize.Level0) +{ + bool ret = ComponentManager::GetInstance().InitCompSource(); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: InitCompSink_001 + * @tc.desc: Verify the InitCompSink function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, InitCompSink_001, TestSize.Level0) +{ + bool ret = ComponentManager::GetInstance().InitCompSink(); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: Enable_001 + * @tc.desc: Verify the Enable function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, Enable_001, TestSize.Level0) +{ + ComponentManager::GetInstance().compSource_.clear(); + std::string networkId; + std::string uuid; + std::string dhId; + DHType dhType = DHType::CAMERA; + int32_t ret = ComponentManager::GetInstance().Enable(networkId, uuid, dhId, dhType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + +/** + * @tc.name: Enable_002 + * @tc.desc: Verify the Enable function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, Enable_002, TestSize.Level0) +{ + std::string networkId; + std::string uuid; + std::string dhId; + DHType dhType = DHType::CAMERA; + IDistributedHardwareSource *sourcePtr = nullptr; + ComponentManager::GetInstance().compSource_.insert(std::make_pair(dhType, sourcePtr)); + int32_t ret = ComponentManager::GetInstance().Enable(networkId, uuid, dhId, dhType); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_CAPABILITY_MAP_NOT_FOUND, ret); +} + +/** + * @tc.name: Disable_001 + * @tc.desc: Verify the Disable function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, Disable_001, TestSize.Level0) +{ + ComponentManager::GetInstance().compSource_.clear(); + std::string networkId; + std::string uuid; + std::string dhId; + DHType dhType = DHType::INPUT; + int32_t ret = ComponentManager::GetInstance().Disable(networkId, uuid, dhId, dhType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + +/** + * @tc.name: Disable_002 + * @tc.desc: Verify the Disable function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, Disable_002, TestSize.Level0) +{ + std::string networkId; + std::string uuid; + std::string dhId; + DHType dhType = DHType::INPUT; + IDistributedHardwareSource *sourcePtr = nullptr; + ComponentManager::GetInstance().compSource_.insert(std::make_pair(dhType, sourcePtr)); + int32_t ret = ComponentManager::GetInstance().Disable(networkId, uuid, dhId, dhType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + +/** + * @tc.name: GetDHType_001 + * @tc.desc: Verify the GetDHType function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, GetDHType_001, TestSize.Level0) +{ + std::string uuid; + std::string dhId; + auto ret = ComponentManager::GetInstance().GetDHType(uuid, dhId); + EXPECT_EQ(DHType::UNKNOWN, ret); +} + +/** + * @tc.name: GetEnableParam_001 + * @tc.desc: Verify the GetEnableParam function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, GetEnableParam_001, TestSize.Level0) +{ + std::string networkId; + std::string uuid; + std::string dhId; + DHType dhType = DHType::CAMERA; + EnableParam param; + int32_t ret = ComponentManager::GetInstance().GetEnableParam(networkId, uuid, dhId, dhType, param); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: GetSinkVersionFromVerMgr_001 + * @tc.desc: Verify the GetSinkVersionFromVerMgr function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, GetSinkVersionFromVerMgr_001, TestSize.Level0) +{ + std::string uuid; + DHType dhType = DHType::CAMERA; + std::string sinkVersion; + int32_t ret = ComponentManager::GetInstance().GetSinkVersionFromVerMgr(uuid, dhType, sinkVersion); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: GetSinkVersionFromVerInfoMgr_001 + * @tc.desc: Verify the GetSinkVersionFromVerInfoMgr function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, GetSinkVersionFromVerInfoMgr_001, TestSize.Level0) +{ + std::string uuid; + DHType dhType = DHType::CAMERA; + std::string sinkVersion; + int32_t ret = ComponentManager::GetInstance().GetSinkVersionFromVerInfoMgr(uuid, dhType, sinkVersion); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: GetSinkVersion_001 + * @tc.desc: Verify the GetSinkVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, GetSinkVersion_001, TestSize.Level0) +{ + std::string networkId; + std::string uuid; + DHType dhType = DHType::CAMERA; + std::string sinkVersion; + int32_t ret = ComponentManager::GetInstance().GetSinkVersion(networkId, uuid, dhType, sinkVersion); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: UpdateVersionCache_001 + * @tc.desc: Verify the UpdateVersionCache function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, UpdateVersionCache_001, TestSize.Level0) +{ + std::string uuid; + VersionInfo versionInfo; + ComponentManager::GetInstance().UpdateVersionCache(uuid, versionInfo); + EXPECT_EQ(true, ComponentManager::GetInstance().compSource_.empty()); +} + +/** + * @tc.name: DumpLoadedComps_001 + * @tc.desc: Verify the DumpLoadedComps function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, DumpLoadedComps_001, TestSize.Level0) +{ + std::set compSourceType; + std::set compSinkType; + ComponentManager::GetInstance().DumpLoadedComps(compSourceType, compSinkType); + EXPECT_EQ(true, ComponentManager::GetInstance().compSource_.empty()); +} + +/** + * @tc.name: Recover_001 + * @tc.desc: Verify the Recover function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, Recover_001, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + ComponentManager::GetInstance().Recover(dhType); + EXPECT_EQ(true, ComponentManager::GetInstance().compSource_.empty()); +} + +/** + * @tc.name: DoRecover_001 + * @tc.desc: Verify the DoRecover function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, DoRecover_001, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + ComponentManager::GetInstance().DoRecover(dhType); + EXPECT_EQ(true, ComponentManager::GetInstance().compSource_.empty()); +} + +/** + * @tc.name: ReStartSA_001 + * @tc.desc: Verify the ReStartSA function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, ReStartSA_001, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + ComponentManager::GetInstance().ReStartSA(dhType); + EXPECT_EQ(true, ComponentManager::GetInstance().compSource_.empty()); +} + +/** + * @tc.name: RecoverDistributedHardware_001 + * @tc.desc: Verify the RecoverDistributedHardware function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentManagerTest, RecoverDistributedHardware_001, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + ComponentManager::GetInstance().RecoverDistributedHardware(dhType); + EXPECT_EQ(true, ComponentManager::GetInstance().compSource_.empty()); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b887fafeaa2333963367baec614d83b138bc2ac8 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/component_monitor_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//third_party/json/include", + "include", + "${utils_path}/include", + "${utils_path}/include/log", + "${utils_path}/include/eventbus", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/componentloader", + "${services_path}/distributedhardwarefwkservice/include/componentmanager", + "${services_path}/distributedhardwarefwkservice/include/lowlatency", + "${services_path}/distributedhardwarefwkservice/include/resourcemanager", + "${services_path}/distributedhardwarefwkservice/include/versionmanager", + "${services_path}/distributedhardwarefwkservice/include/utils", + "${common_path}/utils/include", + "${common_path}/log/include", + ] +} + +ohos_unittest("ComponentMonitorTest") { + module_out_path = module_out_path + + sources = [ "src/component_monitor_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "ipc:ipc_core", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"ComponentMonitorTest\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("component_monitor_test") { + testonly = true + deps = [ ":ComponentMonitorTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/include/component_monitor_test.h b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/include/component_monitor_test.h new file mode 100644 index 0000000000000000000000000000000000000000..66cbeec0cd4158fe9225723629d13f52a0ad9f15 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/include/component_monitor_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_COMPONENT_MONITOR_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_COMPONENT_MONITOR_TEST_H + +#include "gtest/gtest.h" + +#define private public +#include "component_monitor.h" +#undef private + +namespace OHOS { +namespace DistributedHardware { +class ComponentMonitorTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr compMonitorPtr_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/src/component_monitor_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/src/component_monitor_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd9574295c0a72ca026774debad5316900f3606d --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_monitior/src/component_monitor_test.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "component_monitor_test.h" + +#include +#include +#include +#include +#include + +#include "component_loader.h" +#include "iservice_registry.h" +#include "system_ability_status_change_stub.h" +#include "single_instance.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void ComponentMonitorTest::SetUpTestCase(void) {} + +void ComponentMonitorTest::TearDownTestCase(void) {} + +void ComponentMonitorTest::SetUp() +{ + compMonitorPtr_ = std::make_shared(); +} + +void ComponentMonitorTest::TearDown() +{ + compMonitorPtr_->saListeners_.clear(); + compMonitorPtr_ = nullptr; +} + +/** + * @tc.name: AddSAMonitor_001 + * @tc.desc: Verify the AddSAMonitor function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentMonitorTest, AddSAMonitor_001, TestSize.Level0) +{ + int32_t saId = static_cast(DHType::AUDIO); + compMonitorPtr_->AddSAMonitor(saId); + EXPECT_EQ(false, compMonitorPtr_->saListeners_.empty()); +} + +/** + * @tc.name: AddSAMonitor_002 + * @tc.desc: Verify the AddSAMonitor function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentMonitorTest, AddSAMonitor_002, TestSize.Level0) +{ + int32_t saId = static_cast(DHType::CAMERA); + sptr listener = new ComponentMonitor::CompSystemAbilityListener(); + compMonitorPtr_->saListeners_.insert(std::make_pair(saId, listener)); + compMonitorPtr_->AddSAMonitor(saId); + EXPECT_EQ(false, compMonitorPtr_->saListeners_.empty()); +} + +/** + * @tc.name: RemoveSAMonitor_001 + * @tc.desc: Verify the RemoveSAMonitor function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentMonitorTest, RemoveSAMonitor_001, TestSize.Level0) +{ + int32_t saId = static_cast(DHType::GPS); + compMonitorPtr_->RemoveSAMonitor(saId); + EXPECT_EQ(true, compMonitorPtr_->saListeners_.empty()); +} + +/** + * @tc.name: RemoveSAMonitor_002 + * @tc.desc: Verify the RemoveSAMonitor function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentMonitorTest, RemoveSAMonitor_002, TestSize.Level0) +{ + int32_t saId = static_cast(DHType::CAMERA); + sptr listener = new ComponentMonitor::CompSystemAbilityListener(); + compMonitorPtr_->saListeners_.insert(std::make_pair(saId, listener)); + compMonitorPtr_->RemoveSAMonitor(saId); + EXPECT_EQ(true, compMonitorPtr_->saListeners_.empty()); +} + +/** + * @tc.name: OnRemoveSystemAbility_001 + * @tc.desc: Verify the OnRemoveSystemAbility function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentMonitorTest, OnRemoveSystemAbility_001, TestSize.Level0) +{ + sptr listener = new ComponentMonitor::CompSystemAbilityListener(); + int32_t saId = static_cast(DHType::UNKNOWN); + std::string deviceId; + compMonitorPtr_->AddSAMonitor(saId); + listener->OnRemoveSystemAbility(saId, deviceId); + EXPECT_EQ(DHType::UNKNOWN, ComponentLoader::GetInstance().GetDHTypeBySrcSaId(saId)); +} + +/** + * @tc.name: OnRemoveSystemAbility_002 + * @tc.desc: Verify the OnRemoveSystemAbility function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ComponentMonitorTest, OnRemoveSystemAbility_002, TestSize.Level0) +{ + sptr listener = new ComponentMonitor::CompSystemAbilityListener(); + int32_t saId = static_cast(DHType::CAMERA); + std::string deviceId; + compMonitorPtr_->AddSAMonitor(saId); + listener->OnRemoveSystemAbility(saId, deviceId); + EXPECT_EQ(DHType::UNKNOWN, ComponentLoader::GetInstance().GetDHTypeBySrcSaId(saId)); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/BUILD.gn index 8418a17d321fe14c85a5874bbb08cd0a549ba3a4..25d0f8a9cae4bec383f816b1b235d68c4d328469 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,8 +20,6 @@ module_out_path = "distributed_hardware_fwk/db_adapter_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//base/notification/eventhandler/interfaces/inner_api", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", "include", "${utils_path}/include", "${utils_path}/include/log", @@ -31,10 +29,7 @@ config("module_private_config") { "${services_path}/distributedhardwarefwkservice/include/utils", "${common_path}/utils/include", "${common_path}/log/include", - "//commonlibrary/c_utils/base/include", "//third_party/json/include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", ] } @@ -50,12 +45,17 @@ ohos_unittest("DbAdapterTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", - "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", "//third_party/googletest:gtest_main", ] - external_deps = [ "c_utils:utils" ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] } group("db_adapter_test") { diff --git a/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/src/db_adapter_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/src/db_adapter_test.cpp index 17387888d32bd87cd7012827e3d0aa0c16e99a95..ad453238403fe57238f09655c2565735b81665c7 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/src/db_adapter_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/src/db_adapter_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -40,6 +40,7 @@ namespace DistributedHardware { namespace { const string DATABASE_DIR = "/data/service/el1/public/database/dtbhardware_manager_service/"; +const std::string DEV_NETWORK_ID_1 = "nt36a637105409e904d4da83790a4a9"; const string TEST_DEV_ID_0 = "bb536a637105409e904d4da83791aa11"; const string TEST_DEV_ID_1 = "bb536a637105409e904d4da83791bb22"; const string TEST_DEV_ID_2 = "bb536a637105409e904d4da83791bb33"; @@ -112,6 +113,7 @@ void DbAdapterTest::SetUp() void DbAdapterTest::TearDown() { + g_dbAdapterPtr->manualSyncCountMap_.clear(); } /** @@ -122,7 +124,7 @@ void DbAdapterTest::TearDown() */ HWTEST_F(DbAdapterTest, db_adapter_test_000, TestSize.Level0) { - EXPECT_EQ(g_dbAdapterPtr->Init(), DH_FWK_SUCCESS); + EXPECT_EQ(DH_FWK_SUCCESS, g_dbAdapterPtr->Init()); } /** @@ -144,7 +146,7 @@ HWTEST_F(DbAdapterTest, db_adapter_test_001, TestSize.Level0) keys.push_back(key); values.push_back(resInfo->ToJsonString()); } - EXPECT_EQ(g_dbAdapterPtr->PutDataBatch(keys, values), DH_FWK_SUCCESS); + EXPECT_EQ(DH_FWK_SUCCESS, g_dbAdapterPtr->PutDataBatch(keys, values)); for (auto &resInfo : resInfos) { g_dbAdapterPtr->RemoveDataByKey(resInfo->GetKey()); } @@ -161,7 +163,7 @@ HWTEST_F(DbAdapterTest, db_adapter_test_002, TestSize.Level0) std::vector keys { std::string(TEST_DEV_ID_2 + TEST_DH_ID_0) }; std::vector values { TEST_DH_ATTR_0 }; - EXPECT_EQ(g_dbAdapterPtr->PutDataBatch(keys, values), DH_FWK_SUCCESS); + EXPECT_EQ(DH_FWK_SUCCESS, g_dbAdapterPtr->PutDataBatch(keys, values)); g_dbAdapterPtr->RemoveDataByKey(keys[0]); } @@ -176,7 +178,7 @@ HWTEST_F(DbAdapterTest, db_adapter_test_003, TestSize.Level0) std::vector keys { std::string(TEST_DEV_ID_2 + TEST_DH_ID_0) }; std::vector valuesEmpty; - EXPECT_EQ(g_dbAdapterPtr->PutDataBatch(keys, valuesEmpty), ERR_DH_FWK_PARA_INVALID); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, g_dbAdapterPtr->PutDataBatch(keys, valuesEmpty)); } /** @@ -190,7 +192,7 @@ HWTEST_F(DbAdapterTest, db_adapter_test_004, TestSize.Level0) std::vector keysEmpty; std::vector values { TEST_DH_ATTR_0 }; - EXPECT_EQ(g_dbAdapterPtr->PutDataBatch(keysEmpty, values), ERR_DH_FWK_PARA_INVALID); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, g_dbAdapterPtr->PutDataBatch(keysEmpty, values)); } /** @@ -204,7 +206,7 @@ HWTEST_F(DbAdapterTest, db_adapter_test_005, TestSize.Level0) std::vector keysEmpty; std::vector valuesEmpty; - EXPECT_EQ(g_dbAdapterPtr->PutDataBatch(keysEmpty, valuesEmpty), ERR_DH_FWK_PARA_INVALID); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, g_dbAdapterPtr->PutDataBatch(keysEmpty, valuesEmpty)); } /** @@ -218,7 +220,7 @@ HWTEST_F(DbAdapterTest, db_adapter_test_006, TestSize.Level0) std::vector keys { std::string(TEST_DEV_ID_2 + TEST_DH_ID_0) }; std::vector values { TEST_DH_ATTR_0, TEST_DH_ATTR_1 }; - EXPECT_EQ(g_dbAdapterPtr->PutDataBatch(keys, values), ERR_DH_FWK_PARA_INVALID); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, g_dbAdapterPtr->PutDataBatch(keys, values)); } /** @@ -233,7 +235,413 @@ HWTEST_F(DbAdapterTest, db_adapter_test_007, TestSize.Level0) std::vector keys { std::string(TEST_DEV_ID_2 + TEST_DH_ID_0) }; std::vector values { TEST_DH_ATTR_0 }; - EXPECT_EQ(g_dbAdapterPtr->PutDataBatch(keys, values), ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->PutDataBatch(keys, values)); } + +/** + * @tc.name: db_adapter_test_008 + * @tc.desc: Verify the ReInit function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, db_adapter_test_008, TestSize.Level0) +{ + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->ReInit()); +} + +/** + * @tc.name: db_adapter_test_009 + * @tc.desc: Verify the RemoveDeviceData function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, db_adapter_test_009, TestSize.Level0) +{ + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->RemoveDeviceData(TEST_DEV_ID_0)); +} + +/** + * @tc.name: db_adapter_test_010 + * @tc.desc: Verify the RemoveDataByKey function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, db_adapter_test_010, TestSize.Level0) +{ + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->RemoveDataByKey("key")); +} + +/** + * @tc.name: db_adapter_test_011 + * @tc.desc: Verify the ManualSync function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, db_adapter_test_011, TestSize.Level0) +{ + std::string networkId = DEV_NETWORK_ID_1; + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->ManualSync(DEV_NETWORK_ID_1)); +} + +/** + * @tc.name: db_adapter_test_012 + * @tc.desc: Verify the UnRegisterChangeListener function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, db_adapter_test_012, TestSize.Level0) +{ + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->UnRegisterChangeListener()); +} + +/** + * @tc.name: db_adapter_test_013 + * @tc.desc: Verify the PutData function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, db_adapter_test_013, TestSize.Level0) +{ + std::string key = std::string(TEST_DEV_ID_1 + TEST_DH_ID_1); + std::string value = TEST_DH_ATTR_0; + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->PutData(key, value)); +} + +/** + * @tc.name: db_adapter_test_014 + * @tc.desc: Verify the RegisterChangeListener function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, db_adapter_test_014, TestSize.Level0) +{ + std::string networkId = DEV_NETWORK_ID_1; + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->RegisterChangeListener()); +} + +/** + * @tc.name: db_adapter_test_015 + * @tc.desc: Verify the UnRegisterChangeListener function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, db_adapter_test_015, TestSize.Level0) +{ + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->UnRegisterChangeListener()); +} + +/** + * @tc.name: SyncCompleted_001 + * @tc.desc: Verify the SyncCompleted function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, SyncCompleted_001, TestSize.Level0) +{ + std::map results; + g_dbAdapterPtr->SyncCompleted(results); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: SyncCompleted_002 + * @tc.desc: Verify the SyncCompleted function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, SyncCompleted_002, TestSize.Level0) +{ + std::map results; + uint32_t MAX_DB_RECORD_SIZE = 10002; + for (uint32_t i = 0; i < MAX_DB_RECORD_SIZE; ++i) { + results.insert(std::pair(to_string(i), DistributedKv::Status::SUCCESS)); + } + g_dbAdapterPtr->SyncCompleted(results); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: SyncCompleted_003 + * @tc.desc: Verify the SyncCompleted function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, SyncCompleted_003, TestSize.Level0) +{ + std::map results; + uint32_t MAX_DB_RECORD_SIZE = 500; + for (uint32_t i = 0; i < MAX_DB_RECORD_SIZE; ++i) { + results.insert(std::pair(to_string(i), DistributedKv::Status::SUCCESS)); + } + g_dbAdapterPtr->SyncCompleted(results); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: CreateManualSyncCount_001 + * @tc.desc: Verify the CreateManualSyncCount function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, CreateManualSyncCount_001, TestSize.Level0) +{ + std::string deviceId = "deviceId"; + g_dbAdapterPtr->CreateManualSyncCount(deviceId); + EXPECT_EQ(false, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: RemoveManualSyncCount_001 + * @tc.desc: Verify the RemoveManualSyncCount function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, RemoveManualSyncCount_001, TestSize.Level0) +{ + std::string deviceId = "deviceId"; + g_dbAdapterPtr->manualSyncCountMap_.insert(std::make_pair(deviceId, 1)); + g_dbAdapterPtr->RemoveManualSyncCount(deviceId); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: SyncDBForRecover_001 + * @tc.desc: Verify the SyncDBForRecover function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, SyncDBForRecover_001, TestSize.Level0) +{ + g_dbAdapterPtr->storeId_.storeId = GLOBAL_CAPABILITY_ID; + g_dbAdapterPtr->SyncDBForRecover(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: SyncDBForRecover_002 + * @tc.desc: Verify the SyncDBForRecover function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, SyncDBForRecover_002, TestSize.Level0) +{ + g_dbAdapterPtr->storeId_.storeId = GLOBAL_VERSION_ID; + g_dbAdapterPtr->SyncDBForRecover(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: RegisterKvStoreDeathListener_001 + * @tc.desc: Verify the RegisterKvStoreDeathListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, RegisterKvStoreDeathListener_001, TestSize.Level0) +{ + g_dbAdapterPtr->RegisterKvStoreDeathListener(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: UnRegisterKvStoreDeathListener_001 + * @tc.desc: Verify the UnRegisterKvStoreDeathListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, UnRegisterKvStoreDeathListener_001, TestSize.Level0) +{ + g_dbAdapterPtr->UnRegisterKvStoreDeathListener(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: RegisterManualSyncListener_001 + * @tc.desc: Verify the RegisterManualSyncListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, RegisterManualSyncListener_001, TestSize.Level0) +{ + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + g_dbAdapterPtr->UnRegisterKvStoreDeathListener(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: RegisterManualSyncListener_002 + * @tc.desc: Verify the RegisterManualSyncListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, RegisterManualSyncListener_002, TestSize.Level0) +{ + g_dbAdapterPtr->UnRegisterKvStoreDeathListener(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: UnRegisterManualSyncListener_001 + * @tc.desc: Verify the UnRegisterManualSyncListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, UnRegisterManualSyncListener_001, TestSize.Level0) +{ + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + g_dbAdapterPtr->UnRegisterManualSyncListener(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: UnRegisterManualSyncListener_002 + * @tc.desc: Verify the UnRegisterManualSyncListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, UnRegisterManualSyncListener_002, TestSize.Level0) +{ + g_dbAdapterPtr->UnRegisterManualSyncListener(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: OnRemoteDied_001 + * @tc.desc: Verify the OnRemoteDied function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, OnRemoteDied_001, TestSize.Level0) +{ + g_dbAdapterPtr->OnRemoteDied(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: DeleteKvStore_001 + * @tc.desc: Verify the DeleteKvStore function + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, DeleteKvStore_001, TestSize.Level0) +{ + g_dbAdapterPtr->DeleteKvStore(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: ReInit_001 + * @tc.desc: Verify the ReInit_001 function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, ReInit_001, TestSize.Level0) +{ + g_dbAdapterPtr->GetKvStorePtr(); + EXPECT_EQ(DH_FWK_SUCCESS, g_dbAdapterPtr->ReInit()); +} + +/** + * @tc.name: RemoveDeviceData_001 + * @tc.desc: Verify the RemoveDeviceData function. + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, RemoveDeviceData_001, TestSize.Level0) +{ + g_dbAdapterPtr->GetKvStorePtr(); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL, g_dbAdapterPtr->RemoveDeviceData(TEST_DEV_ID_0)); +} + +/** + * @tc.name: UnInit_001 + * @tc.desc: Verify the UnInit function. + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DbAdapterTest, UnInit_001, TestSize.Level0) +{ + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + g_dbAdapterPtr->UnInit(); + EXPECT_EQ(true, g_dbAdapterPtr->manualSyncCountMap_.empty()); +} + +/** + * @tc.name: PutData_01 + * @tc.desc: Verify the PutData function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, PutData_01, TestSize.Level0) +{ + std::string key; + std::string value; + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, g_dbAdapterPtr->PutData(key, value)); +} + +/** + * @tc.name: PutData_02 + * @tc.desc: Verify the PutData function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, PutData_02, TestSize.Level0) +{ + uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024 +1 ; + std::string key = "key"; + key.resize(MAX_MESSAGE_LEN); + std::string value; + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, g_dbAdapterPtr->PutData(key, value)); +} + +/** + * @tc.name: PutData_03 + * @tc.desc: Verify the PutData function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, PutData_03, TestSize.Level0) +{ + std::string key = "key"; + std::string value; + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, g_dbAdapterPtr->PutData(key, value)); +} + +/** + * @tc.name: PutData_04 + * @tc.desc: Verify the PutData function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, PutData_04, TestSize.Level0) +{ + uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024 + 1; + std::string key = "key"; + std::string value; + value.resize(MAX_MESSAGE_LEN); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, g_dbAdapterPtr->PutData(key, value)); +} + +/** + * @tc.name: PutData_05 + * @tc.desc: Verify the PutData function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(DbAdapterTest, PutData_05, TestSize.Level0) +{ + std::string key = "key"; + std::string value = "value"; + g_dbAdapterPtr->kvStoragePtr_ = nullptr; + EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL, g_dbAdapterPtr->PutData(key, value)); +} + } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwaremanager/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwaremanager/BUILD.gn index ecf7d4aa0414c2733a07baa62227bbc8ee87c389..caa0a7b9d0353e68dbecd5a163881e193d78f0bc 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwaremanager/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwaremanager/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,7 +20,6 @@ module_out_path = "distributed_hardware_fwk/dh_manager_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//base/notification/eventhandler/interfaces/inner_api", "include", "${utils_path}/include", "${utils_path}/include/log", @@ -31,7 +30,6 @@ config("module_private_config") { "${services_path}/distributedhardwarefwkservice/include/task", "${services_path}/distributedhardwarefwkservice/include/utils", "//third_party/json/include", - "//commonlibrary/c_utils/base/include", ] } @@ -43,11 +41,16 @@ ohos_unittest("DistributedHardwareManagerTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + ] + defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"DistributedHardwareManagerTest\"", diff --git a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwaremanager/src/distributed_hardware_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwaremanager/src/distributed_hardware_manager_test.cpp index dcf836cc134cded7f0fa736ab6cdedefea1e0ac3..90c0f9a640ef327fdda604233d59e760ebd19723 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwaremanager/src/distributed_hardware_manager_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwaremanager/src/distributed_hardware_manager_test.cpp @@ -168,5 +168,92 @@ HWTEST_F(DistributedHardwareManagerTest, sendOffLineEvent_test_003, TestSize.Lev ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish()); ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish()); } + +/** + * @tc.name: Release_001 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareManagerTest, Release_001, TestSize.Level0) +{ + EXPECT_EQ(DH_FWK_SUCCESS, DistributedHardwareManager::GetInstance().Release()); +} + +/** + * @tc.name: GetComponentVersion_001 + * @tc.desc: Verify the GetComponentVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareManagerTest, RGetComponentVersion_001, TestSize.Level0) +{ + std::unordered_map versionMap; + EXPECT_NE(DH_FWK_SUCCESS, DistributedHardwareManager::GetInstance().GetComponentVersion(versionMap)); +} + +/** + * @tc.name: SendOnLineEvent_001 + * @tc.desc: Verify the SendOnLineEvent function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareManagerTest, SendOnLineEvent_001, TestSize.Level0) +{ + uint32_t MAX_ID_LEN = 257; + std::string networkId1; + std::string networkId2; + networkId2.resize(MAX_ID_LEN); + + std::string networkId3 = "networkId"; + std::string uuid1; + std::string uuid2; + uuid2.resize(MAX_ID_LEN); + std::string uuid3 = "uuid3"; + + uint16_t deviceType = 0; + int32_t ret1 = DistributedHardwareManager::GetInstance().SendOnLineEvent(networkId1, uuid3, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret1); + int32_t ret2 = DistributedHardwareManager::GetInstance().SendOnLineEvent(networkId2, uuid3, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret2); + int32_t ret3 = DistributedHardwareManager::GetInstance().SendOnLineEvent(networkId3, uuid3, deviceType); + EXPECT_EQ(DH_FWK_SUCCESS, ret3); + int32_t ret4 = DistributedHardwareManager::GetInstance().SendOnLineEvent(networkId3, uuid1, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret4); + int32_t ret5 = DistributedHardwareManager::GetInstance().SendOnLineEvent(networkId3, uuid2, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret5); +} + +/** + * @tc.name: SendOffLineEvent_001 + * @tc.desc: Verify the SendOffLineEvent function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareManagerTest, SendOffLineEvent_001, TestSize.Level0) +{ + uint32_t MAX_ID_LEN = 257; + std::string networkId1; + std::string networkId2; + networkId2.resize(MAX_ID_LEN); + + std::string networkId3 = "networkId"; + std::string uuid1; + std::string uuid2; + uuid2.resize(MAX_ID_LEN); + std::string uuid3 = "uuid3"; + + uint16_t deviceType = 0; + int32_t ret1 = DistributedHardwareManager::GetInstance().SendOffLineEvent(networkId1, uuid3, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret1); + int32_t ret2 = DistributedHardwareManager::GetInstance().SendOffLineEvent(networkId2, uuid3, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret2); + int32_t ret3 = DistributedHardwareManager::GetInstance().SendOffLineEvent(networkId3, uuid3, deviceType); + EXPECT_EQ(DH_FWK_SUCCESS, ret3); + int32_t ret4 = DistributedHardwareManager::GetInstance().SendOffLineEvent(networkId3, uuid1, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret4); + int32_t ret5 = DistributedHardwareManager::GetInstance().SendOffLineEvent(networkId3, uuid2, deviceType); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret5); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwareservice/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwareservice/BUILD.gn index 66965cdaa9ed73c427d7b368f369d914e89e3edb..432b09052f7af018abe8f68313faf0c0ca9efa83 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwareservice/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwareservice/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,7 +20,9 @@ module_out_path = "distributed_hardware_fwk/distributed_hardware_service_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ + "${av_trans_path}/common/include", "include", + "${innerkits_path}/include", "${utils_path}/include", "${utils_path}/include/log", "${utils_path}/include/eventbus", @@ -30,8 +32,6 @@ config("module_private_config") { "${services_path}/distributedhardwarefwkservice/include/task", "${services_path}/distributedhardwarefwkservice/include/utils", "//third_party/json/include", - "//commonlibrary/c_utils/base/include", - "//base/notification/eventhandler/interfaces/inner_api", ] } @@ -43,7 +43,7 @@ ohos_unittest("DistributedHardwareServiceTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -56,6 +56,7 @@ ohos_unittest("DistributedHardwareServiceTest") { external_deps = [ "c_utils:utils", + "eventhandler:libeventhandler", "ipc:ipc_core", "safwk:system_ability_fwk", ] diff --git a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwareservice/src/distributed_hardware_service_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwareservice/src/distributed_hardware_service_test.cpp index 2e6e5fe95a7b5b57ef20d6d45faef12d91485147..86841ed8185b031500576abe6ed6c299cc4d023d 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwareservice/src/distributed_hardware_service_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwareservice/src/distributed_hardware_service_test.cpp @@ -69,6 +69,20 @@ HWTEST_F(DistributedHardwareServiceTest, register_publisher_listener_001, TestSi EXPECT_EQ(ret, DH_FWK_SUCCESS); } +/** + * @tc.name: register_publisher_listener_002 + * @tc.desc: Verify the RegisterPublisherListener function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareServiceTest, register_publisher_listener_002, TestSize.Level0) +{ + DistributedHardwareService service(ASID, true); + sptr listener = nullptr; + auto ret = service.RegisterPublisherListener(TOPIC, listener); + EXPECT_EQ(ret, DH_FWK_SUCCESS); +} + /** * @tc.name: unregister_publisher_listener_001 * @tc.desc: Verify the UnregisterPublisherListener function @@ -100,6 +114,22 @@ HWTEST_F(DistributedHardwareServiceTest, publish_message_001, TestSize.Level0) EXPECT_EQ(ret, DH_FWK_SUCCESS); } +/** + * @tc.name: publish_message_002 + * @tc.desc: Verify the PublishMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareServiceTest, publish_message_002, TestSize.Level0) +{ + DistributedHardwareService service(ASID, true); + std::string msg = "msg"; + service.RegisterPublisherListener(TOPIC, g_listener); + auto ret = service.PublishMessage(TOPIC, msg); + + EXPECT_EQ(ret, DH_FWK_SUCCESS); +} + /** * @tc.name: onStop_test_002 * @tc.desc: Verify the OnStop function @@ -136,5 +166,20 @@ HWTEST_F(DistributedHardwareServiceTest, dump_test_001, TestSize.Level0) ret = service.Dump(fd, std::vector { ARGS_C }); EXPECT_EQ(ret, DH_FWK_SUCCESS); } + +/** + * @tc.name: OnStart_001 + * @tc.desc: Verify the OnStart function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareServiceTest, OnStart_001, TestSize.Level0) +{ + DistributedHardwareService service(ASID, true); + service.state_ = ServiceRunningState::STATE_RUNNING; + service.OnStart(); + service.OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, service.state_); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bbde54fd5d5843e48a429fbd683dae9aebe4d181 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/distributed_hardware_stub_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${av_trans_path}/common/include", + "include", + "${innerkits_path}/include", + "${utils_path}/include", + "${utils_path}/include/log", + "${utils_path}/include/eventbus", + "${common_path}/log/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/task", + "${services_path}/distributedhardwarefwkservice/include/utils", + "//third_party/json/include", + ] +} + +ohos_unittest("DistributedHardwareStubTest") { + module_out_path = module_out_path + + sources = [ "src/distributed_hardware_stub_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DistributedHardwareStubTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] +} + +group("distributed_hardware_stub_test") { + testonly = true + deps = [ ":DistributedHardwareStubTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/include/distributed_hardware_stub_test.h b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/include/distributed_hardware_stub_test.h new file mode 100644 index 0000000000000000000000000000000000000000..5485f26b3251392c777c7cb31d22b898564dbb21 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/include/distributed_hardware_stub_test.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_STUB_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_STUB_TEST_H + +#include + +#include "distributed_hardware_errno.h" +#include "distributed_hardware_fwk_kit_paras.h" +#define private public +#include "distributed_hardware_stub.h" +#undef private + +namespace OHOS { +namespace DistributedHardware { +class DistributedHardwareStubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr stubTest_ = nullptr; +}; + +class MockDistributedHardwareStub : public DistributedHardwareStub { +public: +int32_t RegisterPublisherListener(const DHTopic topic, const sptr &listener) +{ + (void)topic; + (void)listener; + return DH_FWK_SUCCESS; +} + +int32_t UnregisterPublisherListener(const DHTopic topic, const sptr &listener) +{ + (void)topic; + (void)listener; + return DH_FWK_SUCCESS; +} + +int32_t PublishMessage(const DHTopic topic, const std::string &msg) +{ + (void)topic; + (void)msg; + return DH_FWK_SUCCESS; +} + +std::string QueryLocalSysSpec(QueryLocalSysSpecType spec) +{ + (void)spec; + return ""; +} + +int32_t InitializeAVCenter(const TransRole &transRole, int32_t &engineId) +{ + (void)transRole; + (void)engineId; + return DH_FWK_SUCCESS; +} + +int32_t ReleaseAVCenter(int32_t engineId) +{ + (void)engineId; + return DH_FWK_SUCCESS; +} + +int32_t CreateControlChannel(int32_t engineId, const std::string &peerDevId) +{ + (void)engineId; + (void)peerDevId; + return DH_FWK_SUCCESS; +} + +int32_t NotifyAVCenter(int32_t engineId, const AVTransEvent &event) +{ + (void)engineId; + (void)event; + return DH_FWK_SUCCESS; +} + +int32_t RegisterCtlCenterCallback(int32_t engineId, const sptr &callback) +{ + (void)engineId; + (void)callback; + return DH_FWK_SUCCESS; +} +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/src/distributed_hardware_stub_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/src/distributed_hardware_stub_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ba1a8c1cace4b5fbc9cd2d1cce6de9017c6e1c4 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/distributedhardwarestub/src/distributed_hardware_stub_test.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "distributed_hardware_stub_test.h" + +#include + +#include "iremote_stub.h" +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void DistributedHardwareStubTest::SetUpTestCase(void) {} + +void DistributedHardwareStubTest::TearDownTestCase(void) {} + +void DistributedHardwareStubTest::SetUp() +{ + stubTest_ = std::make_shared(); +} + +void DistributedHardwareStubTest::TearDown() +{ + stubTest_ = nullptr; +} + +/** + * @tc.name: OnRemoteRequest_001 + * @tc.desc: Verify the OnRemoteRequest function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareStubTest, OnRemoteRequest_001, TestSize.Level0) +{ + uint32_t code = 0; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_NE(DH_FWK_SUCCESS, stubTest_->OnRemoteRequest(code, data, reply, option)); +} + +/** + * @tc.name: OnRemoteRequest_002 + * @tc.desc: Verify the OnRemoteRequest function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareStubTest, OnRemoteRequest_002, TestSize.Level0) +{ + uint32_t code = 0; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_EQ(ERR_INVALID_DATA, stubTest_->OnRemoteRequest(code, data, reply, option)); +} + +/** + * @tc.name: RegisterPublisherListenerInner_001 + * @tc.desc: Verify the RegisterPublisherListenerInner function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareStubTest, RegisterPublisherListenerInner_001, TestSize.Level0) +{ + MessageParcel data; + MessageParcel reply; + EXPECT_NE(DH_FWK_SUCCESS, stubTest_->RegisterPublisherListenerInner(data, reply)); +} + +/** + * @tc.name: UnregisterPublisherListenerInner_001 + * @tc.desc: Verify the UnregisterPublisherListenerInner function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareStubTest, UnregisterPublisherListenerInner_001, TestSize.Level0) +{ + MessageParcel data; + MessageParcel reply; + EXPECT_NE(DH_FWK_SUCCESS, stubTest_->UnregisterPublisherListenerInner(data, reply)); +} + +/** + * @tc.name: PublishMessageInner_001 + * @tc.desc: Verify the PublishMessageInner function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareStubTest, PublishMessageInner_001, TestSize.Level0) +{ + MessageParcel data; + MessageParcel reply; + EXPECT_NE(DH_FWK_SUCCESS, stubTest_->PublishMessageInner(data, reply)); +} + +/** + * @tc.name: ValidTopic_001 + * @tc.desc: Verify the ValidTopic function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(DistributedHardwareStubTest, ValidTopic_001, TestSize.Level0) +{ + uint32_t topic = static_cast(DHTopic::TOPIC_MIN); + EXPECT_EQ(false, stubTest_->ValidTopic(topic)); + + uint32_t topic1 = static_cast(DHTopic::TOPIC_MAX); + EXPECT_EQ(false, stubTest_->ValidTopic(topic1)); + + uint32_t topic2 = static_cast(DHTopic::TOPIC_START_DSCREEN); + EXPECT_EQ(true, stubTest_->ValidTopic(topic2)); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0e912ddb8e63ce0067dac82c337802066dd54e1d --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/enabled_comps_dump_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//third_party/json/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/hidumphelper", + ] +} + +ohos_unittest("EnabledCompsDumpTest") { + module_out_path = module_out_path + + sources = [ "src/enabled_comps_dump_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"EnabledCompsDumpTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] +} + +group("enabled_comps_dump_test") { + testonly = true + deps = [ ":EnabledCompsDumpTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/include/version_info_manager_test.h b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/include/enabled_comps_dump_test.h similarity index 79% rename from services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/include/version_info_manager_test.h rename to services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/include/enabled_comps_dump_test.h index b2c20ca5534f73e3b2c0a73183aab3239e513161..db52150a43a1f478e4e9ff99532cc4d9c7017b26 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/include/version_info_manager_test.h +++ b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/include/enabled_comps_dump_test.h @@ -13,17 +13,14 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_HARDWARE_VERSION_INFO_MANAGER_TEST_H -#define OHOS_DISTRIBUTED_HARDWARE_VERSION_INFO_MANAGER_TEST_H +#ifndef OHOS_DISTRIBUTED_ENABLED_COMPS_DUMP_TEST_H +#define OHOS_DISTRIBUTED_ENABLED_COMPS_DUMP_TEST_H #include -#include - -#include "version_info.h" namespace OHOS { namespace DistributedHardware { -class VersionInfoManagerTest : public testing::Test { +class EnabledCompsDumpTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); diff --git a/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/src/enabled_comps_dump_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/src/enabled_comps_dump_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fceaced286faa2740172d85e811c7a12ac964609 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/enabledcompsdump/src/enabled_comps_dump_test.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "enabled_comps_dump_test.h" + +#include +#include +#include + +#define private public +#include "enabled_comps_dump.h" +#undef private + +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void EnabledCompsDumpTest::SetUpTestCase(void) {} + +void EnabledCompsDumpTest::TearDownTestCase(void) {} + +void EnabledCompsDumpTest::SetUp() {} + +void EnabledCompsDumpTest::TearDown() {} + +/** + * @tc.name: DumpEnabledComp_001 + * @tc.desc: Verify the DumpEnabledComp function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(EnabledCompsDumpTest, DumpEnabledComp_001, TestSize.Level0) +{ + std::string networkId; + DHType dhType = DHType::CAMERA; + std::string dhId; + EnabledCompsDump::GetInstance().DumpEnabledComp(networkId, dhType, dhId); + EXPECT_EQ(false, EnabledCompsDump::GetInstance().compInfoSet_.empty()); +} + +/** + * @tc.name: DumpDisabledComp_001 + * @tc.desc: Verify the DumpDisabledComp function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(EnabledCompsDumpTest, DumpDisabledComp_001, TestSize.Level0) +{ + std::string networkId; + DHType dhType = DHType::CAMERA; + std::string dhId; + EnabledCompsDump::GetInstance().DumpDisabledComp(networkId, dhType, dhId); + EXPECT_EQ(true, EnabledCompsDump::GetInstance().compInfoSet_.empty()); +} + +/** + * @tc.name: Dump_001 + * @tc.desc: Verify the Dump function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(EnabledCompsDumpTest, Dump_001, TestSize.Level0) +{ + std::set compInfoSet; + EnabledCompsDump::GetInstance().Dump(compInfoSet); + EXPECT_EQ(true, EnabledCompsDump::GetInstance().compInfoSet_.empty()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..aaf718a094594e2165bbd9321d7a6b349d6781ce --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/hidump_helper_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//third_party/json/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/hidumphelper", + "${common_path}/utils/include", + ] +} + +ohos_unittest("HidumpHelperTest") { + module_out_path = module_out_path + + sources = [ "src/hidump_helper_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"HidumpHelperTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] +} + +group("hidump_helper_test") { + testonly = true + deps = [ ":HidumpHelperTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/include/hidump_helper_test.h b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/include/hidump_helper_test.h new file mode 100644 index 0000000000000000000000000000000000000000..a8c7b6d85a4337d8a6311e4e788734b083f01e84 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/include/hidump_helper_test.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_HIDUMP_HELPER_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_HIDUMP_HELPER_TEST_H + +#include + +namespace OHOS { +namespace DistributedHardware { +class HidumpHelperTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/src/hidump_helper_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/src/hidump_helper_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1cfeb6712a09f9744b0f2161504d6e41a8a84c9d --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/hidumphelper/hidumphelper/src/hidump_helper_test.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hidump_helper_test.h" + +#include +#include +#include + +#define private public +#include "hidump_helper.h" +#undef private +#include "distributed_hardware_errno.h" + +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void HidumpHelperTest::SetUpTestCase(void) {} + +void HidumpHelperTest::TearDownTestCase(void) {} + +void HidumpHelperTest::SetUp() {} + +void HidumpHelperTest::TearDown() {} + +/** + * @tc.name: Dump_001 + * @tc.desc: Verify the Dump function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, Dump_001, TestSize.Level0) +{ + std::vector args; + std::string result; + int32_t ret = HidumpHelper::GetInstance().Dump(args, result); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: Dump_002 + * @tc.desc: Verify the Dump function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, Dump_002, TestSize.Level0) +{ + std::vector args; + args.push_back("ARGS_HELP"); + std::string result; + int32_t ret = HidumpHelper::GetInstance().Dump(args, result); + EXPECT_EQ(ERR_DH_FWK_HIDUMP_INVALID_ARGS, ret); +} + +/** + * @tc.name: ProcessDump_001 + * @tc.desc: Verify the ProcessDump function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, ProcessDump_001, TestSize.Level0) +{ + HidumpFlag flag = HidumpFlag::UNKNOWN; + std::string result; + int32_t ret = HidumpHelper::GetInstance().ProcessDump(flag, result); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: ShowAllLoadedComps_001 + * @tc.desc: Verify the ShowAllLoadedComps function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, ShowAllLoadedComps_001, TestSize.Level0) +{ + std::string result; + int32_t ret = HidumpHelper::GetInstance().ShowAllLoadedComps(result); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: ShowAllEnabledComps_001 + * @tc.desc: Verify the ShowAllEnabledComps function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, ShowAllEnabledComps_001, TestSize.Level0) +{ + std::string result; + int32_t ret = HidumpHelper::GetInstance().ShowAllEnabledComps(result); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: ShowAllTaskInfos_001 + * @tc.desc: Verify the ShowAllTaskInfos function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, ShowAllTaskInfos_001, TestSize.Level0) +{ + std::string result; + int32_t ret = HidumpHelper::GetInstance().ShowAllTaskInfos(result); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: ShowAllCapabilityInfos_001 + * @tc.desc: Verify the ShowAllCapabilityInfos function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, ShowAllCapabilityInfos_001, TestSize.Level0) +{ + std::string result; + int32_t ret = HidumpHelper::GetInstance().ShowAllCapabilityInfos(result); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: ShowHelp_001 + * @tc.desc: Verify the ShowHelp function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, ShowHelp_001, TestSize.Level0) +{ + std::string result; + int32_t ret = HidumpHelper::GetInstance().ShowHelp(result); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: ShowIllealInfomation_001 + * @tc.desc: Verify the ShowIllealInfomation function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(HidumpHelperTest, ShowIllealInfomation_001, TestSize.Level0) +{ + std::string result; + int32_t ret = HidumpHelper::GetInstance().ShowIllealInfomation(result); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/ipc/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/ipc/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f188e1a663ca3c679a1528eb4f186393b7bd9e5d --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/ipc/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../../../../distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/publisher_listener_proxy_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/ipc", + ] +} + +ohos_unittest("PublisherListenerProxyTest") { + module_out_path = module_out_path + + sources = [ "src/publisher_listener_proxy_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${innerkits_path}:libdhfwk_sdk", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"PublisherListenerProxyTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + ] +} + +group("publisher_listener_proxy_test") { + testonly = true + deps = [ ":PublisherListenerProxyTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/ipc/include/publisher_listener_proxy_test.h b/services/distributedhardwarefwkservice/test/unittest/common/ipc/include/publisher_listener_proxy_test.h new file mode 100644 index 0000000000000000000000000000000000000000..e7afb95c5ad902a51c74216cf89f37e5f44dac4e --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/ipc/include/publisher_listener_proxy_test.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_PUBLISHER_LISTENER_PROXY_TEST_H +#define OHOS_PUBLISHER_LISTENER_PROXY_TEST_H + +#include +#include +#include + +#define private public +#include "publisher_listener_proxy.h" +#undef private +#include "distributed_hardware_errno.h" + +namespace OHOS { +namespace DistributedHardware { +class PublisherListenerProxyTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr proxy_ = nullptr; +}; + +class MockIRemoteObject : public IRemoteObject { +public: +sptr AsObject() +{ + return nullptr; +} + +void OnMessage(const DHTopic topic, const std::string& message) +{ + (void)topic; + (void)message; +} + +int32_t GetObjectRefCount() +{ + return DH_FWK_SUCCESS; +} + +int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + (void)code; + (void)data; + (void)reply; + (void)option; + return DH_FWK_SUCCESS; +} + +bool AddDeathRecipient(const sptr &recipient) +{ + (void)recipient; + return true; +} + +bool RemoveDeathRecipient(const sptr &recipient) +{ + (void)recipient; + return true; +} + +int Dump(int fd, const std::vector &args) +{ + (void)fd; + (void)args; + return DH_FWK_SUCCESS; +} +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_PUBLISHER_LISTENER_PROXY_TEST_H \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/unittest/common/ipc/src/publisher_listener_proxy_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/ipc/src/publisher_listener_proxy_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efda36b6a446f4fdc6b5e04cfac10232b4487abb --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/ipc/src/publisher_listener_proxy_test.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "publisher_listener_proxy_test.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void PublisherListenerProxyTest::SetUpTestCase() +{ +} + +void PublisherListenerProxyTest::TearDownTestCase() +{ +} + +void PublisherListenerProxyTest::SetUp() +{ + sptr object = nullptr; + proxy_ = std::make_shared(object); +} + +void PublisherListenerProxyTest::TearDown() +{ + proxy_ = nullptr; +} + +/** + * @tc.name: OnMessage_001 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(PublisherListenerProxyTest, OnMessage_001, TestSize.Level0) +{ + uint32_t invalid = 7; + DHTopic topic = static_cast(invalid); + std::string message; + proxy_->OnMessage(topic, message); + EXPECT_EQ(true, message.empty()); +} + +/** + * @tc.name: OnMessage_002 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(PublisherListenerProxyTest, OnMessage_002, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + std::string message; + proxy_->OnMessage(topic, message); + EXPECT_EQ(true, message.empty()); +} + +/** + * @tc.name: OnMessage_003 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(PublisherListenerProxyTest, OnMessage_003, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + std::string message = "message"; + proxy_->OnMessage(topic, message); + EXPECT_EQ(false, message.empty()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/localhardwaremanager/BUILD.gn similarity index 82% rename from services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/BUILD.gn rename to services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/localhardwaremanager/BUILD.gn index 37505648a53f9db71e152b7e54bd7a42a66fdba9..aa5f97731d6b021475f3c72a4888b0c227f9bbcc 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/localhardwaremanager/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -12,6 +12,7 @@ # limitations under the License. import("//build/test.gni") + import( "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") @@ -30,6 +31,7 @@ config("module_private_config") { "${services_path}/distributedhardwarefwkservice/include/componentloader", "${services_path}/distributedhardwarefwkservice/include/localhardwaremanager", "${services_path}/distributedhardwarefwkservice/include/utils", + "${services_path}/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/include", "${common_path}/utils/include", "${common_path}/log/include", "//third_party/json/include", @@ -40,21 +42,20 @@ ohos_unittest("LocalHardwareManagerTest") { module_out_path = module_out_path sources = [ + "${services_path}/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/src/mock_hardware_handler.cpp", "src/local_hardware_manager_test.cpp", - "src/mock_hardware_handler.cpp", - "src/plugin_listener_impl_test.cpp", ] configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", "//third_party/googletest:gtest_main", ] external_deps = [ "eventhandler:libeventhandler", - "hisysevent_native:libhisysevent", + "hisysevent:libhisysevent", "kv_store:distributeddata_inner", ] diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/include/local_hardware_manager_test.h b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/localhardwaremanager/include/local_hardware_manager_test.h similarity index 100% rename from services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/include/local_hardware_manager_test.h rename to services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/localhardwaremanager/include/local_hardware_manager_test.h diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/localhardwaremanager/src/local_hardware_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/localhardwaremanager/src/local_hardware_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0895975afdbb06ea37f160731b7755244b23f7fe --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/localhardwaremanager/src/local_hardware_manager_test.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "local_hardware_manager_test.h" + +#define private public +#include "capability_info_manager.h" +#include "component_loader.h" +#include "dh_context.h" +#include "local_hardware_manager.h" +#undef private +#include "mock_hardware_handler.h" +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void LocalHardwareManagerTest::SetUpTestCase(void) {} + +void LocalHardwareManagerTest::TearDownTestCase(void) {} + +void LocalHardwareManagerTest::SetUp() {} + +void LocalHardwareManagerTest::TearDown() {} + +/** + * @tc.name: local_hardware_manager_test_001 + * @tc.desc: Verify the Init function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, local_hardware_manager_test_001, TestSize.Level0) +{ + LocalHardwareManager::GetInstance().Init(); +} + +/** + * @tc.name: local_hardware_manager_test_002 + * @tc.desc: Verify the UnInit function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, local_hardware_manager_test_002, TestSize.Level0) +{ + LocalHardwareManager::GetInstance().UnInit(); +} + +/** + * @tc.name: Init_001 + * @tc.desc: Verify the Init function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, Init_001, TestSize.Level0) +{ + ComponentLoader::GetInstance().UnInit(); + LocalHardwareManager::GetInstance().Init(); + EXPECT_EQ(true, LocalHardwareManager::GetInstance().pluginListenerMap_.empty()); +} + +/** + * @tc.name: CheckNonExistCapabilityInfo_001 + * @tc.desc: Verify the CheckNonExistCapabilityInfo function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, CheckNonExistCapabilityInfo_001, TestSize.Level0) +{ + std::vector dhItems; + DHType dhType = DHType::INPUT; + LocalHardwareManager::GetInstance().CheckNonExistCapabilityInfo(dhItems, dhType); + EXPECT_EQ(true, LocalHardwareManager::GetInstance().pluginListenerMap_.empty()); +} + +/** + * @tc.name: CheckNonExistCapabilityInfo_002 + * @tc.desc: Verify the CheckNonExistCapabilityInfo function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, CheckNonExistCapabilityInfo_002, TestSize.Level0) +{ + std::vector dhItems; + DHType dhType = DHType::AUDIO; + LocalHardwareManager::GetInstance().CheckNonExistCapabilityInfo(dhItems, dhType); + EXPECT_EQ(true, LocalHardwareManager::GetInstance().pluginListenerMap_.empty()); +} + +/** + * @tc.name: GetLocalCapabilityMapByPrefix_001 + * @tc.desc: Verify the GetLocalCapabilityMapByPrefix function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, GetLocalCapabilityMapByPrefix_001, TestSize.Level0) +{ + DHType dhType = DHType::INPUT; + CapabilityInfoMap capabilityInfoMap; + LocalHardwareManager::GetInstance().GetLocalCapabilityMapByPrefix(dhType, capabilityInfoMap); + EXPECT_EQ(true, LocalHardwareManager::GetInstance().pluginListenerMap_.empty()); +} + +/** + * @tc.name: GetLocalCapabilityMapByPrefix_002 + * @tc.desc: Verify the GetLocalCapabilityMapByPrefix function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, GetLocalCapabilityMapByPrefix_002, TestSize.Level0) +{ + DHType dhType = DHType::GPS; + CapabilityInfoMap capabilityInfoMap; + DHContext::GetInstance().devInfo_.deviceId = "deviceId"; + LocalHardwareManager::GetInstance().GetLocalCapabilityMapByPrefix(dhType, capabilityInfoMap); + EXPECT_EQ(true, LocalHardwareManager::GetInstance().pluginListenerMap_.empty()); +} + +/** + * @tc.name: QueryLocalHardware_001 + * @tc.desc: Verify the QueryLocalHardware function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, QueryLocalHardware_001, TestSize.Level0) +{ + DHType dhType = DHType::AUDIO; + IHardwareHandler *hardwareHandler = new MockHardwareHandler(); + LocalHardwareManager::GetInstance().QueryLocalHardware(dhType, hardwareHandler); + EXPECT_EQ(true, LocalHardwareManager::GetInstance().pluginListenerMap_.empty()); +} + +/** + * @tc.name: AddLocalCapabilityInfo_001 + * @tc.desc: Verify the AddLocalCapabilityInfo function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(LocalHardwareManagerTest, AddLocalCapabilityInfo_001, TestSize.Level0) +{ + std::vector dhItems; + DHType dhType = DHType::AUDIO; + LocalHardwareManager::GetInstance().AddLocalCapabilityInfo(dhItems, dhType); + EXPECT_EQ(true, LocalHardwareManager::GetInstance().pluginListenerMap_.empty()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..99d25e2f26fc72120019fe3e58dad497417547aa --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/plugin_listener_impl_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${utils_path}/include", + "${utils_path}/include/eventbus", + "${utils_path}/include/log", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/versionmanager", + "${services_path}/distributedhardwarefwkservice/include/resourcemanager", + "${services_path}/distributedhardwarefwkservice/include/componentloader", + "${services_path}/distributedhardwarefwkservice/include/localhardwaremanager", + "${services_path}/distributedhardwarefwkservice/include/utils", + "${common_path}/utils/include", + "${common_path}/log/include", + "//third_party/json/include", + ] +} + +ohos_unittest("PluginListenerImplTest") { + module_out_path = module_out_path + + sources = [ + "src/mock_hardware_handler.cpp", + "src/plugin_listener_impl_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "eventhandler:libeventhandler", + "hisysevent:libhisysevent", + "kv_store:distributeddata_inner", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"PluginListenerImplTest\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("plugin_listener_impl_test") { + testonly = true + deps = [ ":PluginListenerImplTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/include/mock_hardware_handler.h b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/include/mock_hardware_handler.h similarity index 100% rename from services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/include/mock_hardware_handler.h rename to services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/include/mock_hardware_handler.h diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/include/plugin_listener_impl_test.h b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/include/plugin_listener_impl_test.h similarity index 100% rename from services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/include/plugin_listener_impl_test.h rename to services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/include/plugin_listener_impl_test.h diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/src/mock_hardware_handler.cpp b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/src/mock_hardware_handler.cpp similarity index 100% rename from services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/src/mock_hardware_handler.cpp rename to services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/src/mock_hardware_handler.cpp diff --git a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/src/plugin_listener_impl_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/src/plugin_listener_impl_test.cpp similarity index 47% rename from services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/src/plugin_listener_impl_test.cpp rename to services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/src/plugin_listener_impl_test.cpp index 4a26a0413af6bb2b44d18eca98b3ce792105262e..9e463772cbc51bf2496dfa7c0b18bfe3575d87b0 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/src/plugin_listener_impl_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/localhardwaremanager/pluginlistenerimpl/src/plugin_listener_impl_test.cpp @@ -65,5 +65,84 @@ HWTEST_F(PluginListenerImplTest, plugin_listener_impl_test_002, TestSize.Level0) EXPECT_EQ(g_mockHardwareHandler->UnPluginHardware(dhId), DH_FWK_SUCCESS); g_mockHardwareHandler->UnRegisterPluginListener(); } + +/** + * @tc.name: PluginHardware_001 + * @tc.desc: Verify the PluginHardware function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(PluginListenerImplTest, PluginHardware_001, TestSize.Level0) +{ + DHType type = DHType::AUDIO; + std::shared_ptr listener = std::make_shared(type); + std::string dhId; + std::string attrs; + listener->PluginHardware(dhId, attrs); + EXPECT_EQ(true, dhId.empty()); +} + +/** + * @tc.name: PluginHardware_002 + * @tc.desc: Verify the PluginHardware function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(PluginListenerImplTest, PluginHardware_002, TestSize.Level0) +{ + uint32_t MAX_ID_LEN = 257; + DHType type = DHType::AUDIO; + std::shared_ptr listener = std::make_shared(type); + std::string dhId1; + std::string dhId2; + dhId2.resize(MAX_ID_LEN); + std::string dhId3 = "dhId3"; + std::string attrs1; + std::string attrs2; + attrs2.resize(MAX_ID_LEN); + std::string attrs3 = "attrs3"; + listener->PluginHardware(dhId1, attrs1); + listener->PluginHardware(dhId2, attrs1); + listener->PluginHardware(dhId3, attrs1); + listener->PluginHardware(dhId3, attrs2); + listener->PluginHardware(dhId3, attrs3); + EXPECT_EQ(true, dhId1.empty()); +} + +/** + * @tc.name: UnPluginHardware_001 + * @tc.desc: Verify the UnPluginHardware function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(PluginListenerImplTest, UnPluginHardware_001, TestSize.Level0) +{ + DHType type = DHType::AUDIO; + std::shared_ptr listener = std::make_shared(type); + std::string dhId; + listener->UnPluginHardware(dhId); + EXPECT_EQ(true, dhId.empty()); +} + +/** + * @tc.name: UnPluginHardware_002 + * @tc.desc: Verify the UnPluginHardware function. + * @tc.type: FUNC + * @tc.require: AR000GHSK3 + */ +HWTEST_F(PluginListenerImplTest, UnPluginHardware_002, TestSize.Level0) +{ + uint32_t MAX_ID_LEN = 257; + DHType type = DHType::AUDIO; + std::shared_ptr listener = std::make_shared(type); + std::string dhId1; + std::string dhId2; + dhId2.resize(MAX_ID_LEN); + std::string dhId3 = "dhId3"; + listener->UnPluginHardware(dhId1); + listener->UnPluginHardware(dhId2); + listener->UnPluginHardware(dhId3); + EXPECT_EQ(true, dhId1.empty()); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4d4ffd5dc6da23631caed3d93b925b7289d2f10e --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/low_latency_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//third_party/json/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/lowlatency", + "${services_path}/distributedhardwarefwkservice/include/utils", + ] +} + +ohos_unittest("LowLatencyTest") { + module_out_path = module_out_path + + sources = [ "src/low_latency_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${innerkits_path}:libdhfwk_sdk", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"LowLatencyTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] +} + +group("low_latency_test") { + testonly = true + deps = [ ":LowLatencyTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/include/low_latency_test.h b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/include/low_latency_test.h new file mode 100644 index 0000000000000000000000000000000000000000..914222113ea742df6f3a51bee53f6e020e297187 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/include/low_latency_test.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_TEST_H + +#include +#include +#include + +#define private public +#include "low_latency.h" +#undef private +#include "distributed_hardware_errno.h" + +namespace OHOS { +namespace DistributedHardware { +class LowLatencyTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_TEST_H \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/src/low_latency_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/src/low_latency_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4eb918ee2a91f43378be227068cf7ffa0051d576 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatency/src/low_latency_test.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "low_latency_test.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void LowLatencyTest::SetUpTestCase() +{ +} + +void LowLatencyTest::TearDownTestCase() +{ +} + +void LowLatencyTest::SetUp() +{ +} + +void LowLatencyTest::TearDown() +{ + LowLatency::GetInstance().lowLatencySwitchSet_.clear(); +} + +/** + * @tc.name: EnableLowLatency_001 + * @tc.desc: Verify the EnableLowLatency function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyTest, EnableLowLatency_001, TestSize.Level0) +{ + DHType dhType = DHType::UNKNOWN; + LowLatency::GetInstance().EnableLowLatency(dhType); + EXPECT_EQ(true, LowLatency::GetInstance().lowLatencySwitchSet_.empty()); +} + +/** + * @tc.name: EnableLowLatency_002 + * @tc.desc: Verify the EnableLowLatency function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyTest, EnableLowLatency_002, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + LowLatency::GetInstance().EnableLowLatency(dhType); + EXPECT_EQ(false, LowLatency::GetInstance().lowLatencySwitchSet_.empty()); +} + +/** + * @tc.name: EnableLowLatency_003 + * @tc.desc: Verify the EnableLowLatency function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyTest, EnableLowLatency_003, TestSize.Level0) +{ + LowLatency::GetInstance().lowLatencySwitchSet_.insert(DHType::AUDIO); + DHType dhType = DHType::CAMERA; + LowLatency::GetInstance().EnableLowLatency(dhType); + EXPECT_EQ(false, LowLatency::GetInstance().lowLatencySwitchSet_.empty()); +} + +/** + * @tc.name: EnableLowLatency_004 + * @tc.desc: Verify the EnableLowLatency function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyTest, EnableLowLatency_004, TestSize.Level0) +{ + uint32_t MAX_SWITCH_SIZE = 256; + for (uint32_t i = 0; i <= MAX_SWITCH_SIZE; ++i) { + LowLatency::GetInstance().lowLatencySwitchSet_.insert(static_cast(i)); + } + DHType dhType = DHType::CAMERA; + LowLatency::GetInstance().EnableLowLatency(dhType); + EXPECT_EQ(false, LowLatency::GetInstance().lowLatencySwitchSet_.empty()); +} + +/** + * @tc.name: DisableLowLatency_001 + * @tc.desc: Verify the DisableLowLatency function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyTest, DisableLowLatency_001, TestSize.Level0) +{ + DHType dhType = DHType::UNKNOWN; + LowLatency::GetInstance().DisableLowLatency(dhType); + EXPECT_EQ(true, LowLatency::GetInstance().lowLatencySwitchSet_.empty()); +} + +/** + * @tc.name: DisableLowLatency_002 + * @tc.desc: Verify the DisableLowLatency function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyTest, DisableLowLatency_002, TestSize.Level0) +{ + DHType dhType = DHType::CAMERA; + LowLatency::GetInstance().lowLatencySwitchSet_.insert(dhType); + LowLatency::GetInstance().DisableLowLatency(dhType); + EXPECT_EQ(true, LowLatency::GetInstance().lowLatencySwitchSet_.empty()); +} + +/** + * @tc.name: CloseLowLatency_001 + * @tc.desc: Verify the CloseLowLatency function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyTest, CloseLowLatency_001, TestSize.Level0) +{ + LowLatency::GetInstance().CloseLowLatency(); + EXPECT_EQ(true, LowLatency::GetInstance().lowLatencySwitchSet_.empty()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3aea19cd959caad9833263149ad8134a81874590 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/low_latency_listener_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//third_party/json/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/lowlatency", + "${services_path}/distributedhardwarefwkservice/include/utils", + ] +} + +ohos_unittest("LowLatencyListenerTest") { + module_out_path = module_out_path + + sources = [ "src/low_latency_listener_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${innerkits_path}:libdhfwk_sdk", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gtest_main", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"LowLatencyListenerTest\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] +} + +group("low_latency_listener_test") { + testonly = true + deps = [ ":LowLatencyListenerTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/include/low_latency_listener_test.h b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/include/low_latency_listener_test.h new file mode 100644 index 0000000000000000000000000000000000000000..0a38cae4f6eba3757d7a3ea4cb870fade297f049 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/include/low_latency_listener_test.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_LISTENER_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_LISTENER_TEST_H + +#include +#include +#include + +#define private public +#include "low_latency_listener.h" +#include "low_latency_timer.h" +#undef private +#include "distributed_hardware_errno.h" + +namespace OHOS { +namespace DistributedHardware { +class LowLatencyListenerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + sptr listener_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_HARDWARE_LOW_LATENCY_LISTENER_TEST_H \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/src/low_latency_listener_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/src/low_latency_listener_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3779aa72f996169c5a373f91ed17ea47b3a79e4a --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/lowlatency/lowlatencylistener/src/low_latency_listener_test.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "low_latency_listener_test.h" +#include "nlohmann/json.hpp" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void LowLatencyListenerTest::SetUpTestCase() +{ +} + +void LowLatencyListenerTest::TearDownTestCase() +{ +} + +void LowLatencyListenerTest::SetUp() +{ + listener_ = new(std::nothrow) LowLatencyListener; +} + +void LowLatencyListenerTest::TearDown() +{ + listener_ = nullptr; +} + +/** + * @tc.name: OnMessage_001 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, OnMessage_001, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_MIN; + std::string message; + listener_->OnMessage(topic, message); + EXPECT_EQ(nullptr, listener_->AsObject()); +} + +/** + * @tc.name: OnMessage_002 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, OnMessage_002, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + std::string message; + listener_->OnMessage(topic, message); + EXPECT_EQ(nullptr, listener_->AsObject()); +} + +/** + * @tc.name: OnMessage_003 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, OnMessage_003, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + std::string message = "message"; + listener_->OnMessage(topic, message); + EXPECT_EQ(nullptr, listener_->AsObject()); +} + +/** + * @tc.name: OnMessage_004 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, OnMessage_004, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + + nlohmann::json json; + const std::string DH_TYPE = "dh_type"; + const std::string LOW_LATENCY_ENABLE = "low_latency_enable"; + + json[DH_TYPE] = "dh_type"; + json[LOW_LATENCY_ENABLE] = "low_latency_enable"; + std::string message = json.dump(); + listener_->OnMessage(topic, message); + EXPECT_EQ(nullptr, listener_->AsObject()); +} + +/** + * @tc.name: OnMessage_005 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, OnMessage_005, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + std::string message; + uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024; + message.resize(MAX_MESSAGE_LEN); + listener_->OnMessage(topic, message); + EXPECT_EQ(nullptr, listener_->AsObject()); +} + +/** + * @tc.name: OnMessage_006 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, OnMessage_006, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + nlohmann::json json; + const std::string DH_TYPE; + const std::string LOW_LATENCY_ENABLE; + + json[DH_TYPE] = 0x01; + json[LOW_LATENCY_ENABLE] = true; + std::string message = json.dump(); + listener_->OnMessage(topic, message); + EXPECT_EQ(nullptr, listener_->AsObject()); +} + +/** + * @tc.name: OnMessage_007 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, OnMessage_007, TestSize.Level0) +{ + DHTopic topic = DHTopic::TOPIC_START_DSCREEN; + nlohmann::json json; + const std::string DH_TYPE; + const std::string LOW_LATENCY_ENABLE; + + json[DH_TYPE] = 0x01; + json[LOW_LATENCY_ENABLE] = false; + std::string message = json.dump(); + listener_->OnMessage(topic, message); + EXPECT_EQ(nullptr, listener_->AsObject()); +} + +/** + * @tc.name: ExecuteInner_008 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, ExecuteInner_008, TestSize.Level0) +{ + std::string timerId; + int32_t delayTimeMs = 1; + LowLatencyTimer timer(timerId, delayTimeMs); + timer.ExecuteInner(); + EXPECT_EQ(nullptr, listener_->AsObject()); +} + +/** + * @tc.name: HandleStopTimer_008 + * @tc.desc: Verify the OnMessage function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(LowLatencyListenerTest, HandleStopTimer_008, TestSize.Level0) +{ + std::string timerId; + int32_t delayTimeMs = 1; + LowLatencyTimer timer(timerId, delayTimeMs); + timer.HandleStopTimer(); + EXPECT_EQ(nullptr, listener_->AsObject()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/publisher/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/publisher/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cda9ac005bc5e04ce9bc45b64fc642a894078fc6 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/publisher/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/publisher_item_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${services_path}/distributedhardwarefwkservice/include/publisher", + "${common_path}/utils/include", + ] +} + +ohos_unittest("PublisherItemTest") { + module_out_path = module_out_path + + sources = [ "src/publisher_item_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] +} + +group("publisher_item_test") { + testonly = true + deps = [ ":PublisherItemTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/publisher/include/publisher_item_test.h b/services/distributedhardwarefwkservice/test/unittest/common/publisher/include/publisher_item_test.h new file mode 100644 index 0000000000000000000000000000000000000000..419cd442c3163ed6e347932bc51019c7b9cb844d --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/publisher/include/publisher_item_test.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_PUBLISHER_ITEM_TEST_H +#define OHOS_PUBLISHER_ITEM_TEST_H + +#include +#include + +#define private public +#include "publisher_item.h" +#undef private + +namespace OHOS { +namespace DistributedHardware { +class PublisherItemTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +class MockIPublisherListener : public IPublisherListener { +public: +sptr AsObject() +{ + return nullptr; +} + +void OnMessage(const DHTopic topic, const std::string& message) +{ + (void)topic; + (void)message; +} +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/test/unittest/common/publisher/src/publisher_item_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/publisher/src/publisher_item_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e187bace709936383950cca7537d8b336dce1ee --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/publisher/src/publisher_item_test.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "publisher_item_test.h" + +using namespace testing::ext; +using namespace std; +namespace OHOS { +namespace DistributedHardware { + +void PublisherItemTest::SetUpTestCase(void) {} + +void PublisherItemTest::TearDownTestCase(void) {} + +void PublisherItemTest::SetUp() {} + +void PublisherItemTest::TearDown() {} + +/** + * @tc.name: AddListener_001 + * @tc.desc: Verify the AddListener ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(PublisherItemTest, AddListener_001, TestSize.Level0) +{ + PublisherItem item; + sptr listener = nullptr; + item.AddListener(listener); + EXPECT_EQ(true, item.listeners_.empty()); +} + +/** + * @tc.name: AddListener_002 + * @tc.desc: Verify the AddListener ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(PublisherItemTest, AddListener_002, TestSize.Level0) +{ + PublisherItem item(DHTopic::TOPIC_MIN); + sptr listener = nullptr; + item.AddListener(listener); + EXPECT_EQ(true, item.listeners_.empty()); +} + +/** + * @tc.name: AddListener_003 + * @tc.desc: Verify the AddListener ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(PublisherItemTest, AddListener_003, TestSize.Level0) +{ + PublisherItem item(DHTopic::TOPIC_MIN); + sptr listener = new MockIPublisherListener(); + item.AddListener(listener); + EXPECT_EQ(false, item.listeners_.empty()); +} + + +/** + * @tc.name: RemoveListener_001 + * @tc.desc: Verify the RemoveListener ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(PublisherItemTest, RemoveListener_001, TestSize.Level0) +{ + PublisherItem item(DHTopic::TOPIC_MIN); + sptr listener = nullptr; + item.RemoveListener(listener); + EXPECT_EQ(true, item.listeners_.empty()); +} + +/** + * @tc.name: RemoveListener_002 + * @tc.desc: Verify the RemoveListener ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(PublisherItemTest, RemoveListener_002, TestSize.Level0) +{ + PublisherItem item(DHTopic::TOPIC_MIN); + sptr listener = new MockIPublisherListener(); + item.RemoveListener(listener); + EXPECT_EQ(true, item.listeners_.empty()); +} + +/** + * @tc.name: PublishMessage_001 + * @tc.desc: Verify the PublishMessage ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(PublisherItemTest, PublishMessage_001, TestSize.Level0) +{ + PublisherItem item(DHTopic::TOPIC_MIN); + std::string message; + item.PublishMessage(message); + EXPECT_EQ(true, item.listeners_.empty()); +} + +/** + * @tc.name: PublishMessage_002 + * @tc.desc: Verify the PublishMessage ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(PublisherItemTest, PublishMessage_002, TestSize.Level0) +{ + PublisherItem item(DHTopic::TOPIC_MIN); + std::string message; + uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024 + 10; + message.resize(MAX_MESSAGE_LEN); + item.PublishMessage(message); + EXPECT_EQ(true, item.listeners_.empty()); +} + +/** + * @tc.name: PublishMessage_003 + * @tc.desc: Verify the PublishMessage ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(PublisherItemTest, PublishMessage_003, TestSize.Level0) +{ + PublisherItem item(DHTopic::TOPIC_MIN); + std::string message = "message"; + sptr listener = new MockIPublisherListener(); + item.listeners_.insert(listener); + item.PublishMessage(message); + EXPECT_EQ(false, item.listeners_.empty()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/resourcemanager/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/resourcemanager/BUILD.gn index ecc7de1ae1e017aeb27ff8d82eb4f19093ff50a3..18d2e28067f1c65f25b37d41881ca67cd225c92b 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/resourcemanager/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/resourcemanager/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,8 +20,6 @@ module_out_path = "distributed_hardware_fwk/resource_manager_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//base/notification/eventhandler/interfaces/inner_api", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", "include", "${utils_path}/include", "${utils_path}/include/log", @@ -31,10 +29,7 @@ config("module_private_config") { "${services_path}/distributedhardwarefwkservice/include/utils", "${common_path}/utils/include", "${common_path}/log/include", - "//commonlibrary/c_utils/base/include", "//third_party/json/include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", ] } @@ -47,12 +42,17 @@ ohos_unittest("ResourceManagerTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", - "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", "//third_party/googletest:gtest_main", ] - external_deps = [ "c_utils:utils" ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] } group("resource_manager_test") { diff --git a/services/distributedhardwarefwkservice/test/unittest/common/resourcemanager/src/resource_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/resourcemanager/src/resource_manager_test.cpp index c37786b31762904316ecd17e61b008ec538c6a71..26488f956c7a20610c18a1ef92ba1fb7e02c8755 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/resourcemanager/src/resource_manager_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/resourcemanager/src/resource_manager_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,13 +20,15 @@ #include #include -#include "capability_info.h" #define private public +#include "capability_info.h" #include "capability_info_manager.h" +#include "version_info_event.h" #undef private #include "dh_context.h" #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" +#include "nlohmann/json.hpp" using namespace testing::ext; using namespace std; @@ -40,7 +42,7 @@ namespace { const string DATABASE_DIR = "/data/service/el1/public/database/dtbhardware_manager_service/"; const string DEV_ID_0 = "bb536a637105409e904d4da83790a4a7"; const string DEV_ID_1 = "bb536a637105409e904d4da83790a4a8"; -const string DEV_NAME = "Dev1"; +const string TEST_DEV_NAME = "Dev1"; const string DH_ID_0 = "Camera_0"; const string DH_ID_1 = "Mic_0"; const string DH_ID_2 = "Gps_0"; @@ -61,26 +63,26 @@ constexpr uint32_t TEST_SIZE_10 = 10; const std::string EMPTY_PREFIX = ""; const shared_ptr CAP_INFO_0 = - make_shared(DH_ID_0, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_0); + make_shared(DH_ID_0, DEV_ID_0, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_0); const shared_ptr CAP_INFO_1 = - make_shared(DH_ID_1, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::AUDIO, DH_ATTR_0); + make_shared(DH_ID_1, DEV_ID_0, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::AUDIO, DH_ATTR_0); const shared_ptr CAP_INFO_2 = - make_shared(DH_ID_2, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::GPS, DH_ATTR_0); + make_shared(DH_ID_2, DEV_ID_0, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::GPS, DH_ATTR_0); const shared_ptr CAP_INFO_3 = - make_shared(DH_ID_3, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::SCREEN, DH_ATTR_0); + make_shared(DH_ID_3, DEV_ID_0, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::SCREEN, DH_ATTR_0); const shared_ptr CAP_INFO_4 = - make_shared(DH_ID_4, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::INPUT, DH_ATTR_0); + make_shared(DH_ID_4, DEV_ID_0, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::INPUT, DH_ATTR_0); const shared_ptr CAP_INFO_5 = - make_shared(DH_ID_0, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_1); + make_shared(DH_ID_0, DEV_ID_1, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_1); const shared_ptr CAP_INFO_6 = - make_shared(DH_ID_1, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::AUDIO, DH_ATTR_1); + make_shared(DH_ID_1, DEV_ID_1, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::AUDIO, DH_ATTR_1); const shared_ptr CAP_INFO_7 = - make_shared(DH_ID_2, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::GPS, DH_ATTR_1); + make_shared(DH_ID_2, DEV_ID_1, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::GPS, DH_ATTR_1); const shared_ptr CAP_INFO_8 = - make_shared(DH_ID_3, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::SCREEN, DH_ATTR_1); + make_shared(DH_ID_3, DEV_ID_1, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::SCREEN, DH_ATTR_1); const shared_ptr CAP_INFO_9 = - make_shared(DH_ID_4, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::INPUT, DH_ATTR_1); + make_shared(DH_ID_4, DEV_ID_1, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::INPUT, DH_ATTR_1); } void ResourceManagerTest::SetUpTestCase(void) @@ -230,7 +232,7 @@ HWTEST_F(ResourceManagerTest, resource_manager_test_008, TestSize.Level0) { map queryMap0 { { CapabilityInfoFilter::FILTER_DEVICE_ID, DEV_ID_0 } }; map queryMap1 { { CapabilityInfoFilter::FILTER_DEVICE_ID, DEV_ID_1 } }; - map queryMap2 { { CapabilityInfoFilter::FILTER_DEVICE_NAME, DEV_NAME } }; + map queryMap2 { { CapabilityInfoFilter::FILTER_DEVICE_NAME, TEST_DEV_NAME } }; map queryMap3 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_0 } }; map queryMap4 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_1 } }; map queryMap5 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_2 } }; @@ -372,5 +374,483 @@ HWTEST_F(ResourceManagerTest, resource_manager_test_013, TestSize.Level0) DH_FWK_SUCCESS); EXPECT_EQ(capMap.size(), TEST_SIZE_10); } + +/** + * @tc.name: resource_manager_test_014 + * @tc.desc: Verify the RemoveCapabilityInfoInDB function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, resource_manager_test_014, TestSize.Level0) +{ + std::string deviceIdEmpty = ""; + int32_t ret = CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoInDB(deviceIdEmpty); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + +/** + * @tc.name: resource_manager_test_015 + * @tc.desc: Verify the GetCapabilityByValue function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, resource_manager_test_015, TestSize.Level0) +{ + std::string value = ""; + std::shared_ptr capPtr = nullptr; + int32_t ret = CapabilityUtils::GetCapabilityByValue(value, capPtr); + EXPECT_EQ(ERR_DH_FWK_JSON_PARSE_FAILED, ret); +} + +/** + * @tc.name: resource_manager_test_016 + * @tc.desc: Verify the GetCapabilityKey function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, resource_manager_test_016, TestSize.Level0) +{ + std::string deviceId = "deviceIdtest"; + std::string dhId = "dhIdtest"; + std::string str = CapabilityUtils::GetCapabilityKey(deviceId, dhId); + EXPECT_EQ("deviceIdtest###dhIdtest", str); +} + +/** + * @tc.name: resource_manager_test_017 + * @tc.desc: Verify the IsCapKeyMatchDeviceId function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, resource_manager_test_017, TestSize.Level0) +{ + std::string key = "keytest"; + bool ret = CapabilityUtils::IsCapKeyMatchDeviceId(key, DEV_ID_0); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: resource_manager_test_018 + * @tc.desc: Verify the IsCapKeyMatchDeviceId function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, resource_manager_test_018, TestSize.Level0) +{ + std::string key = "bb536a637105409e904d4da83790a4a7###keytest"; + bool ret = CapabilityUtils::IsCapKeyMatchDeviceId(key, DEV_ID_0); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: resource_manager_test_019 + * @tc.desc: Verify the FromJsonString function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, resource_manager_test_019, TestSize.Level0) +{ + CapabilityInfo capaInfo; + std::string jsonStr = ""; + int32_t ret = capaInfo.FromJsonString(jsonStr); + EXPECT_EQ(ERR_DH_FWK_JSON_PARSE_FAILED, ret); +} + +/** + * @tc.name: resource_manager_test_020 + * @tc.desc: Verify the Compare function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, resource_manager_test_020, TestSize.Level0) +{ + CapabilityInfo capaInfo(DH_ID_0, DEV_ID_0, TEST_DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_0); + bool ret = CAP_INFO_1->Compare(capaInfo); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: OnChange_001 + * @tc.desc: Verify the OnChange function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, OnChange_001, TestSize.Level0) +{ + DistributedKv::Entry insert, update, del; + insert.key = "strBase"; + update.key = "strBase"; + del.key = "strBase"; + insert.value = "strBase"; + update.value = "strBase"; + del.value = "strBase"; + std::vector inserts, updates, deleteds; + inserts.push_back(insert); + updates.push_back(update); + deleteds.push_back(del); + + DistributedKv::ChangeNotification changeIn(std::move(inserts), std::move(updates), std::move(deleteds), "", true); + + CapabilityInfoManager::GetInstance()->OnChange(changeIn); + EXPECT_NE(nullptr, CapabilityInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: OnEvent_001 + * @tc.desc: Verify the OnEvent function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, OnEvent_001, TestSize.Level0) +{ + EventSender sender; + CapabilityInfoEvent ev(sender); + CapabilityInfoManager::GetInstance()->OnEvent(ev); + EXPECT_NE(nullptr, CapabilityInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: OnEvent_002 + * @tc.desc: Verify the OnEvent function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, OnEvent_002, TestSize.Level0) +{ + EventSender sender; + CapabilityInfoEvent ev(sender); + ev.action_ = CapabilityInfoEvent::EventType::RECOVER; + CapabilityInfoManager::GetInstance()->OnEvent(ev); + EXPECT_NE(nullptr, CapabilityInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: HandleCapabilityAddChange_001 + * @tc.desc: Verify the HandleCapabilityAddChange function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, HandleCapabilityAddChange_001, TestSize.Level0) +{ + std::vector insertRecords; + DistributedKv::Entry entry; + entry.key = "strBase"; + entry.value = "strBase"; + insertRecords.push_back(entry); + CapabilityInfoManager::GetInstance()->HandleCapabilityAddChange(insertRecords); + EXPECT_NE(nullptr, CapabilityInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: HandleCapabilityUpdateChange_001 + * @tc.desc: Verify the HandleCapabilityUpdateChange function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, HandleCapabilityUpdateChange_001, TestSize.Level0) +{ + std::vector updateRecords; + DistributedKv::Entry entry; + entry.key = "strBase"; + entry.value = "strBase"; + updateRecords.push_back(entry); + CapabilityInfoManager::GetInstance()->HandleCapabilityUpdateChange(updateRecords); + EXPECT_NE(nullptr, CapabilityInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: IsCapabilityMatchFilter_001 + * @tc.desc: Verify the IsCapabilityMatchFilter function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, IsCapabilityMatchFilter_001, TestSize.Level0) +{ + std::shared_ptr cap = nullptr; + CapabilityInfoFilter filter = CapabilityInfoFilter::FILTER_DH_ID; + std::string value; + bool ret = CapabilityInfoManager::GetInstance()->IsCapabilityMatchFilter(cap, filter, value); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: IsCapabilityMatchFilter_002 + * @tc.desc: Verify the IsCapabilityMatchFilter function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, IsCapabilityMatchFilter_002, TestSize.Level0) +{ + std::shared_ptr cap = std::make_shared("", "", "", 0, DHType::UNKNOWN, ""); + CapabilityInfoFilter filter = CapabilityInfoFilter::FILTER_DH_ID; + std::string value; + bool ret = CapabilityInfoManager::GetInstance()->IsCapabilityMatchFilter(cap, filter, value); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: IsCapabilityMatchFilter_003 + * @tc.desc: Verify the IsCapabilityMatchFilter function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, IsCapabilityMatchFilter_003, TestSize.Level0) +{ + std::shared_ptr cap = std::make_shared("", "", "", 0, DHType::UNKNOWN, ""); + CapabilityInfoFilter filter = CapabilityInfoFilter::FILTER_DEVICE_ID; + std::string value; + bool ret = CapabilityInfoManager::GetInstance()->IsCapabilityMatchFilter(cap, filter, value); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: IsCapabilityMatchFilter_004 + * @tc.desc: Verify the IsCapabilityMatchFilter function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, IsCapabilityMatchFilter_004, TestSize.Level0) +{ + std::shared_ptr cap = std::make_shared("", "", "", 0, DHType::UNKNOWN, ""); + CapabilityInfoFilter filter = CapabilityInfoFilter::FILTER_DEVICE_NAME; + std::string value; + bool ret = CapabilityInfoManager::GetInstance()->IsCapabilityMatchFilter(cap, filter, value); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: IsCapabilityMatchFilter_005 + * @tc.desc: Verify the IsCapabilityMatchFilter function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, IsCapabilityMatchFilter_005, TestSize.Level0) +{ + std::shared_ptr cap = std::make_shared("", "", "", 0, DHType::UNKNOWN, ""); + CapabilityInfoFilter filter = CapabilityInfoFilter::FILTER_DEVICE_TYPE; + uint16_t devType = 123; + std::string value = std::to_string(devType); + bool ret = CapabilityInfoManager::GetInstance()->IsCapabilityMatchFilter(cap, filter, value); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: IsCapabilityMatchFilter_006 + * @tc.desc: Verify the IsCapabilityMatchFilter function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, IsCapabilityMatchFilter_006, TestSize.Level0) +{ + std::shared_ptr cap = std::make_shared("", "", "", 0, DHType::UNKNOWN, ""); + CapabilityInfoFilter filter = CapabilityInfoFilter::FILTER_DH_TYPE; + DHType dhType = DHType::AUDIO; + std::string value = std::to_string(static_cast(dhType)); + bool ret = CapabilityInfoManager::GetInstance()->IsCapabilityMatchFilter(cap, filter, value); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: IsCapabilityMatchFilter_007 + * @tc.desc: Verify the IsCapabilityMatchFilter function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, IsCapabilityMatchFilter_007, TestSize.Level0) +{ + std::shared_ptr cap = std::make_shared("", "", "", 0, DHType::UNKNOWN, ""); + CapabilityInfoFilter filter = CapabilityInfoFilter::FILTER_DH_ATTRS; + std::string value; + bool ret = CapabilityInfoManager::GetInstance()->IsCapabilityMatchFilter(cap, filter, value); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: IsCapabilityMatchFilter_008 + * @tc.desc: Verify the IsCapabilityMatchFilter function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, IsCapabilityMatchFilter_008, TestSize.Level0) +{ + std::shared_ptr cap = std::make_shared("", "", "", 0, DHType::UNKNOWN, ""); + uint32_t invalid = 6; + CapabilityInfoFilter filter = static_cast(invalid); + std::string value; + bool ret = CapabilityInfoManager::GetInstance()->IsCapabilityMatchFilter(cap, filter, value); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: GetCapabilitiesByDeviceId_001 + * @tc.desc: Verify the GetCapabilitiesByDeviceId function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, GetCapabilitiesByDeviceId_001, TestSize.Level0) +{ + std::string deviceId; + std::vector> resInfos; + CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(deviceId, resInfos); + EXPECT_NE(nullptr, CapabilityInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: HasCapability_001 + * @tc.desc: Verify the HasCapability function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(ResourceManagerTest, HasCapability_001, TestSize.Level0) +{ + std::string deviceId; + std::string dhId; + bool ret = CapabilityInfoManager::GetInstance()->HasCapability(deviceId, dhId); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: SyncRemoteCapabilityInfos_001 + * @tc.desc: Verify the CapabilityInfoManager SyncRemoteCapabilityInfos function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, SyncRemoteCapabilityInfos_001, TestSize.Level0) +{ + CapabilityInfoManager::GetInstance()->globalCapInfoMap_.clear(); + CapabilityInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = CapabilityInfoManager::GetInstance()->SyncRemoteCapabilityInfos(); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + +/** + * @tc.name: RemoveCapabilityInfoInDB_001 + * @tc.desc: Verify the RemoveCapabilityInfoInDB function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, RemoveCapabilityInfoInDB_001, TestSize.Level0) +{ + std::string deviceIdEmpty; + uint32_t MAX_ID_LEN = 257; + deviceIdEmpty.resize(MAX_ID_LEN); + int32_t ret = CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoInDB(deviceIdEmpty); + EXPECT_EQ(ERR_DH_FWK_PARA_INVALID, ret); +} + +/** + * @tc.name: RemoveCapabilityInfoInDB_002 + * @tc.desc: Verify the RemoveCapabilityInfoInDB function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, RemoveCapabilityInfoInDB_002, TestSize.Level0) +{ + std::string deviceIdEmpty = "deviceIdEmpty"; + CapabilityInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoInDB(deviceIdEmpty); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + +/** + * @tc.name: HandleCapabilityDeleteChange_001 + * @tc.desc: Verify the HandleCapabilityDeleteChange function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, HandleCapabilityDeleteChange_001, TestSize.Level0) +{ + std::vector deleteRecords; + DistributedKv::Entry entry; + entry.key = "strBase"; + entry.value = "strBase"; + deleteRecords.push_back(entry); + CapabilityInfoManager::GetInstance()->HandleCapabilityDeleteChange(deleteRecords); + EXPECT_EQ(nullptr, CapabilityInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: GetDataByKey_001 + * @tc.desc: Verify the GetDataByKey function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, GetDataByKey_001, TestSize.Level0) +{ + std::string key; + std::shared_ptr capInfoPtr; + CapabilityInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = CapabilityInfoManager::GetInstance()->GetDataByKey(key, capInfoPtr); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + +/** + * @tc.name: GetDataByKeyPrefix_001 + * @tc.desc: Verify the GetDataByKeyPrefix function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, GetDataByKeyPrefix_001, TestSize.Level0) +{ + std::string keyPrefix; + CapabilityInfoMap capabilityMap; + CapabilityInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = CapabilityInfoManager::GetInstance()->GetDataByKeyPrefix(keyPrefix, capabilityMap); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + +/** + * @tc.name: DumpCapabilityInfos_001 + * @tc.desc: Verify the DumpCapabilityInfos function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, DumpCapabilityInfos_001, TestSize.Level0) +{ + std::vector capInfos; + std::string dhId; + std::string devId; + std::string devName; + uint16_t devType = 0; + DHType dhType = DHType::GPS; + std::string dhAttrs; + CapabilityInfo info(dhId, devId, devName, devType, dhType, dhAttrs); + capInfos.push_back(info); + CapabilityInfoManager::GetInstance()->DumpCapabilityInfos(capInfos); + EXPECT_EQ(nullptr, CapabilityInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: FromJson_001 + * @tc.desc: Verify the FromJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(ResourceManagerTest, FromJson_001, TestSize.Level0) +{ + std::string dhId; + std::string devId; + std::string devName; + uint16_t devType = 0; + DHType dhType = DHType::GPS; + std::string dhAttrs; + CapabilityInfo info(dhId, devId, devName, devType, dhType, dhAttrs); + nlohmann::json jsonObject; + const std::string DH_ID = "dh_id"; + const std::string DEV_ID = "dev_id"; + const std::string DEV_NAME = "dev_name"; + const std::string DEV_TYPE = "dev_type"; + const std::string DH_TYPE = "dh_type"; + const std::string DH_ATTRS = "dh_attrs"; + jsonObject[DH_ID] = "dh_id"; + jsonObject[DEV_ID] = "dev_id"; + jsonObject[DEV_NAME] = "dev_name"; + jsonObject[DEV_TYPE] = "dev_type"; + jsonObject[DH_TYPE] = "dh_type"; + jsonObject[DH_ATTRS] = "dh_attrs"; + CapabilityInfo capability; + std::string jsonStr = jsonObject.dump(); + EXPECT_EQ(DH_FWK_SUCCESS, info.FromJsonString(jsonStr)); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/task/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/task/BUILD.gn index c837f278eedbcbd3dc21ccd08a3f5d5fd039d4fe..cbb8b49fea44eea0172cfd37275b59610e82dd30 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/task/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/task/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -29,7 +29,6 @@ config("module_private_config") { "${services_path}/distributedhardwarefwkservice/include/utils", "${common_path}/utils/include", "${common_path}/log/include", - "//commonlibrary/c_utils/base/include", ] } @@ -49,11 +48,13 @@ ohos_unittest("DHTaskTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", - "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", "//third_party/googletest:gtest_main", ] + external_deps = [ "c_utils:utils" ] + defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"TaskTest\"", diff --git a/services/distributedhardwarefwkservice/test/unittest/common/task/include/task_test.h b/services/distributedhardwarefwkservice/test/unittest/common/task/include/task_test.h index 45edd92aa406f9973eafcc241a33ca3c7d6b48e1..8f5f6987d8d604f6344bfc86e1bf96312a58545f 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/task/include/task_test.h +++ b/services/distributedhardwarefwkservice/test/unittest/common/task/include/task_test.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,15 @@ #include +#define private public +#include "disable_task.h" +#include "enable_task.h" +#include "offline_task.h" +#include "task.h" +#include "task_board.h" +#include "task_executor.h" +#undef private + namespace OHOS { namespace DistributedHardware { class TaskTest : public testing::Test { diff --git a/services/distributedhardwarefwkservice/test/unittest/common/task/src/mock_offline_task.cpp b/services/distributedhardwarefwkservice/test/unittest/common/task/src/mock_offline_task.cpp index ad52c38f6d30f89ccad9ce57ab23a108c9193c94..b30914ec919ade2f9c0a84ed6a00f73a62e6613a 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/task/src/mock_offline_task.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/task/src/mock_offline_task.cpp @@ -30,7 +30,7 @@ MockOffLineTask::MockOffLineTask(const std::string &networkId, const std::string void MockOffLineTask::CreateDisableTask() { - for (auto &devInfo : offLineDevInfos) { + for (const auto &devInfo : offLineDevInfos) { TaskParam taskParam = { .networkId = devInfo.networkId, .uuid = devInfo.uuid, diff --git a/services/distributedhardwarefwkservice/test/unittest/common/task/src/task_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/task/src/task_test.cpp index 4e648fd86ee821e72f1edc8f34cc41780e24a611..56359d38e0eaa29a9c61f90f2402d1061fe4988a 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/task/src/task_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/task/src/task_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,6 +20,7 @@ #include "dh_utils_tool.h" #include "distributed_hardware_errno.h" +#include "task_factory.h" #include "mock_disable_task.h" #include "mock_enable_task.h" #include "mock_offline_task.h" @@ -27,9 +28,6 @@ #include "mock_task_factory.h" #include "mock_task_utils.h" -#include "task_board.h" -#include "task_executor.h" - using namespace testing::ext; namespace OHOS { @@ -168,5 +166,242 @@ HWTEST_F(TaskTest, task_test_004, TestSize.Level0) ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish()); ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish()); } + +/** + * @tc.name: task_test_005 + * @tc.desc: Verify the PushTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(TaskTest, task_test_005, TestSize.Level0) +{ + std::shared_ptr task = nullptr; + TaskExecutor::GetInstance().PushTask(task); + ASSERT_EQ(true, TaskExecutor::GetInstance().taskQueue_.empty()); +} + +/** + * @tc.name: task_test_006 + * @tc.desc: Verify the CreateTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(TaskTest, task_test_006, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::ON_LINE, taskParam, nullptr); + ASSERT_NE(nullptr, task); +} + +/** + * @tc.name: task_test_007 + * @tc.desc: Verify the CreateTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(TaskTest, task_test_007, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::DISABLE, taskParam, nullptr); + ASSERT_NE(nullptr, task); +} + +/** + * @tc.name: task_test_008 + * @tc.desc: Verify the CreateTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(TaskTest, task_test_008, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::ON_LINE, taskParam, nullptr); + ASSERT_NE(nullptr, task); +} + +/** + * @tc.name: task_test_009 + * @tc.desc: Verify the CreateTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(TaskTest, task_test_009, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::OFF_LINE, taskParam, nullptr); + ASSERT_NE(nullptr, task); +} + +/** + * @tc.name: task_test_010 + * @tc.desc: Verify the CreateTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(TaskTest, task_test_010, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::UNKNOWN, taskParam, nullptr); + ASSERT_EQ(nullptr, task); +} + +/** + * @tc.name: task_test_011 + * @tc.desc: Verify the RemoveTaskInner function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_011, TestSize.Level0) +{ + std::string taskId; + TaskBoard::GetInstance().tasks_.clear(); + TaskBoard::GetInstance().RemoveTaskInner(taskId); + ASSERT_TRUE(TaskBoard::GetInstance().enabledDevices_.empty()); +} + +/** + * @tc.name: task_test_012 + * @tc.desc: Verify the DumpAllTasks function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_012, TestSize.Level0) +{ + std::vector taskInfos; + std::shared_ptr childrenTask = std::make_shared("networkId", "uuid", "dhId", DHType::AUDIO); + TaskBoard::GetInstance().tasks_.insert(std::make_pair("", childrenTask)); + TaskBoard::GetInstance().DumpAllTasks(taskInfos); + ASSERT_TRUE(TaskBoard::GetInstance().enabledDevices_.empty()); +} + +/** + * @tc.name: task_test_013 + * @tc.desc: Verify the SaveEnabledDevice function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_013, TestSize.Level0) +{ + std::string enabledDeviceKey; + TaskParam taskParam; + TaskBoard::GetInstance().SaveEnabledDevice(enabledDeviceKey, taskParam); + ASSERT_EQ(false, TaskBoard::GetInstance().enabledDevices_.empty()); +} + +/** + * @tc.name: task_test_014 + * @tc.desc: Verify the RemoveEnabledDevice function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_014, TestSize.Level0) +{ + std::string enabledDeviceKey; + TaskBoard::GetInstance().RemoveEnabledDevice(enabledDeviceKey); + ASSERT_TRUE(TaskBoard::GetInstance().enabledDevices_.empty()); +} + +/** + * @tc.name: task_test_015 + * @tc.desc: Verify the GetEnabledDevice function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_015, TestSize.Level0) +{ + TaskBoard::GetInstance().enabledDevices_.clear(); + auto ret = TaskBoard::GetInstance().GetEnabledDevice(); + ASSERT_TRUE(ret.empty()); +} + +/** + * @tc.name: task_test_016 + * @tc.desc: Verify the DoTask function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_016, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::DISABLE, taskParam, nullptr); + task->DoTask(); + ASSERT_TRUE(task->childrenTasks_.empty()); +} + +/** + * @tc.name: task_test_017 + * @tc.desc: Verify the DoTask function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_017, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::ENABLE, taskParam, nullptr); + task->DoTask(); + ASSERT_TRUE(task->childrenTasks_.empty()); +} + +/** + * @tc.name: task_test_018 + * @tc.desc: Verify the CreateDisableTask function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_018, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::OFF_LINE, taskParam, nullptr); + std::vector taskSteps; + taskSteps.push_back(TaskStep::UNREGISTER_OFFLINE_DISTRIBUTED_HARDWARE); + task->SetTaskSteps(taskSteps); + task->DoTask(); + ASSERT_TRUE(task->childrenTasks_.empty()); +} + +/** + * @tc.name: task_test_019 + * @tc.desc: Verify the ClearOffLineInfo function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_019, TestSize.Level0) +{ + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::OFF_LINE, taskParam, nullptr); + std::vector taskSteps; + taskSteps.push_back(TaskStep::CLEAR_OFFLINE_INFO); + task->SetTaskSteps(taskSteps); + task->DoTask(); + ASSERT_TRUE(task->childrenTasks_.empty()); +} + +/** + * @tc.name: task_test_020 + * @tc.desc: Verify the AddChildrenTask function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_020, TestSize.Level0) +{ + std::shared_ptr childrenTask = std::make_shared("networkId", "uuid", "dhId", DHType::AUDIO); + TaskParam taskParam; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::OFF_LINE, taskParam, nullptr); + task->AddChildrenTask(childrenTask); + ASSERT_TRUE(task->childrenTasks_.empty()); +} + +/** + * @tc.name: task_test_021 + * @tc.desc: Verify the TriggerTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(TaskTest, task_test_021, TestSize.Level0) +{ + TaskExecutor::GetInstance().taskThreadFlag_ = false; + TaskExecutor::GetInstance().TriggerTask(); + ASSERT_EQ(true, TaskExecutor::GetInstance().taskQueue_.empty()); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e4b51703302b2e8411bbe7d2b6046a9721504cb9 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/version_info_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${utils_path}/include", + "${utils_path}/include/log", + "${utils_path}/include/eventbus", + "${services_path}/distributedhardwarefwkservice/include", + "${services_path}/distributedhardwarefwkservice/include/resourcemanager", + "${services_path}/distributedhardwarefwkservice/include/utils", + "${services_path}/distributedhardwarefwkservice/include/versionmanager", + "${common_path}/utils/include", + "${common_path}/log/include", + "//third_party/json/include", + ] +} + +ohos_unittest("VersionInfoTest") { + module_out_path = module_out_path + + sources = [ "src/version_info_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] +} + +group("version_info_test") { + testonly = true + deps = [ ":VersionInfoTest" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/include/version_info_test.h b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/include/version_info_test.h similarity index 88% rename from services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/include/version_info_test.h rename to services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/include/version_info_test.h index 3e49b244555f9e198a282c98f999cd87b92af30d..5d08f4bfae6c1dc84b385806dd95f3c6d3f5c6c7 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/include/version_info_test.h +++ b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/include/version_info_test.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_HARDWARE_VERSION_INFO_MANAGER_TEST_H -#define OHOS_DISTRIBUTED_HARDWARE_VERSION_INFO_MANAGER_TEST_H +#ifndef OHOS_DISTRIBUTED_HARDWARE_VERSION_INFO_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_VERSION_INFO_TEST_H #include #include diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/src/version_info_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/src/version_info_test.cpp similarity index 57% rename from services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/src/version_info_test.cpp rename to services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/src/version_info_test.cpp index 2c73db990d46c3da56a06d62c0d105e77e99d233..34db268b17e617704602e57a6b7badc11b5c606f 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/src/version_info_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfo/src/version_info_test.cpp @@ -86,5 +86,59 @@ HWTEST_F(VersionInfoTest, version_info_test_001, TestSize.Level0) EXPECT_EQ(verInfo2.ToJsonString(), jsonStr); } + +/** + * @tc.name: FromJson_001 + * @tc.desc: Verify the FromJson ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(VersionInfoTest, FromJson_001, TestSize.Level0) +{ + VersionInfo verInfo; + const std::string DH_ID = "dh_id"; + const std::string DEV_ID = "dev_id"; + const std::string DEV_NAME = "dev_name"; + const std::string DEV_TYPE = "dev_type"; + const std::string DH_TYPE = "dh_type"; + const std::string DH_ATTRS = "dh_attrs"; + nlohmann::json jsonObject; + jsonObject[DH_ID] = "dh_id"; + jsonObject[DEV_ID] = "dev_id"; + jsonObject[DEV_NAME] = "dev_name"; + jsonObject[DEV_TYPE] = "dev_type"; + jsonObject[DH_TYPE] = "dh_type"; + jsonObject[DH_ATTRS] = "dh_attrs"; + CompVersion compVer; + std::string jsonStr = jsonObject.dump(); + EXPECT_EQ(DH_FWK_SUCCESS, verInfo.FromJsonString(jsonStr)); +} + +/** + * @tc.name: FromJson_002 + * @tc.desc: Verify the FromJson ToJson function. + * @tc.type: FUNC + * @tc.require: AR000GHSCV + */ +HWTEST_F(VersionInfoTest, FromJson_002, TestSize.Level0) +{ + VersionInfo verInfo; + const std::string DH_ID = "dh_id"; + const std::string DEV_ID = "dev_id"; + const std::string DEV_NAME = "dev_name"; + const std::string DEV_TYPE = "dev_type"; + const std::string DH_TYPE = "dh_type"; + const std::string DH_ATTRS = "dh_attrs"; + nlohmann::json jsonObject; + jsonObject[DH_ID] = "dh_id"; + jsonObject[DEV_ID] = "dev_id"; + jsonObject[DEV_NAME] = "dev_name"; + jsonObject[DEV_TYPE] = "dev_type"; + jsonObject[DH_TYPE] = "dh_type"; + jsonObject[DH_ATTRS] = "dh_attrs"; + VersionInfo versionInfo; + std::string jsonStr = jsonObject.dump(); + EXPECT_EQ(DH_FWK_SUCCESS, verInfo.FromJsonString(jsonStr)); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/BUILD.gn similarity index 72% rename from services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/BUILD.gn rename to services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/BUILD.gn index c2562bac7cb81cacdabbfd82e9779d018a61ed35..38a9c45ddb66316900742bd285cc6018ec219fe4 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -30,11 +30,7 @@ config("module_private_config") { "${services_path}/distributedhardwarefwkservice/include/versionmanager", "${common_path}/utils/include", "${common_path}/log/include", - "//base/notification/eventhandler/interfaces/inner_api", - "//commonlibrary/c_utils/base/include", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", "//third_party/json/include", - "//utils/system/safwk/native/include", ] } @@ -42,20 +38,22 @@ config("module_private_config") { ohos_unittest("VersioninfoManagerTest") { module_out_path = module_out_path - sources = [ - "src/version_info_manager_test.cpp", - "src/version_info_test.cpp", - ] + sources = [ "src/version_info_manager_test.cpp" ] configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", - "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", "//third_party/googletest:gtest_main", ] - external_deps = [ "c_utils:utils" ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "kv_store:distributeddata_inner", + "safwk:system_ability_fwk", + ] } group("versioninfo_manager_test") { diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/include/version_info_manager_test.h b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/include/version_info_manager_test.h new file mode 100644 index 0000000000000000000000000000000000000000..511d5dca6b5f39f8ee068dcabb24c284b0e5cc5e --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/include/version_info_manager_test.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_VERSION_INFO_MANAGER_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_VERSION_INFO_MANAGER_TEST_H + +#include +#include + +#include "db_adapter.h" +#include "distributed_hardware_errno.h" +#include "version_info.h" + +namespace OHOS { +namespace DistributedHardware { +class VersionInfoManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +class MockDBAdapter : public DBAdapter { +public: +MockDBAdapter(const std::string &appId, const std::string &storeId, + const std::shared_ptr &changeListener) + : DBAdapter(appId, storeId, changeListener) {} + +int32_t RemoveCapabilityInfoByKey(const std::string &key) +{ + (void)key; + return DH_FWK_SUCCESS; +} + +int32_t GetDataByKey(const std::string &key, std::string &data) +{ + (void)key; + (void)data; + return DH_FWK_SUCCESS; +} + +int32_t RemoveDataByKey(const std::string &key) +{ + (void)key; + return DH_FWK_SUCCESS; +} + +int32_t GetDataByKeyPrefix(const std::string &keyPrefix, std::vector &values) +{ + (void)keyPrefix; + (void)values; + return DH_FWK_SUCCESS; +} + +int32_t ManualSync(const std::string &networkId) +{ + (void)networkId; + return DH_FWK_SUCCESS; +} +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/src/version_info_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/src/version_info_manager_test.cpp similarity index 37% rename from services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/src/version_info_manager_test.cpp rename to services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/src/version_info_manager_test.cpp index c9716e056c5e32c041e1bd3a39de265c1915f1b0..d80a1a955d5a7e847cec765cb060fe6ec9f82568 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/src/version_info_manager_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/versioninfomanager/versioninfomanager/src/version_info_manager_test.cpp @@ -22,9 +22,9 @@ #define private public #include "version_info_manager.h" #include "version_manager.h" +#include "version_info_event.h" #undef private #include "dh_context.h" -#include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" using namespace testing::ext; @@ -138,22 +138,11 @@ HWTEST_F(VersionInfoManagerTest, version_info_manager_test_001, TestSize.Level0) /** * @tc.name:version_info_manager_test_002 - * @tc.desc: Verify the VersionInfoManager SyncRemoteVersionInfos function. - * @tc.type: FUNC - * @tc.require: AR000GHSJE - */ -HWTEST_F(VersionInfoManagerTest, version_info_manager_test_002, TestSize.Level0) -{ - EXPECT_EQ(VersionInfoManager::GetInstance()->SyncRemoteVersionInfos(), DH_FWK_SUCCESS); -} - -/** - * @tc.name:version_info_manager_test_003 * @tc.desc: Verify the VersionInfoManager AddVersion function. * @tc.type: FUNC * @tc.require: AR000GHSCV */ -HWTEST_F(VersionInfoManagerTest, version_info_manager_test_004, TestSize.Level0) +HWTEST_F(VersionInfoManagerTest, version_info_manager_test_002, TestSize.Level0) { for (const auto& verInfo : g_versionInfos) { EXPECT_EQ(VersionInfoManager::GetInstance()->AddVersion(verInfo), DH_FWK_SUCCESS); @@ -161,12 +150,12 @@ HWTEST_F(VersionInfoManagerTest, version_info_manager_test_004, TestSize.Level0) } /** - * @tc.name:version_info_manager_test_005 + * @tc.name:version_info_manager_test_003 * @tc.desc: Verify the VersionInfoManager GetVersionInfoByDeviceId function. * @tc.type: FUNC * @tc.require: AR000GHSJE */ -HWTEST_F(VersionInfoManagerTest, version_info_manager_test_005, TestSize.Level0) +HWTEST_F(VersionInfoManagerTest, version_info_manager_test_003, TestSize.Level0) { VersionInfo versionInfo; for (const auto& verInfo : g_versionInfos) { @@ -176,25 +165,324 @@ HWTEST_F(VersionInfoManagerTest, version_info_manager_test_005, TestSize.Level0) } /** - * @tc.name:version_info_manager_test_006 + * @tc.name:version_info_manager_test_004 * @tc.desc: Verify the VersionInfoManager SyncVersionInfoFromDB function. * @tc.type: FUNC * @tc.require: AR000GHSJE */ -HWTEST_F(VersionInfoManagerTest, version_info_manager_test_006, TestSize.Level0) +HWTEST_F(VersionInfoManagerTest, version_info_manager_test_004, TestSize.Level0) { EXPECT_EQ(VersionInfoManager::GetInstance()->SyncVersionInfoFromDB(DEV_ID_1), DH_FWK_SUCCESS); } /** - * @tc.name:version_info_manager_test_007 + * @tc.name:version_info_manager_test_005 * @tc.desc: Verify the VersionInfoManager UnInit function. * @tc.type: FUNC * @tc.require: AR000GHSJE */ -HWTEST_F(VersionInfoManagerTest, version_info_manager_test_007, TestSize.Level0) +HWTEST_F(VersionInfoManagerTest, version_info_manager_test_005, TestSize.Level0) { EXPECT_EQ(VersionInfoManager::GetInstance()->UnInit(), DH_FWK_SUCCESS); } + +/** + * @tc.name: UpdateVersionCache_001 + * @tc.desc: Verify the UpdateVersionCache function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, UpdateVersionCache_001, TestSize.Level0) +{ + VersionInfo versionInfo; + versionInfo.deviceId = "deviceId"; + versionInfo.dhVersion = "dhVersion"; + VersionInfoManager::GetInstance()->UpdateVersionCache(versionInfo); + EXPECT_EQ(DH_FWK_SUCCESS, VersionInfoManager::GetInstance()->Init()); +} + +/** + * @tc.name: UpdateVersionCache_002 + * @tc.desc: Verify the UpdateVersionCache function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, UpdateVersionCache_002, TestSize.Level0) +{ + VersionInfo versionInfo; + VersionInfoManager::GetInstance()->UpdateVersionCache(versionInfo); + EXPECT_EQ(DH_FWK_SUCCESS, VersionInfoManager::GetInstance()->Init()); +} + +/** + * @tc.name: RemoveVersionInfoByDeviceId_001 + * @tc.desc: Verify the RemoveVersionInfoByDeviceId function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, RemoveVersionInfoByDeviceId_001, TestSize.Level0) +{ + std::string deviceId; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = VersionInfoManager::GetInstance()->RemoveVersionInfoByDeviceId(deviceId); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + +/** + * @tc.name: RemoveVersionInfoByDeviceId_002 + * @tc.desc: Verify the RemoveVersionInfoByDeviceId function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, RemoveVersionInfoByDeviceId_002, TestSize.Level0) +{ + std::string deviceId = "deviceId"; + std::string appId; + std::string storeId; + std::shared_ptr changeListener = nullptr; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = std::make_shared(appId, storeId, changeListener); + int32_t ret = VersionInfoManager::GetInstance()->RemoveVersionInfoByDeviceId(deviceId); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL, ret); +} + +/** + * @tc.name: SyncVersionInfoFromDB_001 + * @tc.desc: Verify the SyncVersionInfoFromDB function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, SyncVersionInfoFromDB_001, TestSize.Level0) +{ + std::string deviceId; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = VersionInfoManager::GetInstance()->SyncVersionInfoFromDB(deviceId); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + +/** + * @tc.name: SyncVersionInfoFromDB_002 + * @tc.desc: Verify the SyncVersionInfoFromDB function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, SyncVersionInfoFromDB_002, TestSize.Level0) +{ + std::string deviceId = "deviceId"; + std::string appId; + std::string storeId; + std::shared_ptr changeListener = nullptr; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = std::make_shared(appId, storeId, changeListener); + int32_t ret = VersionInfoManager::GetInstance()->SyncVersionInfoFromDB(deviceId); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL, ret); +} + +/** + * @tc.name: SyncVersionInfoFromDB_003 + * @tc.desc: Verify the SyncVersionInfoFromDB function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, SyncVersionInfoFromDB_003, TestSize.Level0) +{ + std::string deviceId = "device"; + int32_t ret = VersionInfoManager::GetInstance()->SyncVersionInfoFromDB(deviceId); + EXPECT_NE(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: SyncRemoteVersionInfos_001 + * @tc.desc: Verify the SyncRemoteVersionInfos function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, SyncRemoteVersionInfos_001, TestSize.Level0) +{ + VersionInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = VersionInfoManager::GetInstance()->SyncRemoteVersionInfos(); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + +/** + * @tc.name: SyncRemoteVersionInfos_002 + * @tc.desc: Verify the SyncRemoteVersionInfos function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, SyncRemoteVersionInfos_002, TestSize.Level0) +{ + std::string appId; + std::string storeId; + std::shared_ptr changeListener = nullptr; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = std::make_shared(appId, storeId, changeListener); + int32_t ret = VersionInfoManager::GetInstance()->SyncRemoteVersionInfos(); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL, ret); +} + +/** + * @tc.name: CreateManualSyncCount_001 + * @tc.desc: Verify the CreateManualSyncCount function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, CreateManualSyncCount_001, TestSize.Level0) +{ + std::string deviceId; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + VersionInfoManager::GetInstance()->CreateManualSyncCount(deviceId); + EXPECT_EQ(nullptr, VersionInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: RemoveManualSyncCount_001 + * @tc.desc: Verify the RemoveManualSyncCount function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, RemoveManualSyncCount_001, TestSize.Level0) +{ + std::string deviceId; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + VersionInfoManager::GetInstance()->RemoveManualSyncCount(deviceId); + EXPECT_EQ(nullptr, VersionInfoManager::GetInstance()->dbAdapterPtr_); +} + +/** + * @tc.name: ManualSync_001 + * @tc.desc: Verify the ManualSync function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, ManualSync_001, TestSize.Level0) +{ + std::string deviceId; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = VersionInfoManager::GetInstance()->ManualSync(deviceId); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + +/** + * @tc.name: ManualSync_002 + * @tc.desc: Verify the ManualSync function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, ManualSync_002, TestSize.Level0) +{ + std::string appId; + std::string storeId; + std::shared_ptr changeListener = nullptr; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = std::make_shared(appId, storeId, changeListener); + std::string deviceId; + int32_t ret = VersionInfoManager::GetInstance()->ManualSync(deviceId); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL, ret); +} + +/** + * @tc.name: OnChange_001 + * @tc.desc: Verify the OnChange function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, OnChange_001, TestSize.Level0) +{ + DistributedKv::Entry insert, update, del; + insert.key = "strBase"; + update.key = "strBase"; + del.key = "strBase"; + insert.value = "strBase"; + update.value = "strBase"; + del.value = "strBase"; + std::vector inserts, updates, deleteds; + inserts.push_back(insert); + updates.push_back(update); + deleteds.push_back(del); + + DistributedKv::ChangeNotification changeIn(std::move(inserts), std::move(updates), std::move(deleteds), "", true); + + VersionInfoManager::GetInstance()->OnChange(changeIn); + EXPECT_EQ(DH_FWK_SUCCESS, VersionInfoManager::GetInstance()->Init()); +} + +/** + * @tc.name: HandleVersionAddChange_001 + * @tc.desc: Verify the HandleVersionAddChange function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, HandleVersionAddChange_001, TestSize.Level0) +{ + std::vector insertRecords; + DistributedKv::Entry entry; + entry.key = "strBase"; + entry.value = "strBase"; + insertRecords.push_back(entry); + VersionInfoManager::GetInstance()->HandleVersionAddChange(insertRecords); + EXPECT_EQ(DH_FWK_SUCCESS, VersionInfoManager::GetInstance()->Init()); +} + +/** + * @tc.name: HandleVersionUpdateChange_001 + * @tc.desc: Verify the HandleVersionUpdateChange function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, HandleVersionUpdateChange_001, TestSize.Level0) +{ + std::vector updateRecords; + DistributedKv::Entry entry; + entry.key = "strBase"; + entry.value = "strBase"; + updateRecords.push_back(entry); + VersionInfoManager::GetInstance()->HandleVersionUpdateChange(updateRecords); + EXPECT_EQ(DH_FWK_SUCCESS, VersionInfoManager::GetInstance()->Init()); +} + +/** + * @tc.name: HandleVersionDeleteChange_001 + * @tc.desc: Verify the HandleVersionDeleteChange function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, HandleVersionDeleteChange_001, TestSize.Level0) +{ + std::vector deleteRecords; + DistributedKv::Entry entry; + entry.key = "strBase"; + entry.value = "strBase"; + deleteRecords.push_back(entry); + VersionInfoManager::GetInstance()->HandleVersionDeleteChange(deleteRecords); + EXPECT_EQ(DH_FWK_SUCCESS, VersionInfoManager::GetInstance()->Init()); +} + +/** + * @tc.name: VersionInfoEvent_001 + * @tc.desc: Verify the VersionInfoEvent function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(VersionInfoManagerTest, VersionInfoEvent_001, TestSize.Level0) +{ + EventSender sender; + VersionInfoEvent ev(sender); + ev.action_ = VersionInfoEvent::EventType::RECOVER; + VersionInfoManager::GetInstance()->OnEvent(ev); + EXPECT_EQ(DH_FWK_SUCCESS, VersionInfoManager::GetInstance()->Init()); +} + +/** + * @tc.name: GetVersionInfoByDeviceId_001 + * @tc.desc: Verify the VersionInfoManager GetVersionInfoByDeviceId function. + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(VersionInfoManagerTest, GetVersionInfoByDeviceId_001, TestSize.Level0) +{ + std::string deviceId; + VersionInfo versionInfo; + VersionInfoManager::GetInstance()->dbAdapterPtr_ = nullptr; + int32_t ret = VersionInfoManager::GetInstance()->GetVersionInfoByDeviceId(deviceId, versionInfo); + EXPECT_EQ(ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL, ret); +} + } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versionmanager/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/versionmanager/BUILD.gn index d55ea1270fdb4bcc8afbd14b6b17b56c0b05f38d..e0984cb04578f1ddea6026ffe1fb38daec4be4d8 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/versionmanager/BUILD.gn +++ b/services/distributedhardwarefwkservice/test/unittest/common/versionmanager/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,8 +20,6 @@ module_out_path = "distributed_hardware_fwk/version_manager_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//base/notification/eventhandler/interfaces/inner_api", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", "include", "${utils_path}/include", "${utils_path}/include/eventbus", @@ -34,7 +32,6 @@ config("module_private_config") { "${common_path}/utils/include", "${common_path}/log/include", "//third_party/json/include", - "//commonlibrary/c_utils/base/include", ] } @@ -46,10 +43,16 @@ ohos_unittest("VersionManagerTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", "//third_party/googletest:gtest_main", ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "kv_store:distributeddata_inner", + ] + defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"VersionManagerTest\"", diff --git a/services/distributedhardwarefwkservice/test/unittest/common/versionmanager/src/version_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/versionmanager/src/version_manager_test.cpp index 4193cc1bd7bf96163bee2b6848965430fbcff0a1..6c34d0134bbe02a006760a3144c8a14250c924e9 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/versionmanager/src/version_manager_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/versionmanager/src/version_manager_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,7 +15,9 @@ #include "version_manager_test.h" +#define private public #include "component_loader.h" +#undef private #include "version_manager.h" using namespace testing::ext; @@ -154,5 +156,60 @@ HWTEST_F(VersionManagerTest, version_manager_test_005, TestSize.Level0) ret = VersionManager::GetInstance().RemoveDHVersion(TEST_DEVICE_ID_1); EXPECT_EQ(DH_FWK_SUCCESS, ret); } + +/** + * @tc.name: version_manager_test_006 + * @tc.desc: Verify GetCompVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(VersionManagerTest, version_manager_test_006, TestSize.Level0) +{ + DHVersion dhVersion; + CompVersion cVs1; + CompVersionGetValue(cVs1, TEST_COMPONENT_NAME_1, DHType::CAMERA, TEST_HANDLER_VERSION_1, TEST_SOURCE_VERSION_1, + TEST_SINK_VERSION_1); + dhVersion.uuid = TEST_DEVICE_ID_1; + dhVersion.dhVersion = TEST_DH_VERSION; + dhVersion.compVersions.insert(std::make_pair(cVs1.dhType, cVs1)); + int32_t ret = VersionManager::GetInstance().AddDHVersion(dhVersion.uuid, dhVersion); + EXPECT_EQ(DH_FWK_SUCCESS, ret); + ret = VersionManager::GetInstance().GetCompVersion(TEST_DEVICE_ID_1, DHType::CAMERA, cVs1); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: version_manager_test_007 + * @tc.desc: Verify GetCompVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(VersionManagerTest, version_manager_test_007, TestSize.Level0) +{ + DHVersion dhVersion; + CompVersion cVs1; + CompVersionGetValue(cVs1, TEST_COMPONENT_NAME_1, DHType::CAMERA, TEST_HANDLER_VERSION_1, TEST_SOURCE_VERSION_1, + TEST_SINK_VERSION_1); + dhVersion.uuid = TEST_DEVICE_ID_1; + dhVersion.dhVersion = TEST_DH_VERSION; + dhVersion.compVersions.insert(std::make_pair(cVs1.dhType, cVs1)); + int32_t ret = VersionManager::GetInstance().AddDHVersion(dhVersion.uuid, dhVersion); + EXPECT_EQ(DH_FWK_SUCCESS, ret); + ret = VersionManager::GetInstance().GetCompVersion(TEST_DEVICE_ID_1, DHType::AUDIO, cVs1); + EXPECT_EQ(ERR_DH_FWK_TYPE_NOT_EXIST, ret); +} + +/** + * @tc.name: version_manager_test_008 + * @tc.desc: Verify the Init function. + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(VersionManagerTest, version_manager_test_008, TestSize.Level0) +{ + ComponentLoader::GetInstance().isLocalVersionInit_.store(false); + int32_t ret = VersionManager::GetInstance().Init(); + EXPECT_EQ(ERR_DH_FWK_LOADER_GET_LOCAL_VERSION_FAIL, ret); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 789d4a8047e5a6e1d64544c62fbd2e74fe0b462a..36e94dd938585e9daf2a05b808422cf07e219d75 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -17,11 +17,7 @@ import( ohos_shared_library("distributedhardwareutils") { include_dirs = [ - "//base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include", - "//base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter", - "//third_party/openssl:libcrypto_static", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", + "//third_party/json/include", "${common_path}/log/include", "${common_path}/utils/include", "include", @@ -34,23 +30,27 @@ ohos_shared_library("distributedhardwareutils") { "src/dh_utils_hisysevent.cpp", "src/dh_utils_hitrace.cpp", "src/dh_utils_tool.cpp", + "src/histreamer_ability_parser.cpp", + "src/histreamer_query_tool.cpp", "src/log/dh_log.cpp", ] - deps = [ "//third_party/openssl:libcrypto_static" ] + deps = [ "//third_party/openssl:libcrypto_shared" ] defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"distributedhardwareutils\"", "LOG_DOMAIN=0xD004100", + "OPENSSL_SUPPRESS_DEPRECATED", ] external_deps = [ "c_utils:utils", "dsoftbus:softbus_client", - "hisysevent_native:libhisysevent", - "hitrace_native:hitrace_meter", - "hiviewdfx_hilog_native:libhilog", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "safwk:system_ability_fwk", ] subsystem_name = "distributedhardware" diff --git a/utils/include/dh_utils_tool.h b/utils/include/dh_utils_tool.h index a81b74f02acc6a00f06940dee3d985ad6754ba05..4e0d5cde7f7b597d9e9a25da3bc95f7b046029e0 100644 --- a/utils/include/dh_utils_tool.h +++ b/utils/include/dh_utils_tool.h @@ -18,6 +18,8 @@ #include +#include "nlohmann/json.hpp" + #include "device_type.h" namespace OHOS { @@ -40,6 +42,18 @@ DeviceInfo GetLocalDeviceInfo(); std::string GetDeviceIdByUUID(const std::string &uuid); std::string Sha256(const std::string& string); + +bool IsUInt8(const nlohmann::json& jsonObj, const std::string& key); + +bool IsUInt16(const nlohmann::json& jsonObj, const std::string& key); + +bool IsInt32(const nlohmann::json& jsonObj, const std::string& key); + +bool IsUInt32(const nlohmann::json& jsonObj, const std::string& key); + +bool IsBool(const nlohmann::json& jsonObj, const std::string& key); + +bool IsString(const nlohmann::json& jsonObj, const std::string& key); } // namespace DistributedHardware } // namespace OHOS #endif diff --git a/utils/include/eventbus/event_bus.h b/utils/include/eventbus/event_bus.h index 9e4f013e0ffe691bcbf444899a8742d7ab620bc3..a050daa8d5760feeafd9a7ed77b1c0ea8957f0eb 100644 --- a/utils/include/eventbus/event_bus.h +++ b/utils/include/eventbus/event_bus.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,7 @@ #define OHOS_DISTRIBUTED_HARDWARE_EVENT_BUS_H #include +#include #include #include #include @@ -26,8 +27,11 @@ #include "event_handler.h" +#include "constants.h" #include "dh_log.h" #include "anonymous_string.h" +#include "distributed_hardware_errno.h" +#include "distributed_hardware_log.h" #include "event.h" #include "eventbus_handler.h" #include "event_registration.h" @@ -57,7 +61,7 @@ public: } } - EventBus(const std::string &threadName) + explicit EventBus(const std::string &threadName) { ULOGI("ctor EventBus threadName: %s", threadName.c_str()); if (eventbusHandler_ == nullptr) { @@ -219,6 +223,9 @@ private: } for (auto ® : *registrations) { + if (reg->GetHandler() == nullptr) { + continue; + } if ((reg->GetSender() == nullptr) || (reg->GetSender() == &e.GetSender())) { static_cast *>(const_cast(reg->GetHandler()))->Dispatch(e); } @@ -227,6 +234,10 @@ private: void StartEvent() { + int32_t ret = pthread_setname_np(pthread_self(), START_EVENT); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("StartEvent setname failed."); + } auto busRunner = AppExecFwk::EventRunner::Create(false); { std::lock_guard lock(eventMutex_); diff --git a/utils/include/histreamer_ability_parser.h b/utils/include/histreamer_ability_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..cab9146da174319747fab1adb9f5346f8ad69a18 --- /dev/null +++ b/utils/include/histreamer_ability_parser.h @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_HISTREAMER_ABILITY_PARSER_H +#define OHOS_HISTREAMER_ABILITY_PARSER_H + +#include +#include +#include + +#include "nlohmann/json.hpp" + +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility("default"))) +#endif + +namespace OHOS { +namespace DistributedHardware { + +/** + * @enum Audio AAC Profile。 + * + * AAC mode type. Note that the term profile is used with the MPEG-2 + * standard and the term object type and profile is used with MPEG-4 + * + * @since 1.0 + * @version 1.0 + */ +enum struct AudioAacProfile : uint8_t { + NONE = 0, ///< Null, not used + MAIN = 1, ///< AAC Main object + LC, ///< AAC Low Complexity object (AAC profile) + SSR, ///< AAC Scalable Sample Rate object + LTP, ///< AAC Long Term Prediction object + HE, ///< AAC High Efficiency (object type SBR, HE-AAC profile) + SCALABLE, ///< AAC Scalable object + ERLC = 17, ///< ER AAC Low Complexity object (Error Resilient AAC-LC) + ER_SCALABLE = 20, ///< ER AAC scalable object + LD = 23, ///< AAC Low Delay object (Error Resilient) + HE_PS = 29, ///< AAC High Efficiency with Parametric Stereo coding (HE-AAC v2, object type PS) + ELD = 39, ///< AAC Enhanced Low Delay. NOTE: Pending Khronos standardization + XHE = 42, ///< extended High Efficiency AAC. NOTE: Pending Khronos standardization +}; + +/** + * @enum Audio AAC Stream Format + * + * @since 1.0 + * @version 1.0 + */ +enum struct AudioAacStreamFormat : uint8_t { + MP2ADTS = 0, ///< AAC Audio Data Transport Stream 2 format + MP4ADTS, ///< AAC Audio Data Transport Stream 4 format + MP4LOAS, ///< AAC Low Overhead Audio Stream format + MP4LATM, ///< AAC Low overhead Audio Transport Multiplex + ADIF, ///< AAC Audio Data Interchange Format + MP4FF, ///< AAC inside MPEG-4/ISO File Format + RAW, ///< AAC Raw Format +}; + +/** + * @enum Audio Channel Masks + * + * A 64-bit integer with bits set for each channel. + * + * @since 1.0 + * @version 1.0 + */ +enum AudioChannelMasks : uint64_t { + FRONT_LEFT = 1ULL << 0U, + FRONT_RIGHT = 1ULL << 1U, + FRONT_CENTER = 1ULL << 2U, + LOW_FREQUENCY = 1ULL << 3U, + BACK_LEFT = 1ULL << 4U, + BACK_RIGHT = 1ULL << 5U, + FRONT_LEFT_OF_CENTER = 1ULL << 6U, + FRONT_RIGHT_OF_CENTER = 1ULL << 7U, + BACK_CENTER = 1ULL << 8U, + SIDE_LEFT = 1ULL << 9U, + SIDE_RIGHT = 1ULL << 10U, + TOP_CENTER = 1ULL << 11U, + TOP_FRONT_LEFT = 1ULL << 12U, + TOP_FRONT_CENTER = 1ULL << 13U, + TOP_FRONT_RIGHT = 1ULL << 14U, + TOP_BACK_LEFT = 1ULL << 15U, + TOP_BACK_CENTER = 1ULL << 16U, + TOP_BACK_RIGHT = 1ULL << 17U, + STEREO_LEFT = 1ULL << 29U, + STEREO_RIGHT = 1ULL << 30U, + WIDE_LEFT = 1ULL << 31U, + WIDE_RIGHT = 1ULL << 32U, + SURROUND_DIRECT_LEFT = 1ULL << 33U, + SURROUND_DIRECT_RIGHT = 1ULL << 34U, + LOW_FREQUENCY_2 = 1ULL << 35U, + TOP_SIDE_LEFT = 1ULL << 36U, + TOP_SIDE_RIGHT = 1ULL << 37U, + BOTTOM_FRONT_CENTER = 1ULL << 38U, + BOTTOM_FRONT_LEFT = 1ULL << 39U, + BOTTOM_FRONT_RIGHT = 1ULL << 40U, +}; + +/** + * @enum Audio Channel Layout + * + * Indicates that the channel order in which the user requests decoder output + * is the native codec channel order. + * + * @since 1.0 + * @version 1.0 + */ +enum struct AudioChannelLayout : uint64_t { + UNKNOWN = 0, + MONO = (AudioChannelMasks::FRONT_CENTER), + STEREO = (AudioChannelMasks::FRONT_LEFT | AudioChannelMasks::FRONT_RIGHT), + CH_2POINT1 = (STEREO | AudioChannelMasks::LOW_FREQUENCY), + CH_2_1 = (STEREO | AudioChannelMasks::BACK_CENTER), + SURROUND = (STEREO | AudioChannelMasks::FRONT_CENTER), + CH_3POINT1 = (SURROUND | AudioChannelMasks::LOW_FREQUENCY), + CH_4POINT0 = (SURROUND | AudioChannelMasks::BACK_CENTER), + CH_4POINT1 = (CH_4POINT0 | AudioChannelMasks::LOW_FREQUENCY), + CH_2_2 = (STEREO | AudioChannelMasks::SIDE_LEFT | AudioChannelMasks::SIDE_RIGHT), + QUAD = (STEREO | AudioChannelMasks::BACK_LEFT | AudioChannelMasks::BACK_RIGHT), + CH_5POINT0 = (SURROUND | AudioChannelMasks::SIDE_LEFT | AudioChannelMasks::SIDE_RIGHT), + CH_5POINT1 = (CH_5POINT0 | AudioChannelMasks::LOW_FREQUENCY), + CH_5POINT0_BACK = (SURROUND | AudioChannelMasks::BACK_LEFT | AudioChannelMasks::BACK_RIGHT), + CH_5POINT1_BACK = (CH_5POINT0_BACK | AudioChannelMasks::LOW_FREQUENCY), + CH_6POINT0 = (CH_5POINT0 | AudioChannelMasks::BACK_CENTER), + CH_6POINT0_FRONT = (CH_2_2 | AudioChannelMasks::FRONT_LEFT_OF_CENTER | + AudioChannelMasks::FRONT_RIGHT_OF_CENTER), + HEXAGONAL = (CH_5POINT0_BACK | AudioChannelMasks::BACK_CENTER), + CH_6POINT1 = (CH_5POINT1 | AudioChannelMasks::BACK_CENTER), + CH_6POINT1_BACK = (CH_5POINT1_BACK | AudioChannelMasks::BACK_CENTER), + CH_6POINT1_FRONT = (CH_6POINT0_FRONT | AudioChannelMasks::LOW_FREQUENCY), + CH_7POINT0 = (CH_5POINT0 | AudioChannelMasks::BACK_LEFT | AudioChannelMasks::BACK_RIGHT), + CH_7POINT0_FRONT = (CH_5POINT0 | AudioChannelMasks::FRONT_LEFT_OF_CENTER | + AudioChannelMasks::FRONT_RIGHT_OF_CENTER), + CH_7POINT1 = (CH_5POINT1 | AudioChannelMasks::BACK_LEFT | AudioChannelMasks::BACK_RIGHT), + CH_7POINT1_WIDE = (CH_5POINT1 | AudioChannelMasks::FRONT_LEFT_OF_CENTER | + AudioChannelMasks::FRONT_RIGHT_OF_CENTER), + CH_7POINT1WIDE_BACK = (CH_5POINT1_BACK | AudioChannelMasks::FRONT_LEFT_OF_CENTER | + AudioChannelMasks::FRONT_RIGHT_OF_CENTER), + CH_3POINT1POINT2 = (CH_3POINT1 | AudioChannelMasks::TOP_FRONT_LEFT | AudioChannelMasks::TOP_FRONT_RIGHT), + CH_5POINT1POINT2 = (CH_5POINT1 | AudioChannelMasks::TOP_SIDE_LEFT | AudioChannelMasks::TOP_SIDE_RIGHT), + CH_5POINT1POINT4 = (CH_5POINT1 | AudioChannelMasks::TOP_FRONT_LEFT | AudioChannelMasks::TOP_FRONT_RIGHT | + AudioChannelMasks::TOP_BACK_LEFT | AudioChannelMasks::TOP_BACK_RIGHT), + CH_7POINT1POINT2 = (CH_7POINT1 | AudioChannelMasks::TOP_SIDE_LEFT | AudioChannelMasks::TOP_SIDE_RIGHT), + CH_7POINT1POINT4 = (CH_7POINT1 | AudioChannelMasks::TOP_FRONT_LEFT | AudioChannelMasks::TOP_FRONT_RIGHT | + AudioChannelMasks::TOP_BACK_LEFT | AudioChannelMasks::TOP_BACK_RIGHT), + CH_9POINT1POINT4 = (CH_7POINT1POINT4 | AudioChannelMasks::WIDE_LEFT | + AudioChannelMasks::WIDE_RIGHT), + CH_9POINT1POINT6 = (CH_9POINT1POINT4 | AudioChannelMasks::TOP_SIDE_LEFT | AudioChannelMasks::TOP_SIDE_RIGHT), + CH_10POINT2 = (AudioChannelMasks::FRONT_LEFT | AudioChannelMasks::FRONT_RIGHT | + AudioChannelMasks::FRONT_CENTER | AudioChannelMasks::TOP_FRONT_LEFT | + AudioChannelMasks::TOP_FRONT_RIGHT | AudioChannelMasks::BACK_LEFT | + AudioChannelMasks::BACK_RIGHT | AudioChannelMasks::BACK_CENTER | + AudioChannelMasks::SIDE_LEFT | AudioChannelMasks::SIDE_RIGHT | + AudioChannelMasks::WIDE_LEFT | AudioChannelMasks::WIDE_RIGHT), + CH_22POINT2 = (CH_7POINT1POINT4 | AudioChannelMasks::FRONT_LEFT_OF_CENTER | + AudioChannelMasks::FRONT_RIGHT_OF_CENTER | AudioChannelMasks::BACK_CENTER | + AudioChannelMasks::TOP_CENTER | AudioChannelMasks::TOP_FRONT_CENTER | + AudioChannelMasks::TOP_BACK_CENTER | AudioChannelMasks::TOP_SIDE_LEFT | + AudioChannelMasks::TOP_SIDE_RIGHT | AudioChannelMasks::BOTTOM_FRONT_LEFT | + AudioChannelMasks::BOTTOM_FRONT_RIGHT | AudioChannelMasks::BOTTOM_FRONT_CENTER | + AudioChannelMasks::LOW_FREQUENCY_2), + OCTAGONAL = (CH_5POINT0 | AudioChannelMasks::BACK_LEFT | AudioChannelMasks::BACK_CENTER | + AudioChannelMasks::BACK_RIGHT), + HEXADECAGONAL = (OCTAGONAL | AudioChannelMasks::WIDE_LEFT | AudioChannelMasks::WIDE_RIGHT | + AudioChannelMasks::TOP_BACK_LEFT | AudioChannelMasks::TOP_BACK_RIGHT | + AudioChannelMasks::TOP_BACK_CENTER | AudioChannelMasks::TOP_FRONT_CENTER | + AudioChannelMasks::TOP_FRONT_LEFT | AudioChannelMasks::TOP_FRONT_RIGHT), + STEREO_DOWNMIX = (AudioChannelMasks::STEREO_LEFT | AudioChannelMasks::STEREO_RIGHT), +}; + +/** + * @enum Audio sample formats + * + * 'S' is signed, 'U' is unsigned, and 'F' is a floating-point number. + * 'P' is planes, default is interleaved. + * + * @since 1.0 + * @version 1.0 + */ +enum struct AudioSampleFormat : uint8_t { + NONE, + /* 8 bit */ + S8, U8, S8P, U8P, + /* 16 bit */ + S16, U16, S16P, U16P, + /* 24 bit */ + S24, U24, S24P, U24P, + /* 32 bit */ + S32, U32, S32P, U32P, + /* 64 bit */ + S64, U64, S64P, U64P, + /* float double */ + F32, F32P, F64, F64P, +}; + +/** + * @enum Video Pixel Format. + * + * @since 1.0 + * @version 1.0 + */ +enum struct VideoPixelFormat : uint32_t { + UNKNOWN, + YUV410P, ///< planar YUV 4:1:0, 1 Cr & Cb sample per 4x4 Y samples + YUV411P, ///< planar YUV 4:1:1, 1 Cr & Cb sample per 4x1 Y samples + YUV420P, ///< planar YUV 4:2:0, 1 Cr & Cb sample per 2x2 Y samples + NV12, ///< semi-planar YUV 4:2:0, UVUV... + NV21, ///< semi-planar YUV 4:2:0, VUVU... + YUYV422, ///< packed YUV 4:2:2, Y0 Cb Y1 Cr + YUV422P, ///< planar YUV 4:2:2, 1 Cr & Cb sample per 2x1 Y samples + YUV444P, ///< planar YUV 4:4:4, 1 Cr & Cb sample per 1x1 Y samples + RGBA, ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA... + ARGB, ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB... + ABGR, ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR... + BGRA, ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA... + RGB24, ///< packed RGB 8:8:8, RGBRGB... + BGR24, ///< packed RGB 8:8:8, BGRBGR... + PAL8, ///< 8 bit with AV_PIX_FMT_RGB32 palette + GRAY8, ///< Y + MONOWHITE, ///< Y, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb + MONOBLACK, ///< Y, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb + YUVJ420P, ///< planar YUV 4:2:0, 12bpp, full scale (JPEG) + YUVJ422P, ///< planar YUV 4:2:2, 16bpp, full scale (JPEG) + YUVJ444P, ///< planar YUV 4:4:4, 24bpp, full scale (JPEG) +}; + +/** + * @enum Video Bit Stream format. + * + * @since 1.0 + * @version 1.0 + */ +enum struct VideoBitStreamFormat : uint32_t { + UNKNOWN, + AVC1, // H264 bit stream format + HEVC, // H265 bit stream format + ANNEXB, // H264, H265 bit stream format +}; + +static const std::string AUDIO_ENCODERS = "audioEncoders"; +static const std::string AUDIO_DECODERS = "audioDecoders"; +static const std::string VIDEO_ENCODERS = "videoEncoders"; +static const std::string VIDEO_DECODERS = "videoDecoders"; + +/******************* AudioEncoder Begin *****************/ +struct AudioEncoderIn { + std::string mime; + std::vector sample_rate; +}; + +struct AudioEncoderOut { + std::string mime; + uint32_t ad_mpeg_ver; + AudioAacProfile aac_profile; + AudioAacStreamFormat aac_stm_fmt; +}; + +struct AudioEncoder { + std::string name; + std::vector ins; + std::vector outs; +}; + +void FromJson(const nlohmann::json &jsonObject, AudioEncoderIn &audioEncoderIn); +void FromJson(const nlohmann::json &jsonObject, AudioEncoderOut &audioEncoderOut); +void FromJson(const nlohmann::json &jsonObject, AudioEncoder &audioEncoder); +/******************* AudioEncoder End *******************/ + +/******************* AudioDecoder Begin *****************/ +struct AudioDecoderIn { + std::string mime; + std::vector channel_layout; +}; + +struct AudioDecoderOut { + std::string mime; + std::vector sample_fmt; +}; + +struct AudioDecoder { + std::string name; + std::vector ins; + std::vector outs; +}; + +void FromJson(const nlohmann::json &jsonObject, AudioDecoderIn &audioDecoderIn); +void FromJson(const nlohmann::json &jsonObject, AudioDecoderOut &audioDecoderOut); +void FromJson(const nlohmann::json &jsonObject, AudioDecoder &audioDecoder); +/******************* AudioDecoder End *******************/ + +/******************* VideoEncoder Begin *****************/ +struct VideoEncoderIn { + std::string mime; + std::vector pixel_fmt; +}; + +struct VideoEncoderOut { + std::string mime; +}; + +struct VideoEncoder { + std::string name; + std::vector ins; + std::vector outs; +}; + +void FromJson(const nlohmann::json &jsonObject, VideoEncoderIn &videoEncoderIn); +void FromJson(const nlohmann::json &jsonObject, VideoEncoderOut &videoEncoderOut); +void FromJson(const nlohmann::json &jsonObject, VideoEncoder &videoEncoder); +/******************* VideoEncoder End *******************/ + +/******************* VideoDecoder Begin *****************/ +struct VideoDecoderIn { + std::string mime; + std::vector vd_bit_stream_fmt; +}; + +struct VideoDecoderOut { + std::string mime; + std::vector pixel_fmt; +}; + +struct VideoDecoder { + std::string name; + std::vector ins; + std::vector outs; +}; + +void FromJson(const nlohmann::json &jsonObject, VideoDecoderIn &videoDecoderIn); +void FromJson(const nlohmann::json &jsonObject, VideoDecoderOut &videoDecoderOut); +void FromJson(const nlohmann::json &jsonObject, VideoDecoder &videoDecoder); +/******************* VideoDecoder End *******************/ +template +API_EXPORT void FromJson(const std::string &key, const nlohmann::json &jsonObject, std::vector &objs); +} +} +#endif \ No newline at end of file diff --git a/utils/include/histreamer_query_tool.h b/utils/include/histreamer_query_tool.h new file mode 100644 index 0000000000000000000000000000000000000000..dbbb1398582a1a4fc817f69228de444a7599c6cc --- /dev/null +++ b/utils/include/histreamer_query_tool.h @@ -0,0 +1,37 @@ + +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include "single_instance.h" +namespace OHOS { +namespace DistributedHardware { +enum class HISTREAM_PLUGIN_TYPE : uint8_t { + AUDIO_ENCODER, + AUDIO_DECODER, + VIDEO_ENCODER, + VIDEO_DECODER +}; + +class HiStreamerQueryTool { +DECLARE_SINGLE_INSTANCE(HiStreamerQueryTool); +public: + std::string QueryHiStreamerPluginInfo(HISTREAM_PLUGIN_TYPE type); +private: + std::atomic isInit = false; + void Init(); +}; +} +} \ No newline at end of file diff --git a/utils/src/dh_utils_hisysevent.cpp b/utils/src/dh_utils_hisysevent.cpp index 499e00a160ab7184c13067b06ca44a1690a340f3..be99ff09a218129c360e3799044ddb9385aec69c 100644 --- a/utils/src/dh_utils_hisysevent.cpp +++ b/utils/src/dh_utils_hisysevent.cpp @@ -24,7 +24,7 @@ namespace DistributedHardware { void HiSysEventWriteMsg(const std::string &status, const OHOS::HiviewDFX::HiSysEvent::EventType eventType, const std::string &msg) { - int32_t res = OHOS::HiviewDFX::HiSysEvent::Write( + int32_t res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_HARDWARE_FWK, status.c_str(), eventType, @@ -37,7 +37,7 @@ void HiSysEventWriteMsg(const std::string &status, const OHOS::HiviewDFX::HiSysE void HiSysEventWriteErrCodeMsg(const std::string &status, const OHOS::HiviewDFX::HiSysEvent::EventType eventType, int32_t errCode, const std::string &msg) { - int32_t res = OHOS::HiviewDFX::HiSysEvent::Write( + int32_t res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_HARDWARE_FWK, status.c_str(), eventType, @@ -57,7 +57,7 @@ void HiSysEventWriteReleaseMsg(const std::string &status, const OHOS::HiviewDFX: dhTypeStr = it->second; } - int32_t res = OHOS::HiviewDFX::HiSysEvent::Write( + int32_t res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_HARDWARE_FWK, status.c_str(), eventType, @@ -72,7 +72,7 @@ void HiSysEventWriteReleaseMsg(const std::string &status, const OHOS::HiviewDFX: void HiSysEventWriteCompOfflineMsg(const std::string &status, const OHOS::HiviewDFX::HiSysEvent::EventType eventType, const std::string &anonyNetworkId, const std::string &msg) { - int32_t res = OHOS::HiviewDFX::HiSysEvent::Write( + int32_t res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_HARDWARE_FWK, status.c_str(), eventType, @@ -86,7 +86,7 @@ void HiSysEventWriteCompOfflineMsg(const std::string &status, const OHOS::Hiview void HiSysEventWriteCompMgrFailedMsg(const std::string &status, const OHOS::HiviewDFX::HiSysEvent::EventType eventType, const std::string &anonyDHId, int32_t errCode, const std::string &msg) { - int32_t res = OHOS::HiviewDFX::HiSysEvent::Write( + int32_t res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_HARDWARE_FWK, status.c_str(), eventType, diff --git a/utils/src/dh_utils_tool.cpp b/utils/src/dh_utils_tool.cpp index 8b49ad54ff5594c193453dd6c0cd6104f26d0d01..59907c6b5f6c6a7794a3bc50705fa1ebef616994 100644 --- a/utils/src/dh_utils_tool.cpp +++ b/utils/src/dh_utils_tool.cpp @@ -126,5 +126,43 @@ DeviceInfo GetLocalDeviceInfo() devInfo.deviceType = info->deviceTypeId; return devInfo; } + +bool IsUInt8(const nlohmann::json& jsonObj, const std::string& key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_number_unsigned() && jsonObj[key] <= UINT8_MAX; + return res; +} + +bool IsUInt16(const nlohmann::json& jsonObj, const std::string& key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_number_unsigned() && jsonObj[key] <= UINT16_MAX; + return res; +} + +bool IsInt32(const nlohmann::json& jsonObj, const std::string& key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_number_integer() && INT32_MIN <= jsonObj[key] && + jsonObj[key] <= INT32_MAX; + return res; +} + +bool IsUInt32(const nlohmann::json& jsonObj, const std::string& key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_number_unsigned() && jsonObj[key] <= UINT32_MAX; + return res; +} + +bool IsBool(const nlohmann::json& jsonObj, const std::string& key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_boolean(); + return res; +} + +bool IsString(const nlohmann::json& jsonObj, const std::string& key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_string() && MIN_MESSAGE_LEN < jsonObj[key].size() && + jsonObj[key].size() <= MAX_MESSAGE_LEN; + return res; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/histreamer_ability_parser.cpp b/utils/src/histreamer_ability_parser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..072aa7a2e8631d78c2102ae4cb48633fbe754c3f --- /dev/null +++ b/utils/src/histreamer_ability_parser.cpp @@ -0,0 +1,325 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "histreamer_ability_parser.h" +#include "dh_utils_tool.h" +#include "distributed_hardware_log.h" + + +namespace OHOS { +namespace DistributedHardware { + +static const std::string NAME = "name"; +static const std::string INS = "ins"; +static const std::string OUTS = "outs"; +static const std::string MIME = "mime"; +static const std::string SAMPLE_RATE = "sample_rate"; +static const std::string AUDIO_SAMPLE_FORMAT = "sample_fmt"; +static const std::string AD_MPEG_VER = "ad_mpeg_ver"; +static const std::string AUDIO_AAC_PROFILE = "aac_profile"; +static const std::string AUDIO_AAC_STREAM_FORMAT = "aac_stm_fmt"; +static const std::string AUDIO_CHANNEL_LAYOUT = "channel_layout"; + +static const std::string VIDEO_PIXEL_FMT = "pixel_fmt"; +static const std::string VIDEO_BIT_STREAM_FMT = "vd_bit_stream_fmt"; + +void FromJson(const nlohmann::json &jsonObject, AudioEncoderIn &audioEncoderIn) +{ + if (!IsString(jsonObject, MIME)) { + DHLOGE("AudioEncoderIn MIME is invalid!"); + return; + } + audioEncoderIn.mime = jsonObject.at(MIME).get(); + if (jsonObject.find(SAMPLE_RATE) == jsonObject.end()) { + DHLOGE("AudioEncoderIn SAMPLE_RATE is invalid"); + } + audioEncoderIn.sample_rate = jsonObject.at(SAMPLE_RATE).get>(); +} + +void FromJson(const nlohmann::json &jsonObject, AudioEncoderOut &audioEncoderOut) +{ + if (!IsString(jsonObject, MIME)) { + DHLOGE("AudioEncoderOut MIME is invalid!"); + return; + } + audioEncoderOut.mime = jsonObject.at(MIME).get(); + + if (!IsUInt32(jsonObject, AD_MPEG_VER)) { + DHLOGE("AudioEncoderOut AD_MPEG_VER is invalid"); + return; + } + audioEncoderOut.ad_mpeg_ver = jsonObject.at(AD_MPEG_VER).get(); + + if (!IsUInt8(jsonObject, AUDIO_AAC_PROFILE)) { + DHLOGE("AudioEncoderOut AUDIO_AAC_PROFILE is invalid"); + return; + } + audioEncoderOut.aac_profile = (AudioAacProfile)jsonObject.at(AUDIO_AAC_PROFILE).get(); + + if (!IsUInt8(jsonObject, AUDIO_AAC_STREAM_FORMAT)) { + DHLOGE("AudioEncoderOut AUDIO_AAC_STREAM_FORMAT is invalid"); + return; + } + audioEncoderOut.aac_stm_fmt = (AudioAacStreamFormat)jsonObject.at(AUDIO_AAC_STREAM_FORMAT).get(); +} + +void FromJson(const nlohmann::json &jsonObject, AudioEncoder &audioEncoder) +{ + if (!IsString(jsonObject, NAME)) { + DHLOGE("AudioEncoder NAME is invalid"); + return; + } + audioEncoder.name = jsonObject.at(NAME).get(); + + if (jsonObject.find(INS) == jsonObject.end()) { + DHLOGE("AudioEncoder INS is invalid"); + return; + } + + nlohmann::json audioEncoderInsJson = jsonObject[INS]; + for (const auto &inJson : audioEncoderInsJson) { + AudioEncoderIn in; + FromJson(inJson, in); + audioEncoder.ins.push_back(in); + } + + if (jsonObject.find(OUTS) == jsonObject.end()) { + DHLOGE("AudioEncoder OUTS is invalid"); + return; + } + nlohmann::json audioEncoderOutsJson = jsonObject[OUTS]; + for (const auto &outJson : audioEncoderOutsJson) { + AudioEncoderOut out; + FromJson(outJson, out); + audioEncoder.outs.push_back(out); + } +} + +void FromJson(const nlohmann::json &jsonObject, AudioDecoderIn &audioDecoderIn) +{ + if (!IsString(jsonObject, MIME)) { + DHLOGE("AudioDecoderIn MIME is invalid"); + return; + } + audioDecoderIn.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(AUDIO_CHANNEL_LAYOUT) == jsonObject.end()) { + DHLOGE("AudioEncoder AUDIO_CHANNEL_LAYOUT is invalid"); + return; + } + nlohmann::json channelLayoutJson = jsonObject[AUDIO_CHANNEL_LAYOUT]; + for (auto layout : channelLayoutJson) { + audioDecoderIn.channel_layout.push_back((AudioChannelLayout)layout); + } +} + +void FromJson(const nlohmann::json &jsonObject, AudioDecoderOut &audioDecoderOut) +{ + if (!IsString(jsonObject, MIME)) { + DHLOGE("AudioDecoderOut MIME is invalid"); + return; + } + audioDecoderOut.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(AUDIO_SAMPLE_FORMAT) == jsonObject.end()) { + DHLOGE("AudioDecoderOut AUDIO_SAMPLE_FORMAT is invalid"); + return; + } + + for (auto sampleFormatJson : jsonObject[AUDIO_SAMPLE_FORMAT]) { + audioDecoderOut.sample_fmt.push_back((AudioSampleFormat)sampleFormatJson); + } +} + +void FromJson(const nlohmann::json &jsonObject, AudioDecoder &audioDecoder) +{ + if (!IsString(jsonObject, NAME)) { + DHLOGE("AudioDecoder NAME is invalid"); + return; + } + audioDecoder.name = jsonObject.at(NAME).get(); + + if (jsonObject.find(INS) == jsonObject.end()) { + DHLOGE("AudioDecoder INS is invalid"); + return; + } + + nlohmann::json audioDecoderInsJson = jsonObject[INS]; + for (const auto &inJson : audioDecoderInsJson) { + AudioDecoderIn in; + FromJson(inJson, in); + audioDecoder.ins.push_back(in); + } + + if (jsonObject.find(OUTS) == jsonObject.end()) { + DHLOGE("AudioDecoder OUTS is invalid"); + return; + } + nlohmann::json audioDecoderOutsJson = jsonObject[OUTS]; + for (const auto &outJson : audioDecoderOutsJson) { + AudioDecoderOut out; + FromJson(outJson, out); + audioDecoder.outs.push_back(out); + } +} + +void FromJson(const nlohmann::json &jsonObject, VideoEncoderIn &videoEncoderIn) +{ + if (!IsString(jsonObject, MIME)) { + DHLOGE("VideoEncoderIn MIME is invalid"); + return; + } + videoEncoderIn.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(VIDEO_PIXEL_FMT) == jsonObject.end()) { + DHLOGE("VideoEncoderIn VIDEO_PIXEL_FMT is invalid"); + return; + } + for (auto fmt : jsonObject[VIDEO_PIXEL_FMT]) { + videoEncoderIn.pixel_fmt.push_back((VideoPixelFormat)fmt); + } +} + +void FromJson(const nlohmann::json &jsonObject, VideoEncoderOut &videoEncoderOut) +{ + if (!IsString(jsonObject, MIME)) { + DHLOGE("VideoEncoderOut MIME is invalid"); + return; + } + videoEncoderOut.mime = jsonObject[MIME].get(); +} + +void FromJson(const nlohmann::json &jsonObject, VideoEncoder &videoEncoder) +{ + if (!IsString(jsonObject, NAME)) { + DHLOGE("VideoEncoder NAME is invalid"); + return; + } + videoEncoder.name = jsonObject.at(NAME).get(); + + if (jsonObject.find(INS) == jsonObject.end()) { + DHLOGE("VideoEncoder INS is invalid"); + return; + } + + nlohmann::json videoEncoderInsJson = jsonObject[INS]; + for (const auto &inJson : videoEncoderInsJson) { + VideoEncoderIn in; + FromJson(inJson, in); + videoEncoder.ins.push_back(in); + } + + if (jsonObject.find(OUTS) == jsonObject.end()) { + DHLOGE("VideoEncoder OUTS is invalid"); + return; + } + nlohmann::json videoEncoderOutsJson = jsonObject[OUTS]; + for (const auto &outJson : videoEncoderOutsJson) { + VideoEncoderOut out; + FromJson(outJson, out); + videoEncoder.outs.push_back(out); + } +} + + +void FromJson(const nlohmann::json &jsonObject, VideoDecoderIn &videoDecoderIn) +{ + if (!IsString(jsonObject, MIME)) { + DHLOGE("VideoDecoderIn MIME is invalid"); + return; + } + videoDecoderIn.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(VIDEO_BIT_STREAM_FMT) == jsonObject.end()) { + DHLOGE("VideoDecoderIn VIDEO_BIT_STREAM_FMT is invalid"); + return; + } + for (auto fmt : jsonObject[VIDEO_BIT_STREAM_FMT]) { + videoDecoderIn.vd_bit_stream_fmt.push_back((VideoBitStreamFormat)fmt); + } +} + +void FromJson(const nlohmann::json &jsonObject, VideoDecoderOut &videoDecoderOut) +{ + if (!IsString(jsonObject, MIME)) { + DHLOGE("VideoDecoderOut MIME is invalid"); + return; + } + videoDecoderOut.mime = jsonObject.at(MIME).get(); + + if (jsonObject.find(VIDEO_PIXEL_FMT) == jsonObject.end()) { + DHLOGE("VideoDecoderOut VIDEO_PIXEL_FMT is invalid"); + return; + } + for (auto fmt : jsonObject[VIDEO_PIXEL_FMT]) { + videoDecoderOut.pixel_fmt.push_back((VideoPixelFormat)fmt); + } +} + +void FromJson(const nlohmann::json &jsonObject, VideoDecoder &videoDecoder) +{ + if (!IsString(jsonObject, NAME)) { + DHLOGE("VideoDecoder NAME is invalid"); + return; + } + videoDecoder.name = jsonObject.at(NAME).get(); + + if (jsonObject.find(INS) == jsonObject.end()) { + DHLOGE("VideoDecoder INS is invalid"); + return; + } + + nlohmann::json videoDecoderInsJson = jsonObject[INS]; + for (const auto &inJson : videoDecoderInsJson) { + VideoDecoderIn in; + FromJson(inJson, in); + videoDecoder.ins.push_back(in); + } + + if (jsonObject.find(OUTS) == jsonObject.end()) { + DHLOGE("VideoDecoder OUTS is invalid"); + return; + } + nlohmann::json videoDecoderOutsJson = jsonObject[OUTS]; + for (const auto &outJson : videoDecoderOutsJson) { + VideoDecoderOut out; + FromJson(outJson, out); + videoDecoder.outs.push_back(out); + } +} + +template +void FromJson(const std::string &key, const nlohmann::json &jsonObject, std::vector &objs) +{ + if (jsonObject.find(key) == jsonObject.end()) { + DHLOGE("JSONObject key invalid, key: %s", key.c_str()); + return; + } + for (auto &json : jsonObject[key]) { + T obj; + FromJson(json, obj); + objs.push_back(obj); + } +} +template +void FromJson(const std::string &key, const nlohmann::json &jsonObject, std::vector &objs); +template +void FromJson(const std::string &key, const nlohmann::json &jsonObject, std::vector &objs); +template +void FromJson(const std::string &key, const nlohmann::json &jsonObject, std::vector &objs); +template +void FromJson(const std::string &key, const nlohmann::json &jsonObject, std::vector &objs); +} +} \ No newline at end of file diff --git a/utils/src/histreamer_query_tool.cpp b/utils/src/histreamer_query_tool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..76b3795fba5664dc2abb8ccff06e222e41dcb8d0 --- /dev/null +++ b/utils/src/histreamer_query_tool.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "histreamer_query_tool.h" + +#include +#include + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(HiStreamerQueryTool); +using QueryAudioEncoderFunc = int32_t (*)(char*); +using QueryAudioDecoderFunc = int32_t (*)(char*); +using QueryVideoEncoderFunc = int32_t (*)(char*); +using QueryVideoDecoderFunc = int32_t (*)(char*); + +QueryAudioEncoderFunc queryAudioEncoderFunc = nullptr; +QueryAudioDecoderFunc queryAudioDecoderFunc = nullptr; +QueryVideoEncoderFunc queryVideoEncoderFunc = nullptr; +QueryVideoDecoderFunc queryVideoDecoderFunc = nullptr; + +const std::string QueryAudioEncoderFuncName = "QueryAudioEncoderAbilityStr"; +const std::string QueryAudioDecoderFuncName = "QueryAudioDecoderAbilityStr"; +const std::string QueryVideoEncoderFuncName = "QueryVideoEncoderAbilityStr"; +const std::string QueryVideoDecoderFuncName = "QueryVideoDecoderAbilityStr"; + +const uint32_t MAX_MESSAGES_LEN = 1 * 1024 * 1024; + +#ifdef __LP64__ +const std::string LIB_LOAD_PATH = "/system/lib64/libhistreamer_ability_querier.z.so"; +#else +const std::string LIB_LOAD_PATH = "/system/lib/libhistreamer_ability_querier.z.so"; +#endif + +void HiStreamerQueryTool::Init() +{ + if (isInit) { + return; + } + DHLOGI("Start Init HiStreamer Query SO"); + void *pHandler = dlopen(LIB_LOAD_PATH.c_str(), RTLD_LAZY | RTLD_NODELETE); + if (pHandler == nullptr) { + DHLOGE("libhistreamer_ability_querier.z.so handler load failed, failed reason : %s", dlerror()); + return; + } + + queryAudioEncoderFunc = (QueryAudioEncoderFunc)dlsym(pHandler, + QueryAudioEncoderFuncName.c_str()); + if (queryAudioEncoderFunc == nullptr) { + DHLOGE("get QueryAudioEncoderAbilityStr is null, failed reason : %s", dlerror()); + dlclose(pHandler); + return; + } + + queryAudioDecoderFunc = (QueryAudioDecoderFunc)dlsym(pHandler, + QueryAudioDecoderFuncName.c_str()); + if (queryAudioDecoderFunc == nullptr) { + DHLOGE("get QueryAudioDecoderAbilityStr is null, failed reason : %s", dlerror()); + dlclose(pHandler); + return; + } + + queryVideoEncoderFunc = (QueryVideoEncoderFunc)dlsym(pHandler, + QueryVideoEncoderFuncName.c_str()); + if (queryVideoEncoderFunc == nullptr) { + DHLOGE("get QueryVideoEncoderAbilityStr is null, failed reason : %s", dlerror()); + dlclose(pHandler); + return; + } + + queryVideoDecoderFunc = (QueryVideoDecoderFunc)dlsym(pHandler, + QueryVideoDecoderFuncName.c_str()); + if (queryVideoDecoderFunc == nullptr) { + DHLOGE("get QueryVideoDecoderAbilityStr is null, failed reason : %s", dlerror()); + dlclose(pHandler); + return; + } + + DHLOGI("Init Query HiStreamer Tool Success"); + isInit = true; +} + +std::string HiStreamerQueryTool::QueryHiStreamerPluginInfo(HISTREAM_PLUGIN_TYPE type) +{ + Init(); + if (!isInit || queryAudioEncoderFunc == nullptr || queryAudioDecoderFunc == nullptr || + queryVideoEncoderFunc == nullptr || queryVideoDecoderFunc == nullptr) { + DHLOGE("Query HiStreamer Tool Init failed"); + return ""; + } + + int32_t len = 0; + char* res = reinterpret_cast(malloc(MAX_MESSAGES_LEN)); + if (res == nullptr) { + DHLOGE("Malloc memory failed"); + return ""; + } + switch (type) { + case HISTREAM_PLUGIN_TYPE::AUDIO_ENCODER: { + len = queryAudioEncoderFunc(res); + break; + } + case HISTREAM_PLUGIN_TYPE::AUDIO_DECODER: { + len = queryAudioDecoderFunc(res); + break; + } + case HISTREAM_PLUGIN_TYPE::VIDEO_ENCODER: { + len = queryVideoEncoderFunc(res); + break; + } + case HISTREAM_PLUGIN_TYPE::VIDEO_DECODER: { + len = queryVideoDecoderFunc(res); + break; + } + default: + break; + } + + std::string result(res, len); + free(res); + res = nullptr; + return result; +} +} +} \ No newline at end of file diff --git a/utils/test/fuzztest/utils_fuzzer/BUILD.gn b/utils/test/fuzztest/utils_fuzzer/BUILD.gn index 57c7f42bce3afbe434e8ce60bda0d9c33f4cf26f..f78526e9416461abef1cb8f7e3878f708fec2817 100644 --- a/utils/test/fuzztest/utils_fuzzer/BUILD.gn +++ b/utils/test/fuzztest/utils_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,13 +20,13 @@ import( ##############################fuzztest########################################## ohos_fuzztest("UtilsFuzzTest") { module_out_path = "distributed_hardware_fwk/utils" - fuzz_config_file = "//foundation/distributedhardware/distributed_hardware_fwk/utils/test/fuzztest/utils_fuzzer" + fuzz_config_file = "${utils_path}/test/fuzztest/utils_fuzzer" include_dirs = [ "${utils_path}/include", "${utils_path}/include/log", "${common_path}/utils/include", - "//commonlibrary/c_utils/base/include", + "//third_party/json/include", ] cflags = [ "-g", @@ -36,7 +36,9 @@ ohos_fuzztest("UtilsFuzzTest") { ] sources = [ "utils_fuzzer.cpp" ] - deps = [ "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils" ] + deps = [ "${utils_path}:distributedhardwareutils" ] + + external_deps = [ "c_utils:utils" ] } ############################################################################### diff --git a/utils/test/fuzztest/utils_fuzzer/utils_fuzzer.cpp b/utils/test/fuzztest/utils_fuzzer/utils_fuzzer.cpp index e1b65aa13b7a61c02ca47312baa1b526ced6d8ea..f836dda9b68786c424c2125a335790d86be4bae6 100644 --- a/utils/test/fuzztest/utils_fuzzer/utils_fuzzer.cpp +++ b/utils/test/fuzztest/utils_fuzzer/utils_fuzzer.cpp @@ -26,12 +26,12 @@ namespace OHOS { namespace DistributedHardware { void GetAnonyStringTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size <= 0)) { + if ((data == nullptr) || (size == 0)) { return; } std::string str(reinterpret_cast(data), size); - std::string anonyStr = GetAnonyString(str); + GetAnonyString(str); } void GetAnonyInt32Test(const uint8_t* data, size_t size) @@ -41,19 +41,19 @@ void GetAnonyInt32Test(const uint8_t* data, size_t size) } int32_t i = *(reinterpret_cast(data)); - std::string anonyStr = GetAnonyInt32(i); + GetAnonyInt32(i); } void UtilsToolTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size <= 0)) { + if ((data == nullptr) || (size == 0)) { return; } std::string networkId(reinterpret_cast(data), size); std::string uuid(reinterpret_cast(data), size); - std::string uuidStr = GetUUIDBySoftBus(networkId); - std::string deviceIdStr = GetDeviceIdByUUID(uuid); + GetUUIDBySoftBus(networkId); + GetDeviceIdByUUID(uuid); } } } diff --git a/utils/test/unittest/BUILD.gn b/utils/test/unittest/BUILD.gn index 1ff1b02e22c02518865cbfe7f399e1e3c9c75d92..699cdf197a3b73ae4244e825801839e5ac4e2b4d 100644 --- a/utils/test/unittest/BUILD.gn +++ b/utils/test/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -15,6 +15,8 @@ group("utils_test") { testonly = true deps = [ "common/eventbus:event_bus_test", + "common/eventtrance:event_trance_test", + "common/histreamer_ability_parser:histreamer_ability_parser_test", "common/utilstool:utils_tool_test", ] } diff --git a/utils/test/unittest/common/eventbus/BUILD.gn b/utils/test/unittest/common/eventbus/BUILD.gn index 6025ffbf5710a677310a96ddce045907df89ea61..244fae686832ff62ed01a178516f739847347fc5 100644 --- a/utils/test/unittest/common/eventbus/BUILD.gn +++ b/utils/test/unittest/common/eventbus/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -22,10 +22,10 @@ config("module_private_config") { include_dirs = [ "include", "${common_path}/log/include", + "${common_path}/utils/include", "${utils_path}/include", "${utils_path}/include/log", "${utils_path}/include/eventbus", - "//commonlibrary/c_utils/base/include", ] } @@ -38,11 +38,14 @@ ohos_unittest("EventBusTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils", + "${utils_path}:distributedhardwareutils", "//third_party/googletest:gtest_main", ] - external_deps = [ "eventhandler:libeventhandler" ] + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + ] } group("event_bus_test") { diff --git a/utils/test/unittest/common/eventbus/event_bus_test.cpp b/utils/test/unittest/common/eventbus/event_bus_test.cpp index 8ca543ca2708480dfaffcdf0b594cf29faf504e3..400eafeff7ad0ee9ad6f2f3bc5407b062c16c15a 100644 --- a/utils/test/unittest/common/eventbus/event_bus_test.cpp +++ b/utils/test/unittest/common/eventbus/event_bus_test.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include "distributed_hardware_log.h" #include "event_bus.h" @@ -33,6 +34,7 @@ namespace { FakeListener *g_listener = nullptr; std::shared_ptr g_regHandler = nullptr; EventBus* g_eventBus = nullptr; + const int32_t TEST_TWENTY_MS = 20000; } void EventbusTest::SetUpTestCase(void) @@ -70,6 +72,7 @@ void EventbusTest::SetUp() void EventbusTest::TearDown() { + usleep(TEST_TWENTY_MS); if (g_obj != nullptr) { delete g_obj; g_obj = nullptr; diff --git a/utils/test/unittest/common/eventtrance/BUILD.gn b/utils/test/unittest/common/eventtrance/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4ff0134bd108eb43d2e2dd427d61694ad3357594 --- /dev/null +++ b/utils/test/unittest/common/eventtrance/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/event_trance_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/log", + "${utils_path}/include/eventbus", + "${utils_path}/test/unittest/common/eventtrance", + "//third_party/json/include", + "//third_party/openssl:libcrypto_shared", + "${common_path}/log/include", + "${common_path}/utils/include", + "${services_path}/distributedhardwarefwkservice/include/utils", + "${utils_path}/include/eventtrance", + "${utils_path}/include", + ] +} + +ohos_unittest("EventTranceTest") { + module_out_path = module_out_path + + sources = [ "./event_trance_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/distributedhardwarefwkservice:distributedhardwarefwksvr", + "${utils_path}:distributedhardwareutils", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "safwk:system_ability_fwk", + ] +} + +group("event_trance_test") { + testonly = true + deps = [ ":EventTranceTest" ] +} diff --git a/utils/test/unittest/common/eventtrance/event_trance_test.cpp b/utils/test/unittest/common/eventtrance/event_trance_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4fe6a1a11d1f2b59e8bb74cfccb9f3188d7c600 --- /dev/null +++ b/utils/test/unittest/common/eventtrance/event_trance_test.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "event_trance_test.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void EventTraceTest::SetUpTestCase(void) +{ +} + +void EventTraceTest::TearDownTestCase(void) +{ +} + +void EventTraceTest::SetUp() +{ +} + +void EventTraceTest::TearDown() +{ +} + +/** + * @tc.name: HiSysEventWriteReleaseMsg_001 + * @tc.desc: Verify the HiSysEventWriteReleaseMsg function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(EventTraceTest, HiSysEventWriteReleaseMsg_001, TestSize.Level0) +{ + std::string status; + int32_t errCode = 0; + std::string msg; + HiSysEventWriteErrCodeMsg(status, OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, errCode, msg); + EXPECT_EQ(true, msg.empty()); +} + +/** + * @tc.name: DHCompMgrTraceStart_001 + * @tc.desc: Verify the DHCompMgrTraceStart function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(EventTraceTest, DHCompMgrTraceStart_001, TestSize.Level0) +{ + std::string anonyNetworkId; + std::string anonyDHId; + std::string msg; + DHCompMgrTraceStart(anonyNetworkId, anonyDHId, msg); + EXPECT_EQ(true, msg.empty()); +} + +/** + * @tc.name: GetDeviceInfo_001 + * @tc.desc: Verify the GetDeviceInfo function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(EventTraceTest, GetDeviceInfo_001, TestSize.Level0) +{ + std::string uuid; + std::string networkId; + DHContext::GetInstance().devInfo_.uuid = "uuid"; + DHContext::GetInstance().GetDeviceInfo(); + uint32_t MAX_ONLINE_DEVICE_SIZE = 10002; + for (uint32_t i = 0; i <= MAX_ONLINE_DEVICE_SIZE; ++i) { + DHContext::GetInstance().onlineDeviceMap_.insert(std::make_pair(std::to_string(i), std::to_string(i))); + DHContext::GetInstance().deviceIdUUIDMap_.insert(std::make_pair(std::to_string(i), std::to_string(i))); + } + DHContext::GetInstance().AddOnlineDevice(uuid, networkId); + DHContext::GetInstance().onlineDeviceMap_.clear(); + DHContext::GetInstance().AddOnlineDevice(uuid, networkId); + EXPECT_EQ(true, uuid.empty()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/test/unittest/common/eventtrance/event_trance_test.h b/utils/test/unittest/common/eventtrance/event_trance_test.h new file mode 100644 index 0000000000000000000000000000000000000000..c5c74609d466bf3b637acae3d787fac756826613 --- /dev/null +++ b/utils/test/unittest/common/eventtrance/event_trance_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_EVENT_TRANCE_TEST_H +#define OHOS_DISTRIBUTED_EVENT_TRANCE_TEST_H + +#include + +#define private public +#include "dh_context.h" +#undef private +#include "dh_utils_hisysevent.h" +#include "dh_utils_hitrace.h" + +namespace OHOS { +namespace DistributedHardware { +class EventTraceTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/utils/test/unittest/common/histreamer_ability_parser/BUILD.gn b/utils/test/unittest/common/histreamer_ability_parser/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0f2046f3f5e8fefabb3ea86c68b25a84c4dbe537 --- /dev/null +++ b/utils/test/unittest/common/histreamer_ability_parser/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/distributedhardware/distributed_hardware_fwk/distributedhardwarefwk.gni") + +module_out_path = "distributed_hardware_fwk/histreamer_ability_parser_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${utils_path}/include", + "${utils_path}/include/log", + "//third_party/json/include", + ] +} + +## UnitTest histreamer_ability_parser_test +ohos_unittest("HistreamerAbilityParserTest") { + module_out_path = module_out_path + + sources = [ "${utils_path}/test/unittest/common/histreamer_ability_parser/histreamer_ability_parser_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${utils_path}:distributedhardwareutils", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ "c_utils:utils" ] +} + +group("histreamer_ability_parser_test") { + testonly = true + deps = [ ":HistreamerAbilityParserTest" ] +} diff --git a/utils/test/unittest/common/histreamer_ability_parser/histreamer_ability_parser_test.cpp b/utils/test/unittest/common/histreamer_ability_parser/histreamer_ability_parser_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05ead7cc2cfd94f9714e1d8ded242a0997f89f48 --- /dev/null +++ b/utils/test/unittest/common/histreamer_ability_parser/histreamer_ability_parser_test.cpp @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "histreamer_ability_parser_test.h" +#include +#include + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +static const std::uint16_t UINT16_ONE = 1; + +static const std::string TEST_STR = "test string"; +static const std::string KEY = "key"; +static const std::string NAME = "name"; +static const std::string MIME = "mime"; +static const std::string INS = "ins"; +static const std::string OUTS = "outs"; +static const std::string AUDIO_ENCODER_NAME = "ffmpegAuEnc_aac"; +static const std::string AUDIO_ENCODERIN_MIME = "audio/raw"; +static const std::string AUDIO_ENCODEROUT_MIME = "audio/mp4a-latm"; +static const std::string AD_MPEG_VER = "ad_mpeg_ver"; +static const std::uint32_t AD_MPEG_VER_VALUE = 4; +static const std::string AUDIO_AAC_PROFILE = "aac_profile"; +static const std::uint32_t AUDIO_AAC_PROFILE_VALUE = 0; +static const std::string AUDIO_AAC_STREAM_FORMAT = "aac_stm_fmt"; + +static const std::string AUDIO_DECODER_NAME = "ffmpegAuDec_aac"; +static const std::string AUDIO_DECODERIN_MIME = "audio/mp4a-latm"; +static const std::string AUDIO_DECODEROUT_MIME = "audio/raw"; + +static const std::string VIDEO_ENCODER_NAME = "HdiCodecAdapter.OMX.rk.video_encoder.hevc"; +static const std::string VIDEO_ENCODERIN_MIME = "video/raw"; +static const std::string VIDEO_ENCODEROUT_MIME = "video/hevc"; + +static const std::string VIDEO_DECODER_NAME = "HdiCodecAdapter.OMX.rk.video_decoder.hevc"; +static const std::string VIDEO_DECODERIN_MIME = "video/hevc"; +static const std::string VIDEO_DECODEROUT_MIME = "video/raw"; + +static const std::string SAMPLE_RATE = "sample_rate"; +static const std::string VIDEO_PIXEL_FMT = "pixel_fmt"; + +void HistreamerAbilityParserTest::SetUpTestCase(void) {} + +void HistreamerAbilityParserTest::TearDownTestCase(void) {} + +void HistreamerAbilityParserTest::SetUp() {} + +void HistreamerAbilityParserTest::TearDown() {} + +/** + * @tc.name: histreamer_ability_parser_test_001 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioEncoderIn &audioEncoderIn) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_001, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioEncoderIn audioEncoderIn; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, audioEncoderIn); + EXPECT_TRUE(audioEncoderIn.mime.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_002 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioEncoderOut &audioEncoderOut) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_002, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioEncoderOut audioEncoderOut; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, audioEncoderOut); + EXPECT_TRUE(audioEncoderOut.mime.empty()); + + jsonObject[MIME] = AUDIO_ENCODEROUT_MIME; + jsonObject[AD_MPEG_VER] = TEST_STR; + FromJson(jsonObject, audioEncoderOut); + EXPECT_EQ(AUDIO_ENCODEROUT_MIME, audioEncoderOut.mime); + + jsonObject[AD_MPEG_VER] = AD_MPEG_VER_VALUE; + jsonObject[AUDIO_AAC_PROFILE] = TEST_STR; + FromJson(jsonObject, audioEncoderOut); + EXPECT_EQ(AD_MPEG_VER_VALUE, (uint32_t)audioEncoderOut.ad_mpeg_ver); + + jsonObject[AUDIO_AAC_PROFILE] = AUDIO_AAC_PROFILE_VALUE; + jsonObject[AUDIO_AAC_STREAM_FORMAT] = TEST_STR; + FromJson(jsonObject, audioEncoderOut); + EXPECT_EQ(AUDIO_AAC_PROFILE_VALUE, (uint32_t)audioEncoderOut.aac_profile); +} + +/** + * @tc.name: histreamer_ability_parser_test_003 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioEncoder &audioEncoder) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_003, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioEncoder audioEncoder; + jsonObject[NAME] = UINT16_ONE; + FromJson(jsonObject, audioEncoder); + EXPECT_TRUE(audioEncoder.name.empty()); + + jsonObject[NAME] = AUDIO_ENCODER_NAME; + FromJson(jsonObject, audioEncoder); + EXPECT_EQ(AUDIO_ENCODER_NAME, audioEncoder.name); + EXPECT_TRUE(audioEncoder.ins.empty()); + + AudioEncoderIn audioEncoderIn; + audioEncoderIn.mime = AUDIO_ENCODERIN_MIME; + audioEncoderIn.sample_rate = {96000, 88200, 64000, 48000, 44100, 32000}; + audioEncoder.ins.push_back(audioEncoderIn); + FromJson(jsonObject, audioEncoder); + EXPECT_FALSE(audioEncoder.ins.empty()); + EXPECT_TRUE(audioEncoder.outs.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_004 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioDecoderIn &audioDecoderIn) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_004, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioDecoderIn audioDecoderIn; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, audioDecoderIn); + EXPECT_TRUE(audioDecoderIn.mime.empty()); + + jsonObject[MIME] = AUDIO_DECODERIN_MIME; + FromJson(jsonObject, audioDecoderIn); + EXPECT_EQ(AUDIO_DECODERIN_MIME, audioDecoderIn.mime); + EXPECT_TRUE(audioDecoderIn.channel_layout.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_005 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioDecoderOut &audioDecoderOut) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_005, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioDecoderOut audioDecoderOut; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, audioDecoderOut); + EXPECT_TRUE(audioDecoderOut.mime.empty()); + + jsonObject[MIME] = AUDIO_DECODEROUT_MIME; + FromJson(jsonObject, audioDecoderOut); + EXPECT_EQ(AUDIO_DECODEROUT_MIME, audioDecoderOut.mime); + EXPECT_TRUE(audioDecoderOut.sample_fmt.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_006 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, AudioDecoder &audioDecoder) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_006, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioDecoder audioDecoder; + jsonObject[NAME] = UINT16_ONE; + FromJson(jsonObject, audioDecoder); + EXPECT_TRUE(audioDecoder.name.empty()); + + jsonObject[NAME] = AUDIO_DECODER_NAME; + FromJson(jsonObject, audioDecoder); + EXPECT_EQ(AUDIO_DECODER_NAME, audioDecoder.name); + EXPECT_TRUE(audioDecoder.ins.empty()); + + AudioDecoderIn audioDecoderIn; + audioDecoderIn.mime = AUDIO_DECODERIN_MIME; + audioDecoderIn.channel_layout = { + AudioChannelLayout::CH_2POINT1, + AudioChannelLayout::CH_2_1, + AudioChannelLayout::SURROUND, + }; + audioDecoder.ins.push_back(audioDecoderIn); + FromJson(jsonObject, audioDecoder); + EXPECT_FALSE(audioDecoder.ins.empty()); + EXPECT_TRUE(audioDecoder.outs.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_007 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoEncoderIn &videoEncoderIn) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_007, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoEncoderIn videoEncoderIn; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, videoEncoderIn); + EXPECT_TRUE(videoEncoderIn.mime.empty()); + + jsonObject[MIME] = VIDEO_ENCODERIN_MIME; + FromJson(jsonObject, videoEncoderIn); + EXPECT_EQ(VIDEO_ENCODERIN_MIME, videoEncoderIn.mime); + EXPECT_TRUE(videoEncoderIn.pixel_fmt.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_008 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoEncoderOut &videoEncoderOut) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_008, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoEncoderOut videoEncoderOut; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, videoEncoderOut); + EXPECT_TRUE(videoEncoderOut.mime.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_009 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoEncoder &videoEncoder) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_009, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoEncoder videoEncoder; + jsonObject[NAME] = UINT16_ONE; + FromJson(jsonObject, videoEncoder); + EXPECT_TRUE(videoEncoder.name.empty()); + + jsonObject[NAME] = VIDEO_ENCODER_NAME; + FromJson(jsonObject, videoEncoder); + EXPECT_EQ(VIDEO_ENCODER_NAME, videoEncoder.name); + EXPECT_TRUE(videoEncoder.ins.empty()); + + VideoEncoderIn videoEncoderIn; + videoEncoderIn.mime = VIDEO_ENCODERIN_MIME; + videoEncoderIn.pixel_fmt = { + VideoPixelFormat::YUV410P, + VideoPixelFormat::RGBA, + }; + videoEncoder.ins.push_back(videoEncoderIn); + FromJson(jsonObject, videoEncoder); + EXPECT_FALSE(videoEncoder.ins.empty()); + EXPECT_TRUE(videoEncoder.outs.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_010 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoDecoderIn &videoDecoderIn) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_010, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoDecoderIn videoDecoderIn; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, videoDecoderIn); + EXPECT_TRUE(videoDecoderIn.mime.empty()); + + jsonObject[MIME] = VIDEO_DECODERIN_MIME; + FromJson(jsonObject, videoDecoderIn); + EXPECT_EQ(VIDEO_DECODERIN_MIME, videoDecoderIn.mime); + EXPECT_TRUE(videoDecoderIn.vd_bit_stream_fmt.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_011 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoDecoderOut &videoDecoderOut) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_011, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoDecoderOut videoDecoderOut; + jsonObject[MIME] = UINT16_ONE; + FromJson(jsonObject, videoDecoderOut); + EXPECT_TRUE(videoDecoderOut.mime.empty()); + + jsonObject[MIME] = VIDEO_DECODEROUT_MIME; + FromJson(jsonObject, videoDecoderOut); + EXPECT_EQ(VIDEO_DECODEROUT_MIME, videoDecoderOut.mime); + EXPECT_TRUE(videoDecoderOut.pixel_fmt.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_012 + * @tc.desc: Verify the FromJson(const nlohmann::json &jsonObject, VideoDecoder &videoDecoder) function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_012, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoDecoder videoDecoder; + jsonObject[NAME] = UINT16_ONE; + FromJson(jsonObject, videoDecoder); + EXPECT_TRUE(videoDecoder.name.empty()); + + jsonObject[NAME] = VIDEO_DECODER_NAME; + FromJson(jsonObject, videoDecoder); + EXPECT_EQ(VIDEO_DECODER_NAME, videoDecoder.name); + EXPECT_TRUE(videoDecoder.ins.empty()); + + VideoDecoderIn videoDecoderIn; + videoDecoderIn.mime = VIDEO_DECODERIN_MIME; + videoDecoderIn.vd_bit_stream_fmt = { + VideoBitStreamFormat::AVC1, + VideoBitStreamFormat::HEVC, + }; + videoDecoder.ins.push_back(videoDecoderIn); + FromJson(jsonObject, videoDecoder); + EXPECT_FALSE(videoDecoder.ins.empty()); + EXPECT_TRUE(videoDecoder.outs.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_013 + * @tc.desc: Verify the FromJson function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_013, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioEncoder audioEncoder; + jsonObject[NAME] = AUDIO_ENCODER_NAME; + audioEncoder.name = AUDIO_ENCODER_NAME; + std::vectoraudioEncoders; + + FromJson(VIDEO_PIXEL_FMT, jsonObject, audioEncoders); + EXPECT_TRUE(audioEncoders.empty()); + + FromJson(NAME, jsonObject, audioEncoders); + EXPECT_FALSE(audioEncoders.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_014 + * @tc.desc: Verify the FromJson function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_014, TestSize.Level0) +{ + nlohmann::json jsonObject; + AudioDecoder audioDecoder; + jsonObject[NAME] = AUDIO_DECODER_NAME; + audioDecoder.name = AUDIO_DECODER_NAME; + std::vectoraudioDecoders; + + FromJson(VIDEO_PIXEL_FMT, jsonObject, audioDecoders); + EXPECT_TRUE(audioDecoders.empty()); + + FromJson(NAME, jsonObject, audioDecoders); + EXPECT_FALSE(audioDecoders.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_015 + * @tc.desc: Verify the FromJson function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_015, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoEncoder videoEncoder; + jsonObject[NAME] = VIDEO_ENCODER_NAME; + videoEncoder.name = VIDEO_ENCODER_NAME; + std::vectorvideoEncoders; + + FromJson(AUDIO_AAC_PROFILE, jsonObject, videoEncoders); + EXPECT_TRUE(videoEncoders.empty()); + + FromJson(NAME, jsonObject, videoEncoders); + EXPECT_FALSE(videoEncoders.empty()); +} + +/** + * @tc.name: histreamer_ability_parser_test_016 + * @tc.desc: Verify the FromJson function + * @tc.type: FUNC + * @tc.require: issuelI7MJPJ + */ +HWTEST_F(HistreamerAbilityParserTest, histreamer_ability_parser_test_016, TestSize.Level0) +{ + nlohmann::json jsonObject; + VideoDecoder videoDecoder; + jsonObject[NAME] = VIDEO_DECODER_NAME; + videoDecoder.name = VIDEO_DECODER_NAME; + std::vectorvideoDecoders; + + FromJson(AUDIO_AAC_PROFILE, jsonObject, videoDecoders); + EXPECT_TRUE(videoDecoders.empty()); + + FromJson(NAME, jsonObject, videoDecoders); + EXPECT_FALSE(videoDecoders.empty()); +} + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/test/unittest/common/histreamer_ability_parser/histreamer_ability_parser_test.h b/utils/test/unittest/common/histreamer_ability_parser/histreamer_ability_parser_test.h new file mode 100644 index 0000000000000000000000000000000000000000..65d7279ddcb84385715567a5b74606cd828d15aa --- /dev/null +++ b/utils/test/unittest/common/histreamer_ability_parser/histreamer_ability_parser_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_HISTREAMER_ABILITY_PARSER_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_HISTREAMER_ABILITY_PARSER_TEST_H + +#include "histreamer_ability_parser.h" +#include "nlohmann/json.hpp" +#include +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class HistreamerAbilityParserTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif \ No newline at end of file diff --git a/utils/test/unittest/common/utilstool/BUILD.gn b/utils/test/unittest/common/utilstool/BUILD.gn index 2371d935b35b2d8a5563dbbea693cd875d311a60..7b15eecf5a425c8f814fdc648930407666e45fb3 100644 --- a/utils/test/unittest/common/utilstool/BUILD.gn +++ b/utils/test/unittest/common/utilstool/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -24,7 +24,7 @@ config("module_private_config") { "${utils_path}/include", "${utils_path}/include/log", "${common_path}/utils/include", - "//commonlibrary/c_utils/base/include", + "//third_party/json/include", ] } @@ -38,9 +38,11 @@ ohos_unittest("UtilsToolTest") { configs = [ ":module_private_config" ] deps = [ - "//foundation/distributedhardware/distributed_hardware_fwk/utils:distributedhardwareutils", + "${utils_path}:distributedhardwareutils", "//third_party/googletest:gtest_main", ] + + external_deps = [ "c_utils:utils" ] } group("utils_tool_test") { diff --git a/utils/test/unittest/common/utilstool/utils_tool_test.cpp b/utils/test/unittest/common/utilstool/utils_tool_test.cpp index b8981972b12e9b0bb773b8b36cd2d6321d97730a..e43067bf0cc72186ebe9492fc97eeae8c31bd66e 100644 --- a/utils/test/unittest/common/utilstool/utils_tool_test.cpp +++ b/utils/test/unittest/common/utilstool/utils_tool_test.cpp @@ -120,5 +120,44 @@ HWTEST_F(UtilsToolTest, utils_tool_test_004, TestSize.Level0) ASSERT_STRNE(std::to_string(i4).c_str(), GetAnonyInt32(i4).c_str()); ASSERT_STRNE(std::to_string(i5).c_str(), GetAnonyInt32(i5).c_str()); } + +/** + * @tc.name: utils_tool_test_005 + * @tc.desc: Verify the GetUUIDBySoftBus function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(UtilsToolTest, utils_tool_test_005, TestSize.Level0) +{ + std::string networkId = ""; + std::string ret = GetUUIDBySoftBus(networkId); + EXPECT_EQ(0, ret.size()); +} + +/** + * @tc.name: utils_tool_test_006 + * @tc.desc: Verify the GetDeviceIdByUUID function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(UtilsToolTest, utils_tool_test_006, TestSize.Level0) +{ + std::string uuidEmpty = ""; + std::string ret = GetDeviceIdByUUID(uuidEmpty); + ASSERT_EQ(0, ret.size()); +} + +/** + * @tc.name: utils_tool_test_007 + * @tc.desc: Verify the GetDeviceIdByUUID function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(UtilsToolTest, utils_tool_test_007, TestSize.Level0) +{ + std::string uuid = "bb536a637105409e904d4da78290ab1"; + std::string ret = GetDeviceIdByUUID(uuid); + ASSERT_NE(0, ret.size()); +} } // namespace DistributedHardware } // namespace OHOS