diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e454a52586f29b8ce8a6799163eac1f875e9ac01 --- /dev/null +++ b/LICENSE @@ -0,0 +1,178 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + diff --git a/OAT.xml b/OAT.xml new file mode 100644 index 0000000000000000000000000000000000000000..c18b31e0f12e182059756552ea2d9d0b42600f88 --- /dev/null +++ b/OAT.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + diff --git a/README.en.md b/README.en.md deleted file mode 100644 index 702c1b79d3890a74f90650dd6fb2e461f8271e01..0000000000000000000000000000000000000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# distributed_camera - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md deleted file mode 100644 index 9e662c7bae5054347b599092bedd552cb5942e31..0000000000000000000000000000000000000000 --- a/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# distributed_camera - -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} - -#### 软件架构 -软件架构说明 - - -#### 安装教程 - -1. xxxx -2. xxxx -3. xxxx - -#### 使用说明 - -1. xxxx -2. xxxx -3. xxxx - -#### 参与贡献 - -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request - - -#### 特技 - -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README_ZH.md b/README_ZH.md new file mode 100644 index 0000000000000000000000000000000000000000..39f17d5bfa6f9c26d43bac715514e299b1f19798 --- /dev/null +++ b/README_ZH.md @@ -0,0 +1,70 @@ +# **分布式相机组件** + +## **简介** + +分布式相机是多个设备的相机同时协同使用的能力。分布式相机组件是为分布式硬件子系统提供这一能力的组件。本组件不直接对接应用,只向分布式硬件框架子系统提供C++接口。应用可以通过相机框架的接口使用分布式相机组件操作其他设备的Camera,使用方式与本地相机一致。 + +其系统架构图如下图所示: + +![](figures/distributedcamera_arch.png) + +**分布式相机接口(DistributedCameraSDK)**:为分布式硬件管理框架提供超级终端虚拟Camera使能/去使能能力,以及相机状态。 + +**分布式相机主控端生命周期管理(DistributedCameraSourceMgr)**:通过状态机管理主控端Camera状态,负责主控端相关对象的创建销毁,以及两端的参数协商。 + +**分布式相机被控端生命周期管理(DistributedCameraSinkMgr)**:管理被控端Camera状态,负责被控端相关对象的创建销毁,以及两端的参数协商。 + +**通道模块(Channel)**:通过软总线连接主控端与被控端,接收发送主控端的相机指令或被控端的图像信息。 + +**数据处理器(DataProcess)**:对相机框架返回的图像数据做处理(编解码、色彩空间转换、分辨率缩放、帧率调整,角度调整等)。 + +**分布式相机客户端(CameraClient)**:被控端调用多媒体接口查询操作本地相机(查询相机数量及相关信息;打开、关闭、获取流等操作)。 + +**虚拟相机HDF层实现(VirtualCameraHdf)**:在HDF层建立的虚拟Camera硬件,能够被多媒体框架发现和加载,像使用本地的Camera一样被使用 + +## **目录** + +``` +/foundation/distributedhardware/distributedcamera +├── camera_hdf # 分布式相机HAL功能 +├── common # 分布式相机公共模块 +├── interfaces # 分布式相机对外接口模块 +├── sa_profile # 分布式相机SA配置模块 +├── services # 服务模块 +│ └── cameraservice # 相机服务模块 +│ ├── base # 分布式相机两端公共部分 +│ ├── cameraoperator # 分布式相机相机操作模块 +│ ├── sinkservice # 分布式相机被控端服务模块 +│ └── sourceservice # 分布式相机主控端服务模块 +│ ├── channel # 分布式相机通道模块 +│ └── data_process # 分布式相机数据处理模块 +``` + +## **约束** +**语言限制**:C++语言。 +**组网环境**:必须确保设备在同一个局域网中。 +**操作系统限制**:OpenHarmony操作系统。 + +## **说明** +### **概念说明** +#### 主控端(source):控制端,通过调用分布式相机能力,使用被控端的摄像头进行预览、拍照、录像等功能。 +#### 被控端(sink):被控制端,通过分布式相机接收主控端的命令,使用本地摄像头为主控端提供图像数据。 +#### Metadata:又叫元数据,是用于控制相机各种属性的参数。 + +### **接口说明** +分布式相机组件实现分布式硬件管理框架提供的接口,分布式硬件管理框架统一调用接口实现虚拟硬件驱动注册等功能。 + +### **业务流程说明** +#### **1. 设备开机启动** +系统拉起分布式相机的SA服务,Source侧被初始化,相关模块被初始化。 + +#### **2. 设备组网上线** +设备上线后,分布式硬件管理框架同步到上线设备的相机硬件信息并使能,使能成功后在系统中会新增分布式相机驱动并通知到相机框架,相机框架统一管理本地相机和分布式相机驱动;上层应用通过相机框架接口可以查询到分布式相机,并按照和本地相机相同的接口使用分布式相机。 + +#### **3. 设备下线** +设备下线后,分布式硬件管理框架去使能下线设备的相机硬件,本地移除分布式相机驱动并通知到相机框架,此时下线设备的分布式相机不可用。 + +## **涉及仓** +**** +**分布式相机** +[distributed_camera](https://gitee.com/openharmony/distributed_camera) \ No newline at end of file diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..dfcb1b63a2162bcc8776a523bd4084b53896abd4 --- /dev/null +++ b/bundle.json @@ -0,0 +1,96 @@ +{ + "name":"@ohos/distributed_camera", + "description":"distributed hardware camera", + "version":"3.1", + "author":{}, + "repository":"https://gitee.com/openharmony/distributed_camera", + "license":"Apache License 2.0", + "publishAs":"code-segment", + "segment":{ + "destPath":"foundation/distributedhardware/distributedcamera/" + }, + "dirs":{}, + "scripts":{}, + "component":{ + "name":"distributed_camera", + "subsystem":"distributedhardware", + "syscap":[ + "SystemCapability.distributedhardware.distributed_camera" + ], + "features":[], + "adapted_system_type":[ + "standard" + ], + "rom":"2000k", + "ram":"6M", + "deps":{ + "components":[ + "appexecfwk_standard", + "eventhandler", + "hiviewdfx_hilog_native", + "ipc", + "safwk", + "samgr_standard", + "dsoftbus_standard", + "utils_base", + "graphic_standard", + "distributed_hardware_fwk", + "multimedia_camera_standard", + "multimedia_media_standard", + "hdf", + "hidl_adapter" + ], + "third_party":[ + "jsoncpp", + "googletest" + ] + }, + "build":{ + "sub_component":[ + "//foundation/distributedhardware/distributedcamera/common:distributed_camera_utils", + "//foundation/distributedhardware/distributedcamera/interfaces/inner_kits/native_cpp/camera_sink:distributed_camera_sink_sdk", + "//foundation/distributedhardware/distributedcamera/interfaces/inner_kits/native_cpp/camera_source:distributed_camera_source_sdk", + "//foundation/distributedhardware/distributedcamera/services/cameraservice/cameraoperator/client:distributed_camera_client", + "//foundation/distributedhardware/distributedcamera/services/cameraservice/cameraoperator/handler:distributed_camera_handler", + "//foundation/distributedhardware/distributedcamera/services/cameraservice/sinkservice:distributed_camera_sink", + "//foundation/distributedhardware/distributedcamera/services/cameraservice/sourceservice:distributed_camera_source", + "//foundation/distributedhardware/distributedcamera/services/data_process:distributed_camera_data_process", + "//foundation/distributedhardware/distributedcamera/sa_profile:dcamera_sa_profile", + "//foundation/distributedhardware/distributedcamera/services/channel:distributed_camera_channel", + "//foundation/distributedhardware/distributedcamera/camera_hdf/interfaces/hdi_ipc/config/host:distributed_camera_host_config", + "//foundation/distributedhardware/distributedcamera/camera_hdf/interfaces/hdi_ipc/config/provider:distributed_camera_provider_config", + "//foundation/distributedhardware/distributedcamera/camera_hdf/interfaces/hdi_ipc/client:distributed_camera_hdf_client", + "//foundation/distributedhardware/distributedcamera/camera_hdf/hdi_impl:distributed_camera_hdf" + ], + "inner_kits":[ + { + "type":"so", + "name":"//foundation/distributedhardware/distributedcamera/interfaces/inner_kits/native_cpp/camera_sink:distributed_camera_sink_sdk", + "header":{ + "header_base":"//foundation/distributedhardware/distributedcamera/interfaces/inner_kits/native_cpp/camera_sink/include", + "header_files":[ + "idistributed_camera_sink.h" + ] + } + }, + { + "type":"so", + "name":"//foundation/distributedhardware/distributedcamera/interfaces/inner_kits/native_cpp/camera_source:distributed_camera_source_sdk", + "header":{ + "header_base":"//foundation/distributedhardware/distributedcamera/interfaces/inner_kits/native_cpp/camera_source/include", + "header_files":[ + "idistributed_camera_source.h" + ] + } + } + ], + "test":[ + "//foundation/distributedhardware/distributedcamera/services/cameraservice/cameraoperator/client/test/unittest:camera_client_test", + "//foundation/distributedhardware/distributedcamera/services/cameraservice/cameraoperator/handler/test/unittest:camera_handler_test", + "//foundation/distributedhardware/distributedcamera/services/cameraservice/sinkservice/test/unittest:sink_service_test", + "//foundation/distributedhardware/distributedcamera/services/cameraservice/sourceservice/test/unittest:source_service_test", + "//foundation/distributedhardware/distributedcamera/services/cameraservice/base/test/unittest:services_base_test" + ] + } + } +} \ No newline at end of file diff --git a/camera_hdf/hdi_impl/BUILD.gn b/camera_hdf/hdi_impl/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9e152f18adde15e7b4479cb30afec3c64b96ce17 --- /dev/null +++ b/camera_hdf/hdi_impl/BUILD.gn @@ -0,0 +1,108 @@ +# 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. + +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_hdf") { + include_dirs = [ + "include/dcamera_device", + "include/dcamera_host", + "include/dcamera_provider", + "include/dstream_operator", + "include/utils", + "../interfaces/include", + "../interfaces/hdi_ipc", + "../interfaces/hdi_ipc/server/device", + "../interfaces/hdi_ipc/server/host", + "../interfaces/hdi_ipc/server/operator", + "../interfaces/hdi_ipc/server/provider", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${common_path}/include/utils", + "${common_path}/include/constants", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include/", + "${fwk_utils_path}/include", + "${fwk_utils_path}/include/log", + "${camera_hdf_path}/camera/interfaces/include", + "${camera_hdf_path}/gralloc/src/adapter", + "${display_hdf_path}/interfaces/include", + "${hdf_framework_path}/include/utils", + "${hdf_framework_path}/include/core", + "${hdf_framework_path}/include/osal", + "${hdf_uhdf_path}/include/hdi", + "${hdf_uhdf_path}/osal/include", + "${hdf_uhdf_path}/ipc/include", + "${hdf_uhdf_path}/include/host", + "//third_party/jsoncpp/include", + + #producer + "//foundation/graphic/standard/frameworks/surface/include", + "//foundation/graphic/standard/interfaces/kits/surface", + "//foundation/graphic/standard/utils/include", + "//foundation/communication/ipc/ipc/native/src/core/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/multimedia/camera_standard/frameworks/native/metadata/include", + ] + + sources = [ + "../interfaces/hdi_ipc/server/device/dcamera_device_callback_proxy.cpp", + "../interfaces/hdi_ipc/server/device/dcamera_device_stub.cpp", + "../interfaces/hdi_ipc/server/host/dcamera_host_callback_proxy.cpp", + "../interfaces/hdi_ipc/server/host/dcamera_host_stub.cpp", + "../interfaces/hdi_ipc/server/operator/doffline_stream_operator_stub.cpp", + "../interfaces/hdi_ipc/server/operator/dstream_operator_callback_proxy.cpp", + "../interfaces/hdi_ipc/server/operator/dstream_operator_stub.cpp", + "../interfaces/hdi_ipc/server/provider/dcamera_provider_callback_proxy.cpp", + "../interfaces/hdi_ipc/server/provider/dcamera_provider_stub.cpp", + "src/dcamera_device/dcamera_device.cpp", + "src/dcamera_device/dmetadata_processor.cpp", + "src/dcamera_host/dcamera_host.cpp", + "src/dcamera_provider/dcamera_provider.cpp", + "src/dstream_operator/doffline_stream_operator.cpp", + "src/dstream_operator/dstream_operator.cpp", + "src/dstream_operator/dbuffer_manager.cpp", + "src/dstream_operator/dimage_buffer.cpp", + "src/dstream_operator/dcamera_steam.cpp", + "src/utils/dcamera.cpp" + ] + + deps = [ + "//utils/native/base:utils", + "${common_path}:distributed_camera_utils", + "${fwk_utils_path}:distributedhardwareutils", + "//drivers/adapter/uhdf2/ipc:libhdf_ipc_adapter", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + "//foundation/graphic/standard/frameworks/surface:surface", + "//drivers/peripheral/display/hal:hdi_display_gralloc", + "//foundation/multimedia/camera_standard/frameworks/native/metadata:metadata", + "//third_party/jsoncpp:jsoncpp", + "${camera_hdf_path}/gralloc/src/adapter:libgralloc_adapter", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"distributedcamerahdf\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} diff --git a/camera_hdf/hdi_impl/include/dcamera_device/dcamera_device.h b/camera_hdf/hdi_impl/include/dcamera_device/dcamera_device.h new file mode 100644 index 0000000000000000000000000000000000000000..9a42c19f900dd71b8d8b6a11295785191b40d748 --- /dev/null +++ b/camera_hdf/hdi_impl/include/dcamera_device/dcamera_device.h @@ -0,0 +1,84 @@ +/* + * 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 DISTRIBUTED_CAMERA_DEVICE_H +#define DISTRIBUTED_CAMERA_DEVICE_H + +#include +#include +#include "dcamera_device_stub.h" +#include "dmetadata_processor.h" +#include "dstream_operator.h" +#include "icamera_device_callback.h" +#include "idistributed_camera_provider_callback.h" +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraDevice : public DCameraDeviceStub { +public: + DCameraDevice(const std::shared_ptr &dhBase, const std::string &abilityInfo); + DCameraDevice() = default; + virtual ~DCameraDevice() = default; + DCameraDevice(const DCameraDevice &other) = delete; + DCameraDevice(DCameraDevice &&other) = delete; + DCameraDevice& operator=(const DCameraDevice &other) = delete; + DCameraDevice& operator=(DCameraDevice &&other) = delete; + +public: + CamRetCode GetStreamOperator(const OHOS::sptr &callback, + OHOS::sptr &streamOperator) override; + CamRetCode UpdateSettings(const std::shared_ptr &settings) override; + CamRetCode SetResultMode(const ResultCallbackMode &mode) override; + CamRetCode GetEnabledResults(std::vector &results) override; + CamRetCode EnableResult(const std::vector &results) override; + CamRetCode DisableResult(const std::vector &results) override; + void Close() override; + + CamRetCode OpenDCamera(const OHOS::sptr &callback); + CamRetCode GetDCameraAbility(std::shared_ptr &ability); + DCamRetCode AcquireBuffer(int streamId, std::shared_ptr &buffer); + DCamRetCode ShutterBuffer(int streamId, const std::shared_ptr &buffer); + DCamRetCode OnSettingsResult(const std::shared_ptr &result); + DCamRetCode Notify(const std::shared_ptr &event); + void SetProviderCallback(const OHOS::sptr &callback); + OHOS::sptr GetProviderCallback(); + std::string GetDCameraId(); + bool IsOpened(); + +private: + void Init(const std::string &abilityInfo); + DCamRetCode CreateDStreamOperator(); + std::string GenerateCameraId(const std::shared_ptr &dhBase); + +private: + bool isOpened_; + std::string dCameraId_; + std::shared_ptr dhBase_; + std::string dCameraAbilityInfo_; + OHOS::sptr dCameraDeviceCallback_; + OHOS::sptr dCameraProviderCallback_; + OHOS::sptr dCameraStreamOperator_; + std::shared_ptr dMetadataProcessor_; + + std::mutex openSesslock_; + std::condition_variable openSessCV_; + bool isOpenSessFailed_ = false; + std::mutex isOpenSessFailedlock_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +#endif // DISTRIBUTED_CAMERA_DEVICE_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/include/dcamera_device/dmetadata_processor.h b/camera_hdf/hdi_impl/include/dcamera_device/dmetadata_processor.h new file mode 100644 index 0000000000000000000000000000000000000000..e51023984680f9c82d4fe4c9016945ad926f4e4c --- /dev/null +++ b/camera_hdf/hdi_impl/include/dcamera_device/dmetadata_processor.h @@ -0,0 +1,81 @@ +/* + * 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 DISTRIBUTED_CAMERA_METADATA_PROCESSOR_H +#define DISTRIBUTED_CAMERA_METADATA_PROCESSOR_H + +#include +#include +#include +#include "constants.h" +#include "dcamera.h" +#include +#include + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DMetadataProcessor { +public: + DMetadataProcessor() = default; + ~DMetadataProcessor() = default; + DMetadataProcessor(const DMetadataProcessor &other) = delete; + DMetadataProcessor(DMetadataProcessor &&other) = delete; + DMetadataProcessor& operator=(const DMetadataProcessor &other) = delete; + DMetadataProcessor& operator=(DMetadataProcessor &&other) = delete; + +public: + DCamRetCode InitDCameraAbility(const std::string &abilityInfo); + DCamRetCode GetDCameraAbility(std::shared_ptr &ability); + DCamRetCode SetMetadataResultMode(const ResultCallbackMode &mode); + DCamRetCode GetEnabledMetadataResults(std::vector &results); + DCamRetCode EnableMetadataResult(const std::vector &results); + DCamRetCode DisableMetadataResult(const std::vector &results); + DCamRetCode ResetEnableResults(); + DCamRetCode SaveResultMetadata(std::string resultStr); + DCamRetCode UpdateResultMetadata(bool &needReturn, std::shared_ptr &result); + void PrintDCameraMetadata(const common_metadata_header_t *metadata); + +private: + DCamRetCode InitDCameraDefaultAbilityKeys(const std::string &abilityInfo); + DCamRetCode InitDCameraOutputAbilityKeys(const std::string &abilityInfo); + DCamRetCode AddAbilityEntry(uint32_t tag, const void *data, size_t size); + DCamRetCode UpdateAbilityEntry(uint32_t tag, const void *data, size_t size); + void ConvertToCameraMetadata(common_metadata_header_t *&input, + std::shared_ptr &output); + void ResizeMetadataHeader(common_metadata_header_t *header, uint32_t itemCapacity, uint32_t dataCapacity); + uint32_t GetDataSize(uint32_t type); + std::map> GetDCameraSupportedFormats(const std::string &abilityInfo); + +private: + std::shared_ptr dCameraAbility_; + std::string protocolVersion_; + std::string dCameraPosition_; + DCResolution maxPreviewResolution_; + DCResolution maxPhotoResolution_; + ResultCallbackMode metaResultMode_; + std::set allResultSet_; + std::set enabledResultSet_; + + // The latest result metadata that received from the sink device. + common_metadata_header_t *latestProducerResultMetadata_; + + // The latest result metadata that replied to the camera service. + common_metadata_header_t *latestConsumerResultMetadata_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +#endif // DISTRIBUTED_CAMERA_METADATA_PROCESSOR_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/include/dcamera_host/dcamera_host.h b/camera_hdf/hdi_impl/include/dcamera_host/dcamera_host.h new file mode 100644 index 0000000000000000000000000000000000000000..603ad354d0cb2042b9133c617e49ddb4ac9ce722 --- /dev/null +++ b/camera_hdf/hdi_impl/include/dcamera_host/dcamera_host.h @@ -0,0 +1,77 @@ +/* + * 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 DISTRIBUTED_CAMERA_HOST_H +#define DISTRIBUTED_CAMERA_HOST_H + +#include "dcamera.h" +#include "dcamera_device.h" +#include "icamera_device.h" +#include "icamera_host_callback.h" +#include "icamera_device_callback.h" +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class DCameraHost { +public: + DCameraHost() = default; + virtual ~DCameraHost() = default; + DCameraHost(const DCameraHost &other) = delete; + DCameraHost(DCameraHost &&other) = delete; + DCameraHost& operator=(const DCameraHost &other) = delete; + DCameraHost& operator=(DCameraHost &&other) = delete; + +public: + static std::shared_ptr GetInstance(); + CamRetCode SetCallback(const OHOS::sptr &callback); + CamRetCode GetCameraIds(std::vector &cameraIds); + CamRetCode GetCameraAbility(const std::string &cameraId, std::shared_ptr &ability); + CamRetCode OpenCamera(const std::string &cameraId, const OHOS::sptr &callback, + OHOS::sptr &pDevice); + CamRetCode SetFlashlight(const std::string &cameraId, bool &isEnable); + + DCamRetCode AddDCameraDevice(const std::shared_ptr &dhBase, const std::string &abilityInfo, + const sptr &callback); + DCamRetCode RemoveDCameraDevice(const std::shared_ptr &dhBase); + OHOS::sptr GetDCameraDeviceByDHBase(const std::shared_ptr &dhBase); + void NotifyDCameraStatus(const std::shared_ptr &dhBase, int32_t result); + +private: + bool IsCameraIdInvalid(const std::string &cameraId); + std::string GetCameraIdByDHBase(const std::shared_ptr &dhBase); + +private: + class AutoRelease { + public: + AutoRelease() {}; + ~AutoRelease() + { + if (DCameraHost::instance_ != nullptr) { + DCameraHost::instance_ = nullptr; + } + }; + }; + static AutoRelease autoRelease_; + static std::shared_ptr instance_; + + OHOS::sptr dCameraHostCallback_; + std::map dhBaseHashDCamIdMap_; + std::map> dCameraDeviceMap_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_HOST_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/include/dcamera_provider/dcamera_provider.h b/camera_hdf/hdi_impl/include/dcamera_provider/dcamera_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..24fe1d21e1860194c75fc4b889584162461a1e49 --- /dev/null +++ b/camera_hdf/hdi_impl/include/dcamera_provider/dcamera_provider.h @@ -0,0 +1,79 @@ +/* + * 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 DISTRIBUTED_CAMERA_PROVIDER_H +#define DISTRIBUTED_CAMERA_PROVIDER_H + +#include "dcamera.h" +#include "idistributed_camera_provider_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraHost; +class DCameraDevice; +class DCameraProvider { +public: + DCameraProvider() = default; + virtual ~DCameraProvider() = default; + DCameraProvider(const DCameraProvider &other) = delete; + DCameraProvider(DCameraProvider &&other) = delete; + DCameraProvider& operator=(const DCameraProvider &other) = delete; + DCameraProvider& operator=(DCameraProvider &&other) = delete; + +public: + static std::shared_ptr GetInstance(); + DCamRetCode EnableDCameraDevice(const std::shared_ptr &dhBase, const std::string &abilitySet, + const sptr &callback); + DCamRetCode DisableDCameraDevice(const std::shared_ptr &dhBase); + DCamRetCode AcquireBuffer(const std::shared_ptr &dhBase, int streamId, + std::shared_ptr &buffer); + DCamRetCode ShutterBuffer(const std::shared_ptr &dhBase, int streamId, + const std::shared_ptr &buffer); + DCamRetCode OnSettingsResult(const std::shared_ptr &dhBase, const std::shared_ptr &result); + DCamRetCode Notify(const std::shared_ptr &dhBase, const std::shared_ptr &event); + + DCamRetCode OpenSession(const std::shared_ptr &dhBase); + DCamRetCode CloseSession(const std::shared_ptr &dhBase); + DCamRetCode ConfigureStreams(const std::shared_ptr &dhBase, + const std::vector> &streamInfos); + DCamRetCode ReleaseStreams(const std::shared_ptr &dhBase, const std::vector &streamIds); + DCamRetCode StartCapture(const std::shared_ptr &dhBase, + const std::vector> &captureInfos); + DCamRetCode StopCapture(const std::shared_ptr &dhBase); + DCamRetCode UpdateSettings(const std::shared_ptr &dhBase, + const std::vector> &settings); + +private: + bool IsDhBaseInfoInvalid(const std::shared_ptr &dhBase); + sptr GetCallbackBydhBase(const std::shared_ptr &dhBase); + OHOS::sptr GetDCameraDevice(const std::shared_ptr &dhBase); + +private: + class AutoRelease { + public: + AutoRelease() {}; + ~AutoRelease() + { + if (DCameraProvider::instance_ != nullptr) { + DCameraProvider::instance_ = nullptr; + } + }; + }; + static AutoRelease autoRelease_; + static std::shared_ptr instance_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_PROVIDER_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/include/dstream_operator/dbuffer_manager.h b/camera_hdf/hdi_impl/include/dstream_operator/dbuffer_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..a07d671d6fc19352b00d5202768005aa2bf5b342 --- /dev/null +++ b/camera_hdf/hdi_impl/include/dstream_operator/dbuffer_manager.h @@ -0,0 +1,58 @@ +/* + * 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 DISTRIBUTED_CAMERA_BUFFER_MANAGER_H +#define DISTRIBUTED_CAMERA_BUFFER_MANAGER_H + +#include +#include +#include "constants.h" +#include "display_type.h" +#include +#include "dimage_buffer.h" +#include "surface.h" + +namespace OHOS { +namespace DistributedHardware { +class DBufferManager { +public: + DBufferManager() = default; + virtual ~DBufferManager() = default; + DBufferManager(const DBufferManager &other) = delete; + DBufferManager(DBufferManager &&other) = delete; + DBufferManager& operator=(const DBufferManager &other) = delete; + DBufferManager& operator=(DBufferManager &&other) = delete; + +public: + std::shared_ptr AcquireBuffer(); + RetCode AddBuffer(std::shared_ptr& buffer); + RetCode RemoveBuffer(std::shared_ptr& buffer); + void NotifyStop(bool state); + static RetCode SurfaceBufferToDImageBuffer(const OHOS::sptr &surfaceBuffer, + const std::shared_ptr &buffer); + static RetCode DImageBufferToDCameraBuffer(const std::shared_ptr &imageBuffer, + std::shared_ptr &buffer); + static uint64_t CameraUsageToGrallocUsage(const uint64_t cameraUsage); + static uint32_t PixelFormatToDCameraFormat(const PixelFormat format); + +private: + std::mutex lock_; + std::atomic_bool streamStop_ = false; + std::list> idleList_ = {}; + std::list> busyList_ = {}; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_BUFFER_MANAGER_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/include/dstream_operator/dcamera_steam.h b/camera_hdf/hdi_impl/include/dstream_operator/dcamera_steam.h new file mode 100644 index 0000000000000000000000000000000000000000..703ae26459ece2371dede93ccbcdcdc80b935946 --- /dev/null +++ b/camera_hdf/hdi_impl/include/dstream_operator/dcamera_steam.h @@ -0,0 +1,69 @@ +/* + * 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 DISTRIBUTED_CAMERA_STREAM_H +#define DISTRIBUTED_CAMERA_STREAM_H + +#include "surface.h" +#include "dimage_buffer.h" +#include "dbuffer_manager.h" +#include +#include + +namespace OHOS { +namespace DistributedHardware { +using namespace std; +using namespace OHOS::Camera; +class DCameraStream { +public: + DCameraStream() = default; + ~DCameraStream() = default; + DCameraStream(const DCameraStream &other) = delete; + DCameraStream(DCameraStream &&other) = delete; + DCameraStream &operator=(const DCameraStream &other) = delete; + DCameraStream &operator=(DCameraStream &&other) = delete; + +public: + DCamRetCode InitDCameraStream(const shared_ptr &info); + DCamRetCode GetDCameraStreamInfo(shared_ptr &info); + DCamRetCode SetDCameraBufferQueue(const OHOS::sptr producer); + DCamRetCode ReleaseDCameraBufferQueue(); + DCamRetCode GetDCameraStreamAttribute(shared_ptr &attribute); + DCamRetCode GetDCameraBuffer(shared_ptr &buffer); + DCamRetCode ReturnDCameraBuffer(const shared_ptr &buffer); + DCamRetCode FlushDCameraBuffer(); + DCamRetCode FinishCommitStream(); + bool HasBufferQueue(); + +private: + DCamRetCode InitDCameraBufferManager(); + DCamRetCode GetNextRequest(); + +private: + int32_t index_ = -1; + int dcStreamId_; + shared_ptr dcStreamInfo_ = nullptr; + shared_ptr dcStreamAttribute_ = nullptr; + shared_ptr dcStreamBufferMgr_ = nullptr; + OHOS::sptr dcStreamProducer_ = nullptr; + map, tuple, int, int>> bufferConfigMap_; + mutex lock_; + condition_variable cv_; + int captureBufferCount_ = 0; + bool isBufferMgrInited_ = false; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_STREAM_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/include/dstream_operator/dimage_buffer.h b/camera_hdf/hdi_impl/include/dstream_operator/dimage_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..00cd31c1aaa92a836b6f4eeb866f49e0d3553b9a --- /dev/null +++ b/camera_hdf/hdi_impl/include/dstream_operator/dimage_buffer.h @@ -0,0 +1,89 @@ +/* + * 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 DISTRIBUTED_CAMERA_IMAGE_BUFFER_H +#define DISTRIBUTED_CAMERA_IMAGE_BUFFER_H + +#include +#include "constants.h" +#include "distributed_camera_constants.h" + +namespace OHOS { +namespace DistributedHardware { +class DImageBuffer { +public: + DImageBuffer() = default; + virtual ~DImageBuffer(); + + int32_t GetIndex() const; + uint32_t GetWidth() const; + uint32_t GetHeight() const; + uint32_t GetStride() const; + int32_t GetFormat() const; + uint32_t GetSize() const; + uint64_t GetUsage() const; + uint64_t GetPhyAddress() const; + int32_t GetFileDescriptor() const; + uint64_t GetTimestamp() const; + uint64_t GetFrameNumber() const; + int32_t GetCaptureId() const; + bool GetValidFlag() const; + int32_t GetFenceId() const; + int32_t GetEncodeType() const; + BufferHandle* GetBufferHandle() const; + + void SetIndex(const int32_t index); + void SetWidth(const uint32_t width); + void SetHeight(const uint32_t height); + void SetStride(const uint32_t stride); + void SetFormat(const int32_t format); + void SetSize(const uint32_t size); + void SetUsage(const uint64_t usage); + void SetPhyAddress(const uint64_t addr); + void SetFileDescriptor(const int32_t fd); + void SetTimestamp(const uint64_t timestamp); + void SetFrameNumber(const uint64_t frameNumber); + void SetCaptureId(const int32_t id); + void SetValidFlag(const bool flag); + void SetFenceId(const int32_t fence); + void SetEncodeType(const int32_t type); + void SetBufferHandle(const BufferHandle* bufHandle); + + void Free(); + bool operator==(const DImageBuffer& u); + +private: + int32_t index_ = -1; + uint32_t width_ = 0; + uint32_t height_ = 0; + uint32_t stride_ = 0; + uint32_t format_ = OHOS_CAMERA_FORMAT_INVALID; + uint32_t size_ = 0; + uint64_t usage_ = 0; + uint64_t phyAddr_ = 0; + int32_t fd_ = -1; + uint64_t frameNumber_ = 0; + uint64_t timeStamp_ = 0; + int32_t captureId_ = -1; + bool valid_ = true; + int32_t fenceId_ = -1; + int32_t encodeType_ = 0; + BufferHandle* bufHandle_ = nullptr; + + std::mutex l_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_IMAGE_BUFFER_H diff --git a/camera_hdf/hdi_impl/include/dstream_operator/doffline_stream_operator.h b/camera_hdf/hdi_impl/include/dstream_operator/doffline_stream_operator.h new file mode 100644 index 0000000000000000000000000000000000000000..6dde3f154c0caeb5fb7485c8471815ad0f756857 --- /dev/null +++ b/camera_hdf/hdi_impl/include/dstream_operator/doffline_stream_operator.h @@ -0,0 +1,41 @@ +/* + * 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 DISTRIBUTED_CAMERA_OFFLINE_STREAM_OPERATOR_H +#define DISTRIBUTED_CAMERA_OFFLINE_STREAM_OPERATOR_H + +#include "doffline_stream_operator_stub.h" +#include "dcamera.h" + +namespace OHOS { +namespace DistributedHardware { +class DOfflineStreamOperator : public DOfflineStreamOperatorStub { +public: + DOfflineStreamOperator() = default; + virtual ~DOfflineStreamOperator() = default; + DOfflineStreamOperator(const DOfflineStreamOperator &other) = delete; + DOfflineStreamOperator(DOfflineStreamOperator &&other) = delete; + DOfflineStreamOperator& operator=(const DOfflineStreamOperator &other) = delete; + DOfflineStreamOperator& operator=(DOfflineStreamOperator &&other) = delete; + +public: + virtual CamRetCode CancelCapture(int captureId) override; + virtual CamRetCode ReleaseStreams(const std::vector& streamIds) override; + virtual CamRetCode Release() override; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +#endif // DISTRIBUTED_CAMERA_OFFLINE_STREAM_OPERATOR_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/include/dstream_operator/dstream_operator.h b/camera_hdf/hdi_impl/include/dstream_operator/dstream_operator.h new file mode 100644 index 0000000000000000000000000000000000000000..3885d5033f23cb3cbba5d465b3856026652e1f45 --- /dev/null +++ b/camera_hdf/hdi_impl/include/dstream_operator/dstream_operator.h @@ -0,0 +1,113 @@ +/* + * 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 DISTRIBUTED_CAMERA_STREAM_OPERATOR_H +#define DISTRIBUTED_CAMERA_STREAM_OPERATOR_H + +#include +#include +#include +#include "istream_operator.h" +#include "dstream_operator_stub.h" +#include "dcamera.h" +#include "dmetadata_processor.h" +#include "types.h" +#include "constants.h" +#include "dcamera_steam.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace std; +class DCameraProvider; +class DStreamOperator : public DStreamOperatorStub { +public: + DStreamOperator(std::shared_ptr &dMetadataProcessor); + DStreamOperator() = default; + virtual ~DStreamOperator() = default; + DStreamOperator(const DStreamOperator &other) = delete; + DStreamOperator(DStreamOperator &&other) = delete; + DStreamOperator& operator=(const DStreamOperator &other) = delete; + DStreamOperator& operator=(DStreamOperator &&other) = delete; + +public: + CamRetCode IsStreamsSupported(OperationMode mode, + const std::shared_ptr &modeSetting, + const std::vector> &info, + StreamSupportType &type) override; + CamRetCode CreateStreams(const std::vector>& streamInfos) override; + CamRetCode ReleaseStreams(const std::vector& streamIds) override; + CamRetCode CommitStreams(OperationMode mode, + const std::shared_ptr& modeSetting) override; + CamRetCode GetStreamAttributes(std::vector>& attributes) override; + CamRetCode AttachBufferQueue(int streamId, const OHOS::sptr& producer) override; + CamRetCode DetachBufferQueue(int streamId) override; + CamRetCode Capture(int captureId, const std::shared_ptr& captureInfo, bool isStreaming) override; + CamRetCode CancelCapture(int captureId) override; + CamRetCode ChangeToOfflineStream(const std::vector& streamIds, OHOS::sptr& callback, + OHOS::sptr& offlineOperator) override; + + DCamRetCode InitOutputConfigurations(const std::shared_ptr &dhBase, const std::string &abilityInfo); + DCamRetCode AcquireBuffer(int streamId, std::shared_ptr &buffer); + DCamRetCode ShutterBuffer(int streamId, const std::shared_ptr &buffer); + DCamRetCode SetCallBack(OHOS::sptr const &callback); + DCamRetCode SetDeviceCallback(function &errorCbk, + function)> &resultCbk); + void Release(); + +private: + bool IsCapturing(); + void SetCapturing(bool isCapturing); + DCamRetCode NegotiateSuitableCaptureInfo(const std::shared_ptr& srcCaptureInfo, bool isStreaming); + void ChooseSuitableFormat(std::vector> &streamInfo, + std::shared_ptr &captureInfo); + void ChooseSuitableResolution(std::vector> &streamInfo, + std::shared_ptr &captureInfo); + void ChooseSuitableDataSpace(std::vector> &streamInfo, + std::shared_ptr &captureInfo); + void ChooseSuitableEncodeType(std::vector> &streamInfo, + std::shared_ptr &captureInfo); + void ConvertStreamInfo(std::shared_ptr &srcInfo, std::shared_ptr &dstInfo); + DCEncodeType ConvertDCEncodeType(std::string &srcEncodeType); + std::shared_ptr BuildSuitableCaptureInfo(const shared_ptr& srcCaptureInfo, + std::vector> &srcStreamInfo); + +private: + std::shared_ptr dMetadataProcessor_; + OHOS::sptr dcStreamOperatorCallback_; + function errorCallback_; + function)> resultCallback_; + + std::shared_ptr dhBase_; + std::vector dcSupportedCodecType_; + std::map> dcSupportedFormatMap_; + std::map> dcSupportedResolutionMap_; + + std::map> halStreamMap_; + std::map> dcStreamInfoMap_; + std::map> halCaptureInfoMap_; + std::vector> cachedDCaptureInfoList_; + std::map enableShutterCbkMap_; + std::map, int> acceptedBufferNum_; + + std::mutex requestLock_; + bool isCapturing_ = false; + std::mutex isCapturingLock_; + OperationMode currentOperMode_ = OperationMode::NORMAL; + std::shared_ptr latestStreamSetting_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +#endif // DISTRIBUTED_CAMERA_STREAM_OPERATOR_H diff --git a/camera_hdf/hdi_impl/include/utils/constants.h b/camera_hdf/hdi_impl/include/utils/constants.h new file mode 100644 index 0000000000000000000000000000000000000000..a9a07b88abc0e175fb693d2d0d10705f5170e54a --- /dev/null +++ b/camera_hdf/hdi_impl/include/utils/constants.h @@ -0,0 +1,113 @@ +/* + * 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 DISTRIBUTED_CONSTANTS_H +#define DISTRIBUTED_CONSTANTS_H + +#include +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +const uint32_t YUV_WIDTH_RATIO = 3; +const uint32_t YUV_HEIGHT_RATIO = 2; + +const uint32_t DEVID_MAX_LENGTH = 64; +const uint32_t DHID_MAX_LENGTH = 64; + +constexpr size_t DEFAULT_ENTRY_CAPACITY = 100; +constexpr size_t DEFAULT_DATA_CAPACITY = 2000; + +const uint32_t SIZE_FMT_LEN = 2; +const uint32_t MAX_SUPPORT_PREVIEW_WIDTH = 1920; +const uint32_t MAX_SUPPORT_PREVIEW_HEIGHT = 1080; +const uint32_t MAX_SUPPORT_PHOTO_WIDTH = 4096; +const uint32_t MAX_SUPPORT_PHOTO_HEIGHT = 3072; +const std::string STAR_SEPARATOR = "*"; + +const uint32_t MIN_SUPPORT_DEFAULT_FPS = 15; +const uint32_t MAX_SUPPORT_DEFAULT_FPS = 30; + +const int64_t MAX_FRAME_DURATION = 1000000000LL / 10; + +const uint32_t BUFFER_QUEUE_SIZE = 8; + +const uint32_t DEGREE_180 = 180; +const uint32_t DEGREE_240 = 240; + +const uint32_t INGNORE_STR_LEN = 2; + +const uint32_t WAIT_OPEN_TIMEOUT_SEC = 5; + +const std::string ENCODE_TYPE_STR_H264 = "OMX_hisi_video_encoder_avc"; +const std::string ENCODE_TYPE_STR_H265 = "OMX_hisi_video_encoder_hevc"; +const std::string ENCODE_TYPE_STR_JPEG = "jpeg"; + +enum DCameraBufferUsage : uint64_t { + CAMERA_USAGE_SW_READ_OFTEN = (1 << 0), + CAMERA_USAGE_SW_WRITE_OFTEN = (1 << 1), + CAMERA_USAGE_MEM_DMA = (1 << 2), +}; + +/* Each virtual camera must include these default resolution. */ +const std::vector> DEFAULT_FMT_VEC { +/* + pair(320, 240), + pair(480, 360), + pair(640, 360), + pair(640, 480), + pair(720, 540), + pair(960, 540), + pair(960, 720), + pair(1280, 720), + pair(1440, 1080), + pair(1920, 1080) +*/ +}; + +using DCSceneType = enum _DCSceneType : int32_t { + PREVIEW = 0, + VIDEO = 1, + PHOTO = 2 +}; + +using RetCode = uint32_t; +enum Ret : uint32_t { + RC_OK = 0, + RC_ERROR, +}; + +struct DCResolution { + int32_t width_; + int32_t height_; + + DCResolution() : width_(0), height_(0) {} + + DCResolution(int32_t width, int32_t height) : width_(width), height_(height) {} + + bool operator ==(const DCResolution others) const + { + return (this->width_ == others.width_) && (this->height_ == others.height_); + } + + bool operator <(const DCResolution others) const + { + return this->width_ < others.width_ || + (this->width_ == others.width_ && this->height_ < others.height_); + } +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CONSTANTS_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/include/utils/dcamera.h b/camera_hdf/hdi_impl/include/utils/dcamera.h new file mode 100644 index 0000000000000000000000000000000000000000..768db55138810b59743b6b9fef40b5a149b4ac93 --- /dev/null +++ b/camera_hdf/hdi_impl/include/utils/dcamera.h @@ -0,0 +1,38 @@ +/* + * 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 DISTRIBUTED_CAMERA_H +#define DISTRIBUTED_CAMERA_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +using RetCode = uint32_t; +using MetaType = int32_t; + +CamRetCode MapToExternalRetCode(DCamRetCode retCode); + +DCamRetCode MapToInternalRetCode(CamRetCode retCode); + +uint64_t GetCurrentLocalTimeStamp(); + +void SplitString(const std::string &str, std::vector &tokens, const std::string &delimiters); +} // end namespace DistributedHardware +} // end namespace OHOS + +#endif // DISTRIBUTED_CAMERA_H \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/dcamera_device/dcamera_device.cpp b/camera_hdf/hdi_impl/src/dcamera_device/dcamera_device.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d602127bcfc1453a3077733a15aa85c8491e5cd --- /dev/null +++ b/camera_hdf/hdi_impl/src/dcamera_device/dcamera_device.cpp @@ -0,0 +1,446 @@ +/* + * 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 "dcamera_device.h" +#include +#include +#include +#include "dcamera_host.h" +#include "dcamera_provider.h" +#include "dcamera_utils_tools.h" +#include "distributed_hardware_log.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +using ErrorCallback = std::function; +using ResultCallback = std::function)>; +DCameraDevice::DCameraDevice(const std::shared_ptr &dhBase, const std::string &abilityInfo) + : isOpened_(false), + dCameraId_(GenerateCameraId(dhBase)), + dhBase_(dhBase), + dCameraAbilityInfo_(abilityInfo), + dCameraDeviceCallback_(nullptr), + dCameraStreamOperator_(nullptr), + dMetadataProcessor_(nullptr) +{ + DHLOGI("DCameraDevice::ctor, instance = %p.", this); + Init(abilityInfo); +} + +void DCameraDevice::Init(const std::string &abilityInfo) +{ + if (dMetadataProcessor_ == nullptr) { + dMetadataProcessor_ = std::make_shared(); + } + dMetadataProcessor_->InitDCameraAbility(abilityInfo); +} + +DCamRetCode DCameraDevice::CreateDStreamOperator() +{ + if (dCameraStreamOperator_ == nullptr) { + dCameraStreamOperator_ = new (std::nothrow) DStreamOperator(dMetadataProcessor_); + if (dCameraStreamOperator_ == nullptr) { + DHLOGE("Create distributed camera stream operator failed."); + return DEVICE_NOT_INIT; + } + } + + DCamRetCode ret = dCameraStreamOperator_->InitOutputConfigurations(dhBase_, dCameraAbilityInfo_); + if (ret != SUCCESS) { + DHLOGE("Init distributed camera stream operator failed, ret=%d.", ret); + return ret; + } + + ErrorCallback onErrorCallback = + [this](ErrorType type, int32_t errorMsg) -> void { + if (dCameraDeviceCallback_) { + dCameraDeviceCallback_->OnError(type, errorMsg); + } + }; + ResultCallback onResultCallback = + [this](uint64_t timestamp, const std::shared_ptr &result) -> void { + if (dCameraDeviceCallback_) { + dCameraDeviceCallback_->OnResult(timestamp, result); + } + }; + dCameraStreamOperator_->SetDeviceCallback(onErrorCallback, onResultCallback); + + return ret; +} + +CamRetCode DCameraDevice::GetStreamOperator(const OHOS::sptr &callback, + OHOS::sptr &streamOperator) +{ + if (dCameraStreamOperator_ == nullptr) { + DHLOGE("Distributed camera stream operator not init."); + return CamRetCode::DEVICE_ERROR; + } + + if (callback == nullptr) { + DHLOGE("Input callback is null."); + return CamRetCode::INVALID_ARGUMENT; + } + + DCamRetCode ret = dCameraStreamOperator_->SetCallBack(callback); + if (ret != SUCCESS) { + DHLOGE("Set stream operator callback failed, ret=%d.", ret); + return MapToExternalRetCode(ret); + } + + streamOperator = dCameraStreamOperator_; + return CamRetCode::NO_ERROR; +} + +CamRetCode DCameraDevice::UpdateSettings(const std::shared_ptr &settings) +{ + if (settings == nullptr) { + DHLOGE("DCameraDevice::UpdateSettings, input settings is null."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!IsOpened()) { + DHLOGE("DCameraDevice::UpdateSettings, dcamera device %s already closed.", dCameraId_.c_str()); + return CamRetCode::CAMERA_CLOSED; + } + + std::shared_ptr dcSetting = std::make_shared(); + + dcSetting->type_ = DCSettingsType::UPDATE_METADATA; + std::string abilityStr = CameraStandard::MetadataUtils::EncodeToString(settings); + dcSetting->value_ = Base64Encode(reinterpret_cast(abilityStr.c_str()), abilityStr.length()); + + std::vector> dcSettings; + dcSettings.push_back(dcSetting); + + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider == nullptr) { + DHLOGE("Distributed camera provider instance is null."); + return CamRetCode::DEVICE_ERROR; + } + DCamRetCode ret = provider->UpdateSettings(dhBase_, dcSettings); + + return MapToExternalRetCode(ret); +} + +CamRetCode DCameraDevice::SetResultMode(const ResultCallbackMode &mode) +{ + if (dMetadataProcessor_ == nullptr) { + DHLOGE("Metadata processor not init."); + return CamRetCode::DEVICE_ERROR; + } + + DCamRetCode ret = dMetadataProcessor_->SetMetadataResultMode(mode); + if (ret != SUCCESS) { + DHLOGE("Set metadata result mode failed, ret=%d.", ret); + } + return MapToExternalRetCode(ret); +} + +CamRetCode DCameraDevice::GetEnabledResults(std::vector &results) +{ + if (dMetadataProcessor_ == nullptr) { + DHLOGE("Metadata processor not init."); + return CamRetCode::DEVICE_ERROR; + } + + DCamRetCode ret = dMetadataProcessor_->GetEnabledMetadataResults(results); + if (ret != SUCCESS) { + DHLOGE("Get enabled metadata results failed, ret=%d.", ret); + } + return MapToExternalRetCode(ret); +} + +CamRetCode DCameraDevice::EnableResult(const std::vector &results) +{ + if (dMetadataProcessor_ == nullptr) { + DHLOGE("Metadata processor not init."); + return CamRetCode::DEVICE_ERROR; + } + + DCamRetCode ret = dMetadataProcessor_->EnableMetadataResult(results); + if (ret != SUCCESS) { + DHLOGE("Enable metadata result failed, ret=%d.", ret); + return MapToExternalRetCode(ret); + } + + stringstream sstream; + std::reverse_copy(results.begin(), results.end(), ostream_iterator(sstream, "")); + std::shared_ptr dcSetting = std::make_shared(); + dcSetting->type_ = DCSettingsType::ENABLE_METADATA; + dcSetting->value_ = sstream.str(); + + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider != nullptr) { + std::vector> dcSettings; + dcSettings.push_back(dcSetting); + ret = provider->UpdateSettings(dhBase_, dcSettings); + } + return MapToExternalRetCode(ret); +} + +CamRetCode DCameraDevice::DisableResult(const std::vector &results) +{ + if (dMetadataProcessor_ == nullptr) { + DHLOGE("Metadata processor not init."); + return CamRetCode::DEVICE_ERROR; + } + + DCamRetCode ret = dMetadataProcessor_->DisableMetadataResult(results); + if (ret != SUCCESS) { + DHLOGE("Disable metadata result failed, ret=%d.", ret); + return MapToExternalRetCode(ret); + } + + stringstream sstream; + std::reverse_copy(results.begin(), results.end(), ostream_iterator(sstream, "")); + std::shared_ptr dcSetting = std::make_shared(); + dcSetting->type_ = DCSettingsType::DISABLE_METADATA; + dcSetting->value_ = sstream.str(); + + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider != nullptr) { + std::vector> dcSettings; + dcSettings.push_back(dcSetting); + ret = provider->UpdateSettings(dhBase_, dcSettings); + } + return MapToExternalRetCode(ret); +} + +void DCameraDevice::Close() +{ + DHLOGI("DCameraDevice::Close distributed camera: %s", dCameraId_.c_str()); + + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider != nullptr) { + provider->StopCapture(dhBase_); + } + if (dCameraStreamOperator_ != nullptr) { + dCameraStreamOperator_->Release(); + dCameraStreamOperator_ = nullptr; + } + if (provider != nullptr) { + provider->CloseSession(dhBase_); + } + if (dMetadataProcessor_ != nullptr) { + dMetadataProcessor_->ResetEnableResults(); + } + dCameraDeviceCallback_ = nullptr; + isOpenSessFailed_ = false; + isOpened_ = false; +} + +CamRetCode DCameraDevice::OpenDCamera(const OHOS::sptr &callback) +{ + if (callback == nullptr) { + DHLOGE("Input callback is null."); + return CamRetCode::INVALID_ARGUMENT; + } + dCameraDeviceCallback_ = callback; + + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider == nullptr) { + DHLOGE("Get distributed camera provider instance is null."); + return CamRetCode::DEVICE_ERROR; + } + DCamRetCode ret = provider->OpenSession(dhBase_); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Open distributed camera control session failed, ret = %d.", ret); + return MapToExternalRetCode(ret); + } + + unique_lock lock(openSesslock_); + auto st = openSessCV_.wait_for(lock, chrono::seconds(WAIT_OPEN_TIMEOUT_SEC)); + if (st == cv_status::timeout) { + DHLOGE("Wait for distributed camera session open timeout."); + return CamRetCode::DEVICE_ERROR; + } + { + unique_lock lock(isOpenSessFailedlock_); + if (isOpenSessFailed_) { + DHLOGE("Open distributed camera session failed."); + return CamRetCode::DEVICE_ERROR; + } + } + + ret = CreateDStreamOperator(); + if (ret != SUCCESS) { + DHLOGE("Create distributed camera stream operator failed."); + return MapToExternalRetCode(ret); + } + isOpened_ = true; + + return MapToExternalRetCode(ret); +} + +CamRetCode DCameraDevice::GetDCameraAbility(std::shared_ptr &ability) +{ + if (dMetadataProcessor_ == nullptr) { + DHLOGE("Metadata processor not init."); + return CamRetCode::DEVICE_ERROR; + } + + DCamRetCode ret = dMetadataProcessor_->GetDCameraAbility(ability); + if (ret != SUCCESS) { + DHLOGE("Get distributed camera ability failed, ret=%d.", ret); + } + return MapToExternalRetCode(ret); +} + +DCamRetCode DCameraDevice::AcquireBuffer(int streamId, std::shared_ptr &buffer) +{ + if (dCameraStreamOperator_ == nullptr) { + DHLOGE("Stream operator not init."); + return DEVICE_NOT_INIT; + } + + DCamRetCode ret = dCameraStreamOperator_->AcquireBuffer(streamId, buffer); + if (ret != SUCCESS) { + DHLOGE("Acquire buffer failed, ret=%d.", ret); + } + return ret; +} + +DCamRetCode DCameraDevice::ShutterBuffer(int streamId, const std::shared_ptr &buffer) +{ + if (dCameraStreamOperator_ == nullptr) { + DHLOGE("Stream operator not init."); + return DEVICE_NOT_INIT; + } + + DCamRetCode ret = dCameraStreamOperator_->ShutterBuffer(streamId, buffer); + if (ret != SUCCESS) { + DHLOGE("Shutter buffer failed, ret=%d.", ret); + } + return ret; +} + +DCamRetCode DCameraDevice::OnSettingsResult(const std::shared_ptr &result) +{ + if (result == nullptr) { + DHLOGE("Input camera settings is null."); + return INVALID_ARGUMENT; + } + + if (dMetadataProcessor_ == nullptr) { + DHLOGE("Metadata processor not init."); + return DEVICE_NOT_INIT; + } + + if (result->type_ != DCSettingsType::METADATA_RESULT) { + DHLOGE("Invalid camera setting type = %d.", result->type_); + return INVALID_ARGUMENT; + } + if ((result->value_).empty()) { + DHLOGE("Camera settings result is empty."); + return INVALID_ARGUMENT; + } + + DCamRetCode ret = dMetadataProcessor_->SaveResultMetadata(result->value_); + if (ret != SUCCESS) { + DHLOGE("Save result metadata failed, ret = %d", ret); + } + return ret; +} + +DCamRetCode DCameraDevice::Notify(const std::shared_ptr &event) +{ + DHLOGI("DCameraDevice::Notify for event type = %d, result = %d, content = %s.", event->type_, event->result_, + event->content_.c_str()); + if ((event->type_ != DCameraEventType::DCAMERA_MESSAGE) && (event->type_ != DCameraEventType::DCAMERA_OPERATION)) { + DHLOGE("Invalid distributed camera event type = %d.", event->type_); + return INVALID_ARGUMENT; + } + switch (event->result_) { + case DCameraEventResult::DCAMERA_EVENT_CHANNEL_CONNECTED: { + { + unique_lock lock(isOpenSessFailedlock_); + isOpenSessFailed_ = false; + } + openSessCV_.notify_one(); + break; + } + case DCameraEventResult::DCAMERA_EVENT_OPEN_CHANNEL_ERROR: { + { + unique_lock lock(isOpenSessFailedlock_); + isOpenSessFailed_ = true; + } + openSessCV_.notify_one(); + break; + } + case DCameraEventResult::DCAMERA_EVENT_CHANNEL_DISCONNECTED: { + if (dCameraDeviceCallback_ != nullptr) { + dCameraDeviceCallback_->OnError(ErrorType::FATAL_ERROR, 0); + Close(); + } + break; + } + case DCameraEventResult::DCAMERA_EVENT_CONFIG_STREAMS_ERROR: + case DCameraEventResult::DCAMERA_EVENT_START_CAPTURE_ERROR: { + if (dCameraDeviceCallback_ != nullptr) { + dCameraDeviceCallback_->OnError(ErrorType::REQUEST_TIMEOUT, 0); + } + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider != nullptr) { + provider->StopCapture(dhBase_); + } + if (dCameraStreamOperator_ != nullptr) { + dCameraStreamOperator_->Release(); + } + break; + } + case DCameraEventResult::DCAMERA_EVENT_CAMERA_ERROR: { + std::shared_ptr dCameraHost = DCameraHost::GetInstance(); + if (dCameraHost != nullptr) { + dCameraHost->NotifyDCameraStatus(dhBase_, event->result_); + } + if (dCameraDeviceCallback_ != nullptr) { + dCameraDeviceCallback_->OnError(ErrorType::REQUEST_TIMEOUT, 0); + Close(); + } + break; + } + default: + break; + } + return SUCCESS; +} + +void DCameraDevice::SetProviderCallback(const OHOS::sptr &callback) +{ + dCameraProviderCallback_ = callback; +} + +OHOS::sptr DCameraDevice::GetProviderCallback() +{ + return dCameraProviderCallback_; +} + +std::string DCameraDevice::GenerateCameraId(const std::shared_ptr &dhBase) +{ + return dhBase->deviceId_ + "__" + dhBase->dhId_; +} + +std::string DCameraDevice::GetDCameraId() +{ + return dCameraId_; +} + +bool DCameraDevice::IsOpened() +{ + return isOpened_; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/dcamera_device/dmetadata_processor.cpp b/camera_hdf/hdi_impl/src/dcamera_device/dmetadata_processor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8602c366c9fdb1a91d78ad1d73e6d957a25fd65 --- /dev/null +++ b/camera_hdf/hdi_impl/src/dcamera_device/dmetadata_processor.cpp @@ -0,0 +1,608 @@ +/* + * 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 "dmetadata_processor.h" +#include "dbuffer_manager.h" +#include "dcamera_utils_tools.h" +#include "distributed_hardware_log.h" +#include "json/json.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +DCamRetCode DMetadataProcessor::InitDCameraAbility(const std::string &abilityInfo) +{ + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (jsonReader->parse(abilityInfo.c_str(), abilityInfo.c_str() + abilityInfo.length(), &rootValue, &errs) && + rootValue.isObject()) { + if (rootValue.isMember("MetaData") && rootValue["MetaData"].isString()) { + std::string metadataStr = rootValue["MetaData"].asString(); + if (!metadataStr.empty()) { + dCameraAbility_ = CameraStandard::MetadataUtils::DecodeFromString(Base64Decode(metadataStr)); + DHLOGI("Decode distributed camera metadata from string success."); + } + } + } + + if (dCameraAbility_ == nullptr) { + DHLOGE("Metadata is null in ability set or failed to decode metadata ability from string."); + dCameraAbility_ = std::make_shared(DEFAULT_ENTRY_CAPACITY, DEFAULT_DATA_CAPACITY); + } + + if (CameraStandard::GetCameraMetadataItemCount(dCameraAbility_->get()) <= 0) { + DCamRetCode ret = InitDCameraDefaultAbilityKeys(abilityInfo); + if (ret != SUCCESS) { + DHLOGE("Init distributed camera defalult abilily keys failed."); + dCameraAbility_ = nullptr; + return ret; + } + } + + DCamRetCode ret = InitDCameraOutputAbilityKeys(abilityInfo); + if (ret != SUCCESS) { + DHLOGE("Init distributed camera output abilily keys failed."); + dCameraAbility_ = nullptr; + return ret; + } + + camera_metadata_item_entry_t* itemEntry = CameraStandard::GetMetadataItems(dCameraAbility_->get()); + uint32_t count = dCameraAbility_->get()->item_count; + for (uint32_t i = 0; i < count; i++, itemEntry++) { + allResultSet_.insert((MetaType)(itemEntry->item)); + } + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::InitDCameraDefaultAbilityKeys(const std::string &abilityInfo) +{ + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (jsonReader->parse(abilityInfo.c_str(), abilityInfo.c_str() + abilityInfo.length(), &rootValue, &errs) && + rootValue.isObject()) { + if (rootValue.isMember("ProtocolVer") && rootValue["ProtocolVer"].isString()) { + protocolVersion_ = rootValue["ProtocolVer"].asString(); + } + if (rootValue.isMember("Position") && rootValue["Position"].isString()) { + dCameraPosition_ = rootValue["Position"].asString(); + } + } + + if (dCameraPosition_ == "BACK") { + const uint8_t position = OHOS_CAMERA_POSITION_BACK; + AddAbilityEntry(OHOS_ABILITY_CAMERA_POSITION, &position, 1); + } else if (dCameraPosition_ == "FRONT") { + const uint8_t position = OHOS_CAMERA_POSITION_FRONT; + AddAbilityEntry(OHOS_ABILITY_CAMERA_POSITION, &position, 1); + } else { + const uint8_t position = OHOS_CAMERA_POSITION_OTHER; + AddAbilityEntry(OHOS_ABILITY_CAMERA_POSITION, &position, 1); + } + + const uint8_t cameraType = OHOS_CAMERA_TYPE_LOGICAL; + AddAbilityEntry(OHOS_ABILITY_CAMERA_TYPE, &cameraType, 1); + + const int64_t exposureTime = 0xFFFFFFFFFFFFFFFF; + AddAbilityEntry(OHOS_SENSOR_EXPOSURE_TIME, &exposureTime, 1); + + const float correctionGain = 0.0; + AddAbilityEntry(OHOS_SENSOR_COLOR_CORRECTION_GAINS, &correctionGain, 1); + + const uint8_t faceDetectMode = OHOS_CAMERA_FACE_DETECT_MODE_OFF; + AddAbilityEntry(OHOS_STATISTICS_FACE_DETECT_MODE, &faceDetectMode, 1); + + const uint8_t histogramMode = OHOS_CAMERA_HISTOGRAM_MODE_OFF; + AddAbilityEntry(OHOS_STATISTICS_HISTOGRAM_MODE, &histogramMode, 1); + + const uint8_t aeAntibandingMode = OHOS_CAMERA_AE_ANTIBANDING_MODE_OFF; + AddAbilityEntry(OHOS_CONTROL_AE_ANTIBANDING_MODE, &aeAntibandingMode, 1); + + int32_t aeExposureCompensation = 0xFFFFFFFF; + AddAbilityEntry(OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, &aeExposureCompensation, 1); + + const uint8_t aeLock = OHOS_CAMERA_AE_LOCK_OFF; + AddAbilityEntry(OHOS_CONTROL_AE_LOCK, &aeLock, 1); + + const uint8_t aeMode = OHOS_CAMERA_AE_MODE_OFF; + AddAbilityEntry(OHOS_CONTROL_AE_MODE, &aeMode, 1); + + std::vector fpsRanges; + fpsRanges.push_back(MIN_SUPPORT_DEFAULT_FPS); + fpsRanges.push_back(MAX_SUPPORT_DEFAULT_FPS); + AddAbilityEntry(OHOS_CONTROL_AE_TARGET_FPS_RANGE, fpsRanges.data(), fpsRanges.size()); + + AddAbilityEntry(OHOS_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES, fpsRanges.data(), fpsRanges.size()); + + const uint8_t afMode = OHOS_CAMERA_AF_MODE_OFF; + AddAbilityEntry(OHOS_CONTROL_AF_MODE, &afMode, 1); + + const uint8_t awbLock = OHOS_CAMERA_AWB_LOCK_OFF; + AddAbilityEntry(OHOS_CONTROL_AWB_LOCK, &awbLock, 1); + + const uint8_t awbMode = OHOS_CAMERA_AWB_MODE_OFF; + AddAbilityEntry(OHOS_CONTROL_AWB_MODE, &awbMode, 1); + + const uint8_t aeAntibandingModes = OHOS_CAMERA_AE_ANTIBANDING_MODE_AUTO; + AddAbilityEntry(OHOS_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES, &aeAntibandingModes, 1); + + const uint8_t aeAvailableModes = OHOS_CAMERA_AE_MODE_ON; + AddAbilityEntry(OHOS_CONTROL_AE_AVAILABLE_MODES, &aeAvailableModes, 1); + + const int32_t compensationRange[] = { 0, 0 }; + AddAbilityEntry(OHOS_CONTROL_AE_COMPENSATION_RANGE, compensationRange, + (sizeof(compensationRange) / sizeof(compensationRange[0]))); + + const camera_rational_t compensationStep[] = { { 0, 1 } }; + AddAbilityEntry(OHOS_CONTROL_AE_COMPENSATION_STEP, compensationStep, + (sizeof(compensationStep) / sizeof(compensationStep[0]))); + + const uint8_t afAvailableModes[] = { OHOS_CAMERA_AF_MODE_AUTO, OHOS_CAMERA_AF_MODE_OFF }; + AddAbilityEntry(OHOS_CONTROL_AF_AVAILABLE_MODES, afAvailableModes, + (sizeof(afAvailableModes) / sizeof(afAvailableModes[0]))); + + const uint8_t awbAvailableModes = OHOS_CAMERA_AWB_MODE_AUTO; + AddAbilityEntry(OHOS_CONTROL_AWB_AVAILABLE_MODES, &awbAvailableModes, 1); + + const uint8_t deviceExposureMode = OHOS_CAMERA_EXPOSURE_MODE_CONTINUOUS_AUTO; + AddAbilityEntry(OHOS_ABILITY_DEVICE_AVAILABLE_EXPOSUREMODES, &deviceExposureMode, 1); + + const uint8_t controlExposureMode = OHOS_CAMERA_EXPOSURE_MODE_CONTINUOUS_AUTO; + AddAbilityEntry(OHOS_CONTROL_EXPOSUREMODE, &controlExposureMode, 1); + + const uint8_t deviceFocusModes = OHOS_CAMERA_FOCUS_MODE_AUTO; + AddAbilityEntry(OHOS_ABILITY_DEVICE_AVAILABLE_FOCUSMODES, &deviceFocusModes, 1); + + const uint8_t controlFocusMode = OHOS_CAMERA_FOCUS_MODE_AUTO; + AddAbilityEntry(OHOS_CONTROL_FOCUSMODE, &controlFocusMode, 1); + + const uint8_t deviceFlashModes = OHOS_CAMERA_FLASH_MODE_AUTO; + AddAbilityEntry(OHOS_ABILITY_DEVICE_AVAILABLE_FLASHMODES, &deviceFlashModes, 1); + + const uint8_t controlFlashMode = OHOS_CAMERA_FLASH_MODE_CLOSE; + AddAbilityEntry(OHOS_CONTROL_FLASHMODE, &controlFlashMode, 1); + + float zoomRatioRange[1] = {1.0}; + AddAbilityEntry(OHOS_ABILITY_ZOOM_RATIO_RANGE, zoomRatioRange, + (sizeof(zoomRatioRange) / sizeof(zoomRatioRange[0]))); + + const float zoomRatio = 1.0; + AddAbilityEntry(OHOS_CONTROL_ZOOM_RATIO, &zoomRatio, 1); + + int32_t activeArraySize[] = { + 0, 0, static_cast(maxPreviewResolution_.width_), static_cast(maxPreviewResolution_.height_) + }; + AddAbilityEntry(OHOS_SENSOR_INFO_ACTIVE_ARRAY_SIZE, activeArraySize, + (sizeof(activeArraySize) / sizeof(activeArraySize[0]))); + + int32_t pixelArraySize[] = { + static_cast(maxPreviewResolution_.width_), static_cast(maxPreviewResolution_.height_) + }; + AddAbilityEntry(OHOS_SENSOR_INFO_PIXEL_ARRAY_SIZE, pixelArraySize, + (sizeof(pixelArraySize) / sizeof(pixelArraySize[0]))); + + const int32_t jpegThumbnailSizes[] = {0, 0, DEGREE_240, DEGREE_180}; + AddAbilityEntry(OHOS_JPEG_AVAILABLE_THUMBNAIL_SIZES, jpegThumbnailSizes, + (sizeof(jpegThumbnailSizes) / sizeof(jpegThumbnailSizes[0]))); + + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::InitDCameraOutputAbilityKeys(const std::string &abilityInfo) +{ + std::map> supportedFormats = GetDCameraSupportedFormats(abilityInfo); + + std::vector streamConfigurations; + std::map>::iterator iter; + for (iter = supportedFormats.begin(); iter != supportedFormats.end(); ++iter) { + std::vector resolutionList = iter->second; + for (auto resolution : resolutionList) { + DHLOGI("DMetadataProcessor::supported formats: { format=%d, width=%d, height=%d }", iter->first, + resolution.width_, resolution.height_); + streamConfigurations.push_back(iter->first); + streamConfigurations.push_back(resolution.width_); + streamConfigurations.push_back(resolution.height_); + } + } + UpdateAbilityEntry(OHOS_ABILITY_STREAM_AVAILABLE_BASIC_CONFIGURATIONS, streamConfigurations.data(), + streamConfigurations.size()); + + UpdateAbilityEntry(OHOS_SENSOR_INFO_MAX_FRAME_DURATION, &MAX_FRAME_DURATION, 1); + + const int32_t jpegMaxSize = maxPhotoResolution_.width_ * maxPhotoResolution_.height_; + UpdateAbilityEntry(OHOS_JPEG_MAX_SIZE, &jpegMaxSize, 1); + + const uint8_t connectionType = OHOS_CAMERA_CONNECTION_TYPE_REMOTE; + UpdateAbilityEntry(OHOS_ABILITY_CAMERA_CONNECTION_TYPE, &connectionType, 1); + + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::AddAbilityEntry(uint32_t tag, const void *data, size_t size) +{ + if (dCameraAbility_ == nullptr) { + DHLOGE("Distributed camera abilily is null."); + return INVALID_ARGUMENT; + } + + camera_metadata_item_t item; + int ret = CameraStandard::FindCameraMetadataItem(dCameraAbility_->get(), tag, &item); + if (ret) { + if (!dCameraAbility_->addEntry(tag, data, size)) { + DHLOGE("Add tag %d failed.", tag); + return FAILED; + } + } + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::UpdateAbilityEntry(uint32_t tag, const void *data, size_t size) +{ + if (dCameraAbility_ == nullptr) { + DHLOGE("Distributed camera abilily is null."); + return INVALID_ARGUMENT; + } + + camera_metadata_item_t item; + int ret = CameraStandard::FindCameraMetadataItem(dCameraAbility_->get(), tag, &item); + if (ret) { + if (!dCameraAbility_->addEntry(tag, data, size)) { + DHLOGE("Add tag %d failed.", tag); + return FAILED; + } + } else { + if (!dCameraAbility_->updateEntry(tag, data, size)) { + DHLOGE("Update tag %d failed.", tag); + return FAILED; + } + } + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::GetDCameraAbility(std::shared_ptr &ability) +{ + ability = dCameraAbility_; + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::SetMetadataResultMode(const ResultCallbackMode &mode) +{ + if (mode < ResultCallbackMode::PER_FRAME || mode > ResultCallbackMode::ON_CHANGED) { + DHLOGE("Invalid result callback mode."); + return INVALID_ARGUMENT; + } + metaResultMode_ = mode; + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::GetEnabledMetadataResults(std::vector &results) +{ + auto iter = enabledResultSet_.begin(); + while (iter != enabledResultSet_.end()) { + results.push_back(*iter); + iter++; + } + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::EnableMetadataResult(const std::vector &results) +{ + if (results.size() == 0) { + DHLOGE("Enable metadata result list is empty."); + return SUCCESS; + } + + for (size_t i = 0; i < results.size(); i++) { + auto iter = allResultSet_.find(results[i]); + if (iter != allResultSet_.end()) { + auto anoIter = enabledResultSet_.find(results[i]); + if (anoIter == enabledResultSet_.end()) { + enabledResultSet_.insert(results[i]); + } + } else { + DHLOGE("Cannot find match metatype."); + return SUCCESS; + } + } + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::DisableMetadataResult(const std::vector &results) +{ + if (results.size() == 0) { + DHLOGE("Disable metadata result list is empty."); + return SUCCESS; + } + + for (size_t i = 0; i < results.size(); i++) { + auto iter = allResultSet_.find(results[i]); + if (iter != allResultSet_.end()) { + auto anoIter = enabledResultSet_.find(results[i]); + if (anoIter != enabledResultSet_.end()) { + enabledResultSet_.erase(*iter); + } + } else { + DHLOGE("Cannot find match metatype."); + return SUCCESS; + } + } + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::ResetEnableResults() +{ + if (enabledResultSet_.size() < allResultSet_.size()) { + for (auto result : allResultSet_) { + enabledResultSet_.insert(result); + } + } + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::UpdateResultMetadata(bool &needReturn, + std::shared_ptr &result) +{ + if (latestProducerResultMetadata_ == nullptr) { + needReturn = false; + return SUCCESS; + } + + uint32_t itemCapacity = CameraStandard::GetCameraMetadataItemCapacity(latestProducerResultMetadata_); + uint32_t dataCapacity = CameraStandard::GetCameraMetadataDataSize(latestProducerResultMetadata_); + + if (metaResultMode_ == ResultCallbackMode::PER_FRAME) { + ResizeMetadataHeader(latestConsumerResultMetadata_, itemCapacity, dataCapacity); + CameraStandard::CopyCameraMetadataItems(latestConsumerResultMetadata_, latestProducerResultMetadata_); + ConvertToCameraMetadata(latestConsumerResultMetadata_, result); + needReturn = true; + return SUCCESS; + } else { + for (auto tag : enabledResultSet_) { + camera_metadata_item_t item; + camera_metadata_item_t anoItem; + int ret1 = CameraStandard::FindCameraMetadataItem(latestProducerResultMetadata_, tag, &item); + int ret2 = CameraStandard::FindCameraMetadataItem(latestConsumerResultMetadata_, tag, &anoItem); + if (ret1 == 0 && ret2 == 0) { + if (item.count != anoItem.count || item.data_type != anoItem.data_type) { + ResizeMetadataHeader(latestConsumerResultMetadata_, itemCapacity, dataCapacity); + CameraStandard::CopyCameraMetadataItems(latestConsumerResultMetadata_, + latestProducerResultMetadata_); + ConvertToCameraMetadata(latestConsumerResultMetadata_, result); + needReturn = true; + return SUCCESS; + } else { + uint32_t size = GetDataSize(item.data_type); + for (uint32_t i = 0; i < (size * static_cast(item.count)); i++) { + if (*(item.data.u8 + i) != *(anoItem.data.u8 + i)) { + ResizeMetadataHeader(latestConsumerResultMetadata_, itemCapacity, dataCapacity); + CameraStandard::CopyCameraMetadataItems(latestConsumerResultMetadata_, + latestProducerResultMetadata_); + ConvertToCameraMetadata(latestConsumerResultMetadata_, result); + needReturn = true; + return SUCCESS; + } + } + ResizeMetadataHeader(latestConsumerResultMetadata_, itemCapacity, dataCapacity); + CameraStandard::CopyCameraMetadataItems(latestConsumerResultMetadata_, + latestProducerResultMetadata_); + needReturn = false; + } + } else if (ret1 == 0 || ret2 == 0) { + ResizeMetadataHeader(latestConsumerResultMetadata_, itemCapacity, dataCapacity); + CameraStandard::CopyCameraMetadataItems(latestConsumerResultMetadata_, latestProducerResultMetadata_); + ConvertToCameraMetadata(latestConsumerResultMetadata_, result); + needReturn = true; + return SUCCESS; + } + } + } + return SUCCESS; +} + +DCamRetCode DMetadataProcessor::SaveResultMetadata(std::string resultStr) +{ + if (resultStr.empty()) { + DHLOGE("Input result string is null."); + return INVALID_ARGUMENT; + } + + latestProducerResultMetadata_ = CameraStandard::MetadataUtils::DecodeFromString(resultStr)->get(); + if (latestProducerResultMetadata_ == nullptr) { + DHLOGE("Failed to decode metadata setting from string."); + return INVALID_ARGUMENT; + } + + if (!CameraStandard::GetCameraMetadataItemCount(latestProducerResultMetadata_)) { + DHLOGE("Input result metadata item is empty."); + return INVALID_ARGUMENT; + } + + return SUCCESS; +} + +void DMetadataProcessor::ConvertToCameraMetadata(common_metadata_header_t *&input, + std::shared_ptr &output) +{ + auto ret = CameraStandard::CopyCameraMetadataItems(output->get(), input); + if (ret != CAM_META_SUCCESS) { + DHLOGE("Failed to copy the old metadata to new metadata."); + output = nullptr; + } +} + +void DMetadataProcessor::ResizeMetadataHeader(common_metadata_header_t *header, + uint32_t itemCapacity, uint32_t dataCapacity) +{ + if (header) { + header = nullptr; + } + header = CameraStandard::AllocateCameraMetadataBuffer(itemCapacity, dataCapacity); +} + +uint32_t DMetadataProcessor::GetDataSize(uint32_t type) +{ + int32_t size = 0; + if (type == META_TYPE_BYTE) { + size = sizeof(uint8_t); + } else if (type == META_TYPE_INT32) { + size = sizeof(int32_t); + } else if (type == META_TYPE_UINT32) { + size = sizeof(uint32_t); + } else if (type == META_TYPE_FLOAT) { + size = sizeof(float); + } else if (type == META_TYPE_INT64) { + size = sizeof(int64_t); + } else if (type == META_TYPE_DOUBLE) { + size = sizeof(double); + } else if (type == META_TYPE_RATIONAL) { + size = sizeof(camera_rational_t); + } else { + size = 0; + } + return size; +} + +std::map> DMetadataProcessor::GetDCameraSupportedFormats(const std::string &abilityInfo) +{ + std::map> supportedFormats; + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(abilityInfo.c_str(), abilityInfo.c_str() + abilityInfo.length(), &rootValue, &errs) || + !rootValue.isObject()) { + return supportedFormats; + } + + std::set allFormats; + if (rootValue["OutputFormat"]["Preview"].isArray() && (rootValue["OutputFormat"]["Preview"].size() > 0)) { + uint32_t size = rootValue["OutputFormat"]["Preview"].size(); + for (uint32_t i = 0; i < size; i++) { + allFormats.insert((rootValue["OutputFormat"]["Preview"][i]).asInt()); + } + } + + if (rootValue["OutputFormat"]["Video"].isArray() && (rootValue["OutputFormat"]["Video"].size() > 0)) { + uint32_t size = rootValue["OutputFormat"]["Video"].size(); + for (uint32_t i = 0; i < size; i++) { + allFormats.insert((rootValue["OutputFormat"]["Video"][i]).asInt()); + } + } + + std::vector photoFormats; + if (rootValue["OutputFormat"]["Photo"].isArray() && (rootValue["OutputFormat"]["Photo"].size() > 0)) { + uint32_t size = rootValue["OutputFormat"]["Photo"].size(); + for (uint32_t i = 0; i < size; i++) { + photoFormats.push_back((rootValue["OutputFormat"]["Photo"][i]).asInt()); + allFormats.insert((rootValue["OutputFormat"]["Photo"][i]).asInt()); + } + } + + for (const auto &format : allFormats) { + bool isPhotoFormat = (std::find(photoFormats.begin(), photoFormats.end(), format) != photoFormats.end()); + std::string formatStr = std::to_string(format); + if (rootValue["Resolution"][formatStr].isArray() && rootValue["Resolution"][formatStr].size() > 0) { + std::vector resolutionVec; + uint32_t size = rootValue["Resolution"][formatStr].size(); + for (uint32_t i = 0; i < size; i++) { + std::string resoStr = rootValue["Resolution"][formatStr][i].asString(); + std::vector reso; + SplitString(resoStr, reso, STAR_SEPARATOR); + if (reso.size() != SIZE_FMT_LEN) { + continue; + } + uint32_t width = static_cast(std::atoi(reso[0].c_str())); + uint32_t height = static_cast(std::atoi(reso[1].c_str())); + if (height == 0 || width == 0 || + (isPhotoFormat && (width > MAX_SUPPORT_PHOTO_WIDTH || height > MAX_SUPPORT_PHOTO_HEIGHT)) || + (!isPhotoFormat && + (width > MAX_SUPPORT_PREVIEW_WIDTH || height > MAX_SUPPORT_PREVIEW_HEIGHT))) { + continue; + } + DCResolution resolution(width, height); + resolutionVec.push_back(resolution); + } + if (!resolutionVec.empty()) { + std::sort(resolutionVec.begin(), resolutionVec.end()); + supportedFormats[format] = resolutionVec; + + if (!isPhotoFormat && (maxPreviewResolution_ < resolutionVec[0])) { + maxPreviewResolution_.width_ = resolutionVec[0].width_; + maxPreviewResolution_.height_ = resolutionVec[0].height_; + } + if (isPhotoFormat && (maxPhotoResolution_ < resolutionVec[0])) { + maxPhotoResolution_.width_ = resolutionVec[0].width_; + maxPhotoResolution_.height_ = resolutionVec[0].height_; + } + } + } + } + return supportedFormats; +} + +void DMetadataProcessor::PrintDCameraMetadata(const common_metadata_header_t *metadata) +{ + if (metadata == nullptr) { + DHLOGE("Failed to print metadata, input metadata is null."); + return; + } + + uint32_t tagCount = CameraStandard::GetCameraMetadataItemCount(metadata); + DHLOGD("DMetadataProcessor::PrintDCameraMetadata, input metadata item count = %d.", tagCount); + for (uint32_t i = 0; i < tagCount; i++) { + camera_metadata_item_t item; + int ret = CameraStandard::GetCameraMetadataItem(metadata, i, &item); + if (ret != 0) { + continue; + } + + const char *name = CameraStandard::GetCameraMetadataItemName(item.item); + if (item.data_type == META_TYPE_BYTE) { + for (size_t k = 0; k < item.count; k++) { + DHLOGI("tag index:%d, name:%s, value:%d", item.index, name, (uint8_t)(item.data.u8[k])); + } + } else if (item.data_type == META_TYPE_INT32) { + for (size_t k = 0; k < item.count; k++) { + DHLOGI("tag index:%d, name:%s, value:%d", item.index, name, (int32_t)(item.data.i32[k])); + } + } else if (item.data_type == META_TYPE_UINT32) { + for (size_t k = 0; k < item.count; k++) { + DHLOGI("tag index:%d, name:%s, value:%d", item.index, name, (uint32_t)(item.data.ui32[k])); + } + } else if (item.data_type == META_TYPE_FLOAT) { + for (size_t k = 0; k < item.count; k++) { + DHLOGI("tag index:%d, name:%s, value:%f", item.index, name, (float)(item.data.f[k])); + } + } else if (item.data_type == META_TYPE_INT64) { + for (size_t k = 0; k < item.count; k++) { + DHLOGI("tag index:%d, name:%s, value:%lld", item.index, name, (long long)(item.data.i64[k])); + } + } else if (item.data_type == META_TYPE_DOUBLE) { + for (size_t k = 0; k < item.count; k++) { + DHLOGI("tag index:%d, name:%s, value:%lf", item.index, name, (double)(item.data.d[k])); + } + } else { + DHLOGI("tag index:%d, name:%s, value:%d", item.index, name, *(item.data.r)); + } + } +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/dcamera_host/dcamera_host.cpp b/camera_hdf/hdi_impl/src/dcamera_host/dcamera_host.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfc23c9a9aa539861fd4ee1cd59f53f29d4858fb --- /dev/null +++ b/camera_hdf/hdi_impl/src/dcamera_host/dcamera_host.cpp @@ -0,0 +1,232 @@ +/* + * 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 "dcamera_host.h" +#include "anonymous_string.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +std::shared_ptr DCameraHost::instance_ = nullptr; +DCameraHost::AutoRelease DCameraHost::autoRelease_; + +std::shared_ptr DCameraHost::GetInstance() +{ + if (instance_ == nullptr) { + instance_ = std::make_shared(); + if (instance_ == nullptr) { + DHLOGE("Get distributed camera host instance failed."); + return nullptr; + } + } + return instance_; +} + +CamRetCode DCameraHost::SetCallback(const OHOS::sptr &callback) +{ + if (callback == nullptr) { + DHLOGE("DCameraHost::SetCallback, camera host callback is null."); + return CamRetCode::INVALID_ARGUMENT; + } + dCameraHostCallback_ = callback; + return CamRetCode::NO_ERROR; +} + +CamRetCode DCameraHost::GetCameraIds(std::vector &cameraIds) +{ + auto iter = dhBaseHashDCamIdMap_.begin(); + while (iter != dhBaseHashDCamIdMap_.end()) { + if (!(iter->second).empty()) { + cameraIds.push_back(iter->second); + } + iter++; + } + return CamRetCode::NO_ERROR; +} + +CamRetCode DCameraHost::GetCameraAbility(const std::string &cameraId, + std::shared_ptr &ability) +{ + DHLOGE("DCameraHost::GetCameraAbility for cameraId: %s", cameraId.c_str()); + + if (IsCameraIdInvalid(cameraId)) { + DHLOGE("DCameraHost::GetCameraAbility, invalid camera id."); + return CamRetCode::INVALID_ARGUMENT; + } + + auto iter = dCameraDeviceMap_.find(cameraId); + return (iter->second)->GetDCameraAbility(ability); +} + +CamRetCode DCameraHost::OpenCamera(const std::string &cameraId, + const OHOS::sptr &callback, + OHOS::sptr &pDevice) +{ + DHLOGI("DCameraHost::OpenCamera for cameraId: %s", cameraId.c_str()); + + if (IsCameraIdInvalid(cameraId) || callback == nullptr) { + DHLOGE("DCameraHost::OpenCamera, open camera id is empty or callback is null."); + return CamRetCode::INVALID_ARGUMENT; + } + + auto iter = dCameraDeviceMap_.find(cameraId); + if (iter == dCameraDeviceMap_.end()) { + DHLOGE("DCameraHost::OpenCamera, dcamera device not found."); + return CamRetCode::INSUFFICIENT_RESOURCES; + } + + OHOS::sptr dcameraDevice = iter->second; + if (dcameraDevice == nullptr) { + DHLOGE("DCameraHost::OpenCamera, dcamera device is null."); + return INSUFFICIENT_RESOURCES; + } + + if (dcameraDevice->IsOpened()) { + DHLOGE("DCameraHost::OpenCamera, dcamera device %s already opened.", cameraId.c_str()); + return CamRetCode::CAMERA_BUSY; + } + + CamRetCode ret = dcameraDevice->OpenDCamera(callback); + if (ret != CamRetCode::NO_ERROR) { + DHLOGE("DCameraHost::OpenCamera, open camera failed."); + return ret; + } + pDevice = dcameraDevice; + + DHLOGI("DCameraHost::OpenCamera, open camera %s success.", cameraId.c_str()); + return CamRetCode::NO_ERROR; +} + +CamRetCode DCameraHost::SetFlashlight(const std::string &cameraId, bool &isEnable) +{ + (void)cameraId; + (void)isEnable; + DHLOGI("DCameraHost::SetFlashlight, distributed camera not support."); + + return CamRetCode::METHOD_NOT_SUPPORTED; +} + +DCamRetCode DCameraHost::AddDCameraDevice(const std::shared_ptr &dhBase, const std::string &abilityInfo, + const sptr &callback) +{ + DHLOGI("DCameraHost::AddDCameraDevice for {devId: %s, dhId: %s}", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + OHOS::sptr dcameraDevice = new (std::nothrow) DCameraDevice(dhBase, abilityInfo); + if (dcameraDevice == nullptr) { + DHLOGE("DCameraHost::AddDCameraDevice, create dcamera device failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + std::string dCameraId = dcameraDevice->GetDCameraId(); + dCameraDeviceMap_[dCameraId] = dcameraDevice; + DHBase dhBaseKey(dhBase->deviceId_, dhBase->dhId_); + dhBaseHashDCamIdMap_.emplace(dhBaseKey, dCameraId); + dcameraDevice->SetProviderCallback(callback); + + if (dCameraHostCallback_ != nullptr) { + dCameraHostCallback_->OnCameraEvent(dCameraId, CameraEvent::CAMERA_EVENT_DEVICE_ADD); + } + + DHLOGI("DCameraHost::AddDCameraDevice, create dcamera device success, dCameraId: %s", dCameraId.c_str()); + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraHost::RemoveDCameraDevice(const std::shared_ptr &dhBase) +{ + DHLOGI("DCameraHost::RemoveDCameraDevice for {devId: %s, dhId: %s}", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + std::string dCameraId = GetCameraIdByDHBase(dhBase); + if (dCameraId.empty()) { + DHLOGE("DCameraHost::RemoveDCameraDevice, dhBase not exist."); + return DCamRetCode::INVALID_ARGUMENT; + } + + OHOS::sptr dcameraDevice = GetDCameraDeviceByDHBase(dhBase); + if (dcameraDevice != nullptr) { + if (dcameraDevice->IsOpened()) { + dcameraDevice->Close(); + } + dcameraDevice->SetProviderCallback(nullptr); + } + + DHBase dhBaseKey(dhBase->deviceId_, dhBase->dhId_); + dhBaseHashDCamIdMap_.erase(dhBaseKey); + dCameraDeviceMap_.erase(dCameraId); + + if (dCameraHostCallback_ != nullptr) { + dCameraHostCallback_->OnCameraEvent(dCameraId, CameraEvent::CAMERA_EVENT_DEVICE_RMV); + } + + DHLOGI("DCameraHost::RemoveDCameraDevice, remove dcamera device success, dCameraId: %s", dCameraId.c_str()); + return DCamRetCode::SUCCESS; +} + +bool DCameraHost::IsCameraIdInvalid(const std::string &cameraId) +{ + if (cameraId.empty()) { + return true; + } + + auto iter = dhBaseHashDCamIdMap_.begin(); + while (iter != dhBaseHashDCamIdMap_.end()) { + if (cameraId == iter->second) { + return false; + } + iter++; + } + return true; +} + +std::string DCameraHost::GetCameraIdByDHBase(const std::shared_ptr &dhBase) +{ + DHBase dhBaseKey(dhBase->deviceId_, dhBase->dhId_); + auto iter = dhBaseHashDCamIdMap_.find(dhBaseKey); + if (iter == dhBaseHashDCamIdMap_.end()) { + return ""; + } + return iter->second; +} + +OHOS::sptr DCameraHost::GetDCameraDeviceByDHBase(const std::shared_ptr &dhBase) +{ + std::string dCameraId = GetCameraIdByDHBase(dhBase); + if (dCameraId.empty()) { + DHLOGE("DCameraHost::GetDCameraDeviceByDHBase, dhBase not exist."); + return nullptr; + } + + auto iter = dCameraDeviceMap_.find(dCameraId); + if (iter == dCameraDeviceMap_.end()) { + DHLOGE("DCameraHost::GetDCameraDeviceByDHBase, dcamera device not found."); + return nullptr; + } + return iter->second; +} + +void DCameraHost::NotifyDCameraStatus(const std::shared_ptr &dhBase, int32_t result) +{ + std::string dCameraId = GetCameraIdByDHBase(dhBase); + if (dCameraId.empty()) { + DHLOGE("DCameraHost::NotifyDCameraStatus, dhBase not exist."); + return; + } + if (dCameraHostCallback_ != nullptr) { + dCameraHostCallback_->OnCameraStatus(dCameraId, CameraStatus::UN_AVAILABLE); + } +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/dcamera_provider/dcamera_provider.cpp b/camera_hdf/hdi_impl/src/dcamera_provider/dcamera_provider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..009d6fe83265ae149fee2e3a33c9f7977921c8c3 --- /dev/null +++ b/camera_hdf/hdi_impl/src/dcamera_provider/dcamera_provider.cpp @@ -0,0 +1,306 @@ +/* + * 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 "dcamera_provider.h" +#include "anonymous_string.h" +#include "constants.h" +#include "dcamera_device.h" +#include "dcamera_host.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +std::shared_ptr DCameraProvider::instance_ = nullptr; +DCameraProvider::AutoRelease DCameraProvider::autoRelease_; + +std::shared_ptr DCameraProvider::GetInstance() +{ + if (instance_ == nullptr) { + instance_ = std::make_shared(); + if (instance_ == nullptr) { + DHLOGE("Get distributed camera provider instance failed."); + return nullptr; + } + } + return instance_; +} + +DCamRetCode DCameraProvider::EnableDCameraDevice(const std::shared_ptr &dhBase, + const std::string &abilityInfo, const sptr &callback) +{ + DHLOGI("DCameraProvider::EnableDCameraDevice for {devId: %s, dhId: %s, abilityInfo length: %d}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str(), abilityInfo.length()); + + if (IsDhBaseInfoInvalid(dhBase)) { + DHLOGE("DCameraProvider::EnableDCameraDevice, devId or dhId is invalid."); + return DCamRetCode::INVALID_ARGUMENT; + } + if (abilityInfo.empty()) { + DHLOGE("DCameraProvider::EnableDCameraDevice, dcamera ability is empty."); + return DCamRetCode::INVALID_ARGUMENT; + } + if (callback == nullptr) { + DHLOGE("DCameraProvider::EnableDCameraDevice, dcamera provider callback is null."); + return DCamRetCode::INVALID_ARGUMENT; + } + + std::shared_ptr dCameraHost = DCameraHost::GetInstance(); + if (dCameraHost == nullptr) { + DHLOGE("DCameraProvider::EnableDCameraDevice, dcamera host is null."); + return DCamRetCode::DEVICE_NOT_INIT; + } + DCamRetCode ret = dCameraHost->AddDCameraDevice(dhBase, abilityInfo, callback); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("DCameraProvider::EnableDCameraDevice failed, ret = %d.", ret); + } + + return ret; +} + +DCamRetCode DCameraProvider::DisableDCameraDevice(const std::shared_ptr &dhBase) +{ + DHLOGI("DCameraProvider::DisableDCameraDevice for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + if (IsDhBaseInfoInvalid(dhBase)) { + DHLOGE("DCameraProvider::DisableDCameraDevice, devId or dhId is invalid."); + return DCamRetCode::INVALID_ARGUMENT; + } + + std::shared_ptr dCameraHost = DCameraHost::GetInstance(); + if (dCameraHost == nullptr) { + DHLOGE("DCameraProvider::DisableDCameraDevice, dcamera host is null."); + return DCamRetCode::DEVICE_NOT_INIT; + } + DCamRetCode ret = dCameraHost->RemoveDCameraDevice(dhBase); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("DCameraProvider::DisableDCameraDevice failed, ret = %d.", ret); + return ret; + } + + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraProvider::AcquireBuffer(const std::shared_ptr &dhBase, int streamId, + std::shared_ptr &buffer) +{ + DHLOGI("DCameraProvider::AcquireBuffer for {devId: %s, dhId: %s}, streamId: %d.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str(), streamId); + + OHOS::sptr device = GetDCameraDevice(dhBase); + if (device == nullptr) { + DHLOGE("DCameraProvider::AcquireBuffer failed, dcamera device not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + return device->AcquireBuffer(streamId, buffer); +} + +DCamRetCode DCameraProvider::ShutterBuffer(const std::shared_ptr &dhBase, int streamId, + const std::shared_ptr &buffer) +{ + if (buffer == nullptr) { + DHLOGE("DCameraProvider::ShutterBuffer, input distributed camera buffer is null."); + return DCamRetCode::INVALID_ARGUMENT; + } + DHLOGI("DCameraProvider::ShutterBuffer for {devId: %s, dhId: %s}, streamId = %d, buffer index = %d.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str(), streamId, buffer->index_); + + OHOS::sptr device = GetDCameraDevice(dhBase); + if (device == nullptr) { + DHLOGE("DCameraProvider::ShutterBuffer failed, dcamera device not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + return device->ShutterBuffer(streamId, buffer); +} + +DCamRetCode DCameraProvider::OnSettingsResult(const std::shared_ptr &dhBase, + const std::shared_ptr &result) +{ + DHLOGI("DCameraProvider::OnSettingsResult for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + OHOS::sptr device = GetDCameraDevice(dhBase); + if (device == nullptr) { + DHLOGE("DCameraProvider::OnSettingsResult failed, dcamera device not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + return device->OnSettingsResult(result); +} + +DCamRetCode DCameraProvider::Notify(const std::shared_ptr &dhBase, + const std::shared_ptr &event) +{ + DHLOGI("DCameraProvider::Notify for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + OHOS::sptr device = GetDCameraDevice(dhBase); + if (device == nullptr) { + DHLOGE("DCameraProvider::Notify failed, dcamera device not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + return device->Notify(event); +} + +DCamRetCode DCameraProvider::OpenSession(const std::shared_ptr &dhBase) +{ + DHLOGI("DCameraProvider::OpenSession for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + sptr callback = GetCallbackBydhBase(dhBase); + if (callback == nullptr) { + DHLOGE("DCameraProvider::OpenSession, dcamera provider callback not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + return callback->OpenSession(dhBase); +} + +DCamRetCode DCameraProvider::CloseSession(const std::shared_ptr &dhBase) +{ + DHLOGI("DCameraProvider::CloseSession for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + sptr callback = GetCallbackBydhBase(dhBase); + if (callback == nullptr) { + DHLOGE("DCameraProvider::CloseSession, dcamera provider callback not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + return callback->CloseSession(dhBase); +} + +DCamRetCode DCameraProvider::ConfigureStreams(const std::shared_ptr &dhBase, + const std::vector> &streamInfos) +{ + DHLOGI("DCameraProvider::ConfigureStreams for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + sptr callback = GetCallbackBydhBase(dhBase); + if (callback == nullptr) { + DHLOGE("DCameraProvider::ConfigStreams, dcamera provider callback not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + for (auto info : streamInfos) { + DHLOGI("ConfigureStreams: id=%d, width=%d, height=%d, format=%d, " + + "type=%d.", info->streamId_, info->width_, info->height_, info->format_, info->type_); + } + return callback->ConfigureStreams(dhBase, streamInfos); +} + +DCamRetCode DCameraProvider::ReleaseStreams(const std::shared_ptr &dhBase, + const std::vector &streamIds) +{ + DHLOGI("DCameraProvider::ReleaseStreams for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + sptr callback = GetCallbackBydhBase(dhBase); + if (callback == nullptr) { + DHLOGE("DCameraProvider::ReleaseStreams, dcamera provider callback not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + std::string idString = ""; + for (int id : streamIds) { + idString += (std::to_string(id) + ", "); + } + DHLOGI("ReleaseStreams: ids=[%s].", idString.c_str()); + return callback->ReleaseStreams(dhBase, streamIds); +} + +DCamRetCode DCameraProvider::StartCapture(const std::shared_ptr &dhBase, + const std::vector> &captureInfos) +{ + DHLOGI("DCameraProvider::StartCapture for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + sptr callback = GetCallbackBydhBase(dhBase); + if (callback == nullptr) { + DHLOGE("DCameraProvider::StartCapture, dcamera provider callback not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + for (auto info : captureInfos) { + std::string idString = ""; + for (int id : info->streamIds_) { + idString += (std::to_string(id) + ", "); + } + DHLOGI("StartCapture: ids=[%s], width=%d, height=%d, format=%d, type=%d.", + (idString.empty() ? idString.c_str() : (idString.substr(0, idString.length() - INGNORE_STR_LEN)).c_str()), + info->width_, info->height_, info->format_, info->type_); + } + return callback->StartCapture(dhBase, captureInfos); +} + +DCamRetCode DCameraProvider::StopCapture(const std::shared_ptr &dhBase) +{ + DHLOGI("DCameraProvider::StopCapture for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + sptr callback = GetCallbackBydhBase(dhBase); + if (callback == nullptr) { + DHLOGE("DCameraProvider::StopCapture, dcamera provider callback not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + return callback->StopCapture(dhBase); +} + +DCamRetCode DCameraProvider::UpdateSettings(const std::shared_ptr &dhBase, + const std::vector> &settings) +{ + DHLOGI("DCameraProvider::UpdateSettings for {devId: %s, dhId: %s}.", + GetAnonyString(dhBase->deviceId_).c_str(), dhBase->dhId_.c_str()); + + sptr callback = GetCallbackBydhBase(dhBase); + if (callback == nullptr) { + DHLOGE("DCameraProvider::UpdateSettings, dcamera provider callback not found."); + return DCamRetCode::INVALID_ARGUMENT; + } + + return callback->UpdateSettings(dhBase, settings); +} + +bool DCameraProvider::IsDhBaseInfoInvalid(const std::shared_ptr &dhBase) +{ + return dhBase->deviceId_.empty() || (dhBase->deviceId_.size() > DEVID_MAX_LENGTH) || + dhBase->dhId_.empty() || (dhBase->dhId_.size() > DHID_MAX_LENGTH); +} + +sptr DCameraProvider::GetCallbackBydhBase(const std::shared_ptr &dhBase) +{ + OHOS::sptr device = GetDCameraDevice(dhBase); + if (device == nullptr) { + DHLOGE("DCameraProvider::GetCallbackBydhBase failed, dcamera device not found."); + return nullptr; + } + return device->GetProviderCallback(); +} + +OHOS::sptr DCameraProvider::GetDCameraDevice(const std::shared_ptr &dhBase) +{ + std::shared_ptr dCameraHost = DCameraHost::GetInstance(); + if (dCameraHost == nullptr) { + DHLOGE("DCameraProvider::GetDCameraDevice, dcamera host is null."); + return nullptr; + } + return dCameraHost->GetDCameraDeviceByDHBase(dhBase); +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/dstream_operator/dbuffer_manager.cpp b/camera_hdf/hdi_impl/src/dstream_operator/dbuffer_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4514863ba8208d4c7b86f1407f24da66f87f1d5f --- /dev/null +++ b/camera_hdf/hdi_impl/src/dstream_operator/dbuffer_manager.cpp @@ -0,0 +1,162 @@ +/* + * 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 "dbuffer_manager.h" +#include +#include "distributed_camera_constants.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +std::shared_ptr DBufferManager::AcquireBuffer() +{ + std::unique_lock l(lock_); + + if (!idleList_.empty()) { + auto it = idleList_.begin(); + busyList_.splice(busyList_.begin(), idleList_, it); + DHLOGI("Acquire buffer success, index = %d", (*it)->GetIndex()); + return *it; + } + return nullptr; +} + +RetCode DBufferManager::AddBuffer(std::shared_ptr& buffer) +{ + std::unique_lock l(lock_); + if (idleList_.size() + busyList_.size() >= BUFFER_QUEUE_SIZE) { + DHLOGI("Buffer list is full, cannot add buffer."); + return RC_ERROR; + } + idleList_.emplace_back(buffer); + + return RC_OK; +} + +RetCode DBufferManager::RemoveBuffer(std::shared_ptr& buffer) +{ + std::unique_lock l(lock_); + + auto it = std::find(busyList_.begin(), busyList_.end(), buffer); + if (it == busyList_.end()) { + DHLOGE("Busy list is empty, cannot remove buffer."); + return RC_ERROR; + } + busyList_.erase(it); + + return RC_OK; +} + +void DBufferManager::NotifyStop(bool state) +{ + streamStop_ = state; +} + +RetCode DBufferManager::SurfaceBufferToDImageBuffer(const OHOS::sptr &surfaceBuffer, + const std::shared_ptr &buffer) +{ + if (surfaceBuffer == nullptr) { + DHLOGE("Convert surface buffer failed, surfaceBuffer is null."); + return RC_ERROR; + } + + BufferHandle *bufHandle = surfaceBuffer->GetBufferHandle(); + if (bufHandle == nullptr) { + DHLOGE("Convert surface buffer failed, BufferHandle is null."); + return RC_ERROR; + } + if ((bufHandle->size <= 0) || (bufHandle->width <= 0) || (bufHandle->height <= 0) || (bufHandle->usage <= 0)) { + DHLOGE("Convert surface buffer failed, BufferHandle is invalid."); + return RC_ERROR; + } + + buffer->SetPhyAddress(bufHandle->phyAddr); + buffer->SetFileDescriptor(bufHandle->fd); + buffer->SetStride(bufHandle->stride); + buffer->SetWidth(bufHandle->width); + buffer->SetHeight(bufHandle->height); + buffer->SetFormat(PixelFormatToDCameraFormat(static_cast(bufHandle->format))); + buffer->SetUsage(CameraUsageToGrallocUsage(bufHandle->usage)); + buffer->SetSize(static_cast(bufHandle->size)); + buffer->SetBufferHandle(bufHandle); + + return RC_OK; +} + +uint64_t DBufferManager::CameraUsageToGrallocUsage(const uint64_t cameraUsage) +{ + uint64_t grallocUsage = 0; + uint64_t test = 1; + const uint32_t BYTE = 8; + for (uint32_t i = 0; i < sizeof(cameraUsage) * BYTE; i++) { + switch (cameraUsage & (test << i)) { + case CAMERA_USAGE_SW_READ_OFTEN: + grallocUsage |= HBM_USE_CPU_READ; + break; + case CAMERA_USAGE_SW_WRITE_OFTEN: + grallocUsage |= HBM_USE_CPU_WRITE; + break; + case CAMERA_USAGE_MEM_DMA: + grallocUsage |= HBM_USE_MEM_DMA; + break; + default: + break; + } + } + + return grallocUsage; +} + +uint32_t DBufferManager::PixelFormatToDCameraFormat(const PixelFormat format) +{ + uint32_t cameraFormat = OHOS_CAMERA_FORMAT_INVALID; + switch (format) { + case PIXEL_FMT_RGBA_8888: + cameraFormat = OHOS_CAMERA_FORMAT_RGBA_8888; + break; + case PIXEL_FMT_YCBCR_420_SP: + cameraFormat = OHOS_CAMERA_FORMAT_YCBCR_420_888; + break; + case PIXEL_FMT_YCRCB_420_SP: + cameraFormat = OHOS_CAMERA_FORMAT_YCRCB_420_SP; + break; + default: + cameraFormat = OHOS_CAMERA_FORMAT_INVALID; + break; + } + + return cameraFormat; +} + +RetCode DBufferManager::DImageBufferToDCameraBuffer(const std::shared_ptr &imageBuffer, + std::shared_ptr &buffer) +{ + BufferHandle *bufHandle = imageBuffer->GetBufferHandle(); + if (bufHandle == nullptr) { + DHLOGE("Convert image surface buffer failed, BufferHandle is null."); + return RC_ERROR; + } + if ((bufHandle->size <= 0) || (bufHandle->width <= 0) || (bufHandle->height <= 0) || (bufHandle->usage <= 0)) { + DHLOGE("Convert image surface buffer failed, BufferHandle is invalid."); + return RC_ERROR; + } + buffer->index_ = imageBuffer->GetIndex(); + buffer->size_ = imageBuffer->GetSize(); + buffer->bufferHandle_ = bufHandle; + + return RC_OK; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/dstream_operator/dcamera_steam.cpp b/camera_hdf/hdi_impl/src/dstream_operator/dcamera_steam.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06ac97e9347597467fc9ec90e9019b6047828eb9 --- /dev/null +++ b/camera_hdf/hdi_impl/src/dstream_operator/dcamera_steam.cpp @@ -0,0 +1,363 @@ +/* + * 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 "dcamera_steam.h" +#include +#include +#include "constants.h" +#include "dcamera.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCamRetCode DCameraStream::InitDCameraStream(const shared_ptr &info) +{ + if ((info->streamId_ < 0) || (info->width_ < 0) || (info->height_ < 0) || + (info->format_ < 0) || (info->datasapce_ < 0)) { + DHLOGE("Stream info is invalid."); + return DCamRetCode::INVALID_ARGUMENT; + } + dcStreamId_ = info->streamId_; + dcStreamInfo_ = std::make_shared(); + dcStreamInfo_->streamId_ = info->streamId_; + dcStreamInfo_->width_ = info->width_; + dcStreamInfo_->height_ = info->height_; + dcStreamInfo_->format_ = info->format_; + dcStreamInfo_->datasapce_ = info->datasapce_; + dcStreamInfo_->intent_ = info->intent_; + dcStreamInfo_->tunneledMode_ = info->tunneledMode_; + dcStreamInfo_->bufferQueue_ = info->bufferQueue_; + dcStreamInfo_->minFrameDuration_ = info->minFrameDuration_; + + if (dcStreamAttribute_ == nullptr) { + dcStreamAttribute_ = std::make_shared(); + if (dcStreamAttribute_ == nullptr) { + return DCamRetCode::FAILED; + } + } + dcStreamAttribute_->streamId_ = dcStreamInfo_->streamId_; + dcStreamAttribute_->width_ = dcStreamInfo_->width_; + dcStreamAttribute_->height_ = dcStreamInfo_->height_; + dcStreamAttribute_->overrideFormat_ = dcStreamInfo_->format_; + dcStreamAttribute_->overrideDatasapce_ = dcStreamInfo_->datasapce_; + dcStreamAttribute_->producerUsage_ = HBM_USE_CPU_READ | HBM_USE_CPU_WRITE | HBM_USE_MEM_DMA; + + dcStreamAttribute_->producerBufferCount_ = BUFFER_QUEUE_SIZE; + dcStreamAttribute_->maxBatchCaptureCount_ = BUFFER_QUEUE_SIZE; + dcStreamAttribute_->maxCaptureCount_ = 1; + + DCamRetCode ret = DCamRetCode::SUCCESS; + if (dcStreamInfo_->bufferQueue_ != nullptr) { + DCamRetCode ret = InitDCameraBufferManager(); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Cannot init buffer manager."); + } + } + return ret; +} + +DCamRetCode DCameraStream::InitDCameraBufferManager() +{ + if (dcStreamInfo_ == nullptr) { + DHLOGE("Distributed camera stream info is invalid."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (dcStreamInfo_->bufferQueue_ != nullptr) { + dcStreamProducer_ = OHOS::Surface::CreateSurfaceAsProducer(dcStreamInfo_->bufferQueue_); + } + if (dcStreamProducer_ == nullptr) { + DHLOGE("Distributed camera stream producer is invalid."); + return DCamRetCode::INVALID_ARGUMENT; + } + dcStreamBufferMgr_ = std::make_shared(); + + DCamRetCode ret = DCamRetCode::SUCCESS; + if (!isBufferMgrInited_) { + ret = FinishCommitStream(); + } + return ret; +} + +DCamRetCode DCameraStream::GetDCameraStreamInfo(shared_ptr &info) +{ + if (!dcStreamInfo_) { + DHLOGE("Distributed camera stream info is not init."); + return DCamRetCode::FAILED; + } + info = dcStreamInfo_; + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraStream::SetDCameraBufferQueue(const OHOS::sptr producer) +{ + if (dcStreamInfo_->bufferQueue_) { + DHLOGE("Stream [%d] has already have bufferQueue.", dcStreamId_); + return DCamRetCode::SUCCESS; + } + + dcStreamInfo_->bufferQueue_ = producer; + DCamRetCode ret = InitDCameraBufferManager(); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Init distributed camera buffer manager failed."); + } + return ret; +} + +DCamRetCode DCameraStream::ReleaseDCameraBufferQueue() +{ + DCamRetCode ret = FlushDCameraBuffer(); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Release distributed camera buffer queue failed."); + return ret; + } + dcStreamInfo_->bufferQueue_ = nullptr; + dcStreamProducer_ = nullptr; + dcStreamBufferMgr_ = nullptr; + + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraStream::GetDCameraStreamAttribute(shared_ptr &attribute) +{ + attribute = dcStreamAttribute_; + if (attribute == nullptr) { + return DCamRetCode::INVALID_ARGUMENT; + } + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraStream::FinishCommitStream() +{ + if (isBufferMgrInited_) { + DHLOGI("Stream already inited."); + return DCamRetCode::SUCCESS; + } + if (dcStreamProducer_ == nullptr) { + DHLOGI("No bufferQueue."); + return DCamRetCode::SUCCESS; + } + dcStreamProducer_->SetQueueSize(BUFFER_QUEUE_SIZE); + isBufferMgrInited_ = true; + + for (uint32_t i = 0; i < BUFFER_QUEUE_SIZE; i++) { + GetNextRequest(); + } + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraStream::GetNextRequest() +{ + if (isBufferMgrInited_ == false) { + DHLOGE("BufferManager not be init."); + return DCamRetCode::INVALID_ARGUMENT; + } + if (dcStreamInfo_ == nullptr) { + DHLOGE("Cannot create buffer manager by invalid streaminfo."); + return DCamRetCode::INVALID_ARGUMENT; + } + if (dcStreamProducer_ == nullptr) { + DHLOGE("Cannot create a buffer manager by invalid bufferqueue."); + return DCamRetCode::INVALID_ARGUMENT; + } + + OHOS::sptr surfaceBuffer = nullptr; + int32_t fence = -1; + int32_t usage = HBM_USE_CPU_READ | HBM_USE_CPU_WRITE | HBM_USE_MEM_DMA; + OHOS::BufferRequestConfig config = { + .width = dcStreamInfo_->width_, + .height = dcStreamInfo_->height_, + .strideAlignment = 8, + .format = dcStreamInfo_->format_, + .usage = usage, + .timeout = 0 + }; + + OHOS::SurfaceError surfaceError = dcStreamProducer_->RequestBuffer(surfaceBuffer, fence, config); + if (surfaceError == OHOS::SURFACE_ERROR_NO_BUFFER) { + DHLOGE("No availiable buffer to request in surface."); + return DCamRetCode::EXCEED_MAX_NUMBER; + } + + if (surfaceError != OHOS::SURFACE_ERROR_OK || surfaceBuffer == nullptr) { + DHLOGE("Get producer buffer failed. [streamId = %d] [sfError = %d]", dcStreamInfo_->streamId_, surfaceError); + return DCamRetCode::EXCEED_MAX_NUMBER; + } + + std::shared_ptr imageBuffer = std::make_shared(); + auto surface = OHOS::SurfaceBufferImpl::FromBase(surfaceBuffer); + RetCode ret = DBufferManager::SurfaceBufferToDImageBuffer(surface, imageBuffer); + if (ret != RC_OK) { + DHLOGE("Convert surface buffer to image buffer failed, streamId = %d.", dcStreamInfo_->streamId_); + return DCamRetCode::EXCEED_MAX_NUMBER; + } + + imageBuffer->SetIndex(++index_); + imageBuffer->SetFenceId(fence); + ret = dcStreamBufferMgr_->AddBuffer(imageBuffer); + if (ret != RC_OK) { + DHLOGE("Add buffer to buffer manager failed. [streamId = %d]", dcStreamInfo_->streamId_); + return DCamRetCode::EXCEED_MAX_NUMBER; + } + DHLOGI("Add new image buffer success: index = %d, fence = %d", imageBuffer->GetIndex(), fence); + + auto itr = bufferConfigMap_.find(imageBuffer); + if (itr == bufferConfigMap_.end()) { + auto bufferCfg = std::make_tuple(surfaceBuffer, fence, usage); + bufferConfigMap_.insert(std::make_pair(imageBuffer, bufferCfg)); + } + + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraStream::GetDCameraBuffer(shared_ptr &buffer) +{ + DCamRetCode retCode = GetNextRequest(); + if (retCode != DCamRetCode::SUCCESS && retCode != DCamRetCode::EXCEED_MAX_NUMBER) { + DHLOGE("Get next request failed."); + return retCode; + } + + std::shared_ptr imageBuffer = dcStreamBufferMgr_->AcquireBuffer(); + if (imageBuffer == nullptr) { + DHLOGE("Cannot get idle buffer."); + return DCamRetCode::EXCEED_MAX_NUMBER; + } + + RetCode ret = DBufferManager::DImageBufferToDCameraBuffer(imageBuffer, buffer); + if (ret != RC_OK) { + DHLOGE("Convert image buffer to distributed camera buffer failed."); + return DCamRetCode::FAILED; + } + captureBufferCount_++; + + DHLOGI("Get buffer success. address = %p, index = %d, size = %d", buffer->bufferHandle_->virAddr, + buffer->index_, buffer->size_); + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraStream::ReturnDCameraBuffer(const shared_ptr &buffer) +{ + if (buffer == nullptr) { + DHLOGE("result buffer is null. [streamId = %d]", dcStreamInfo_->streamId_); + return DCamRetCode::INVALID_ARGUMENT; + } + + shared_ptr imageBuffer = nullptr; + map, tuple, int, int>>::iterator iter; + for (iter = bufferConfigMap_.begin(); iter != bufferConfigMap_.end(); ++iter) { + if (buffer->index_ == iter->first->GetIndex()) { + imageBuffer = iter->first; + break; + } + } + if (imageBuffer == nullptr) { + DHLOGE("Cannot found image buffer, buffer index = %d.", buffer->index_); + return DCamRetCode::INVALID_ARGUMENT; + } + + RetCode ret = dcStreamBufferMgr_->RemoveBuffer(imageBuffer); + if (ret != RC_OK) { + DHLOGE("Buffer manager remove buffer failed: %d", ret); + } + + auto bufCfg = bufferConfigMap_.find(imageBuffer); + if (bufCfg == bufferConfigMap_.end()) { + DHLOGE("Cannot get bufferConfig."); + return INVALID_ARGUMENT; + } + auto surfaceBuffer = std::get<0>(bufCfg->second); + int32_t fence = std::get<1>(bufCfg->second); + OHOS::BufferFlushConfig flushConf = { + .damage = { .x = 0, .y = 0, .w = dcStreamInfo_->width_, .h = dcStreamInfo_->height_ }, + .timestamp = 0 + }; + if (dcStreamProducer_ != nullptr) { + if (dcStreamInfo_->intent_ == StreamIntent::VIDEO) { + int32_t size = (dcStreamInfo_->width_) * (dcStreamInfo_->height_) * YUV_WIDTH_RATIO / YUV_HEIGHT_RATIO; + int64_t timeStamp = static_cast(GetCurrentLocalTimeStamp()); + surfaceBuffer->ExtraSet("dataSize", size); + surfaceBuffer->ExtraSet("isKeyFrame", (int32_t)0); + surfaceBuffer->ExtraSet("timeStamp", timeStamp); + } + int ret = dcStreamProducer_->FlushBuffer(surfaceBuffer, fence, flushConf); + if (ret != 0) { + DHLOGI("FlushBuffer error: %d", ret); + } + } + bufferConfigMap_.erase(bufCfg); + { + captureBufferCount_--; + cv_.notify_one(); + } + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraStream::FlushDCameraBuffer() +{ + if (dcStreamBufferMgr_ == nullptr || dcStreamProducer_ == nullptr) { + DHLOGE("BufferManager or Producer is null."); + return DCamRetCode::SUCCESS; + } + + if (captureBufferCount_ != 0) { + DHLOGI("StreamId:%d has request that not return, captureBufferCount=%d", + dcStreamInfo_->streamId_, captureBufferCount_); + } + { + std::unique_lock l(lock_); + cv_.wait(l, [this] { return !captureBufferCount_; }); + } + + while (true) { + std::shared_ptr imageBuffer = dcStreamBufferMgr_->AcquireBuffer(); + if (imageBuffer == nullptr) { + auto bufCfg = bufferConfigMap_.find(imageBuffer); + if (bufCfg == bufferConfigMap_.end()) { + DHLOGE("Buffer not in map."); + return DCamRetCode::INVALID_ARGUMENT; + } + auto surfaceBuffer = std::get<0>(bufCfg->second); + int32_t fence = std::get<1>(bufCfg->second); + OHOS::BufferFlushConfig flushConf = { + .damage = { + .x = 0, + .y = 0, + .w = dcStreamInfo_->width_, + .h = dcStreamInfo_->height_ }, + .timestamp = 0 + }; + if (dcStreamProducer_ != nullptr) { + dcStreamProducer_->FlushBuffer(surfaceBuffer, fence, flushConf); + } + bufferConfigMap_.erase(bufCfg); + } else { + break; + } + } + captureBufferCount_ = 0; + index_ = -1; + return DCamRetCode::SUCCESS; +} + +bool DCameraStream::HasBufferQueue() +{ + if (dcStreamProducer_ == nullptr || isBufferMgrInited_ == false) { + return false; + } + return true; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/dstream_operator/dimage_buffer.cpp b/camera_hdf/hdi_impl/src/dstream_operator/dimage_buffer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7380342af628c96b4195ee03b1e55e97617f1a45 --- /dev/null +++ b/camera_hdf/hdi_impl/src/dstream_operator/dimage_buffer.cpp @@ -0,0 +1,242 @@ +/* + * 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 "dimage_buffer.h" +#include + +namespace OHOS { +namespace DistributedHardware { +DImageBuffer::~DImageBuffer() +{ + Free(); +} + +int32_t DImageBuffer::GetIndex() const +{ + return index_; +} + +uint32_t DImageBuffer::GetWidth() const +{ + return width_; +} + +uint32_t DImageBuffer::GetHeight() const +{ + return height_; +} + +uint32_t DImageBuffer::GetStride() const +{ + return stride_; +} + +int32_t DImageBuffer::GetFormat() const +{ + return format_; +} + +uint32_t DImageBuffer::GetSize() const +{ + return size_; +} + +uint64_t DImageBuffer::GetUsage() const +{ + return usage_; +} + +uint64_t DImageBuffer::GetPhyAddress() const +{ + return phyAddr_; +} + +int32_t DImageBuffer::GetFileDescriptor() const +{ + return fd_; +} + +uint64_t DImageBuffer::GetTimestamp() const +{ + return timeStamp_; +} + +uint64_t DImageBuffer::GetFrameNumber() const +{ + return frameNumber_; +} + +int32_t DImageBuffer::GetCaptureId() const +{ + return captureId_; +} + +bool DImageBuffer::GetValidFlag() const +{ + return valid_; +} + +int32_t DImageBuffer::GetFenceId() const +{ + return fenceId_; +} + +int32_t DImageBuffer::GetEncodeType() const +{ + return encodeType_; +} + +BufferHandle* DImageBuffer::GetBufferHandle() const +{ + return bufHandle_; +} + +void DImageBuffer::SetIndex(const int32_t index) +{ + std::lock_guard l(l_); + index_ = index; + return; +} + +void DImageBuffer::SetWidth(const uint32_t width) +{ + std::lock_guard l(l_); + width_ = width; + return; +} + +void DImageBuffer::SetHeight(const uint32_t height) +{ + std::lock_guard l(l_); + height_ = height; + return; +} + +void DImageBuffer::SetStride(const uint32_t stride) +{ + std::lock_guard l(l_); + stride_ = stride; + return; +} + +void DImageBuffer::SetFormat(const int32_t format) +{ + std::lock_guard l(l_); + format_ = format; + return; +} + +void DImageBuffer::SetSize(const uint32_t size) +{ + std::lock_guard l(l_); + size_ = size; + return; +} + +void DImageBuffer::SetUsage(const uint64_t usage) +{ + std::lock_guard l(l_); + usage_ = usage; + return; +} + +void DImageBuffer::SetPhyAddress(const uint64_t addr) +{ + std::lock_guard l(l_); + phyAddr_ = addr; + return; +} + +void DImageBuffer::SetFileDescriptor(const int32_t fd) +{ + std::lock_guard l(l_); + fd_ = fd; + return; +} + +void DImageBuffer::SetTimestamp(const uint64_t timeStamp) +{ + std::lock_guard l(l_); + timeStamp_ = timeStamp; + return; +} + +void DImageBuffer::SetFrameNumber(const uint64_t frameNumber) +{ + std::lock_guard l(l_); + frameNumber_ = frameNumber; + return; +} + +void DImageBuffer::SetCaptureId(const int32_t id) +{ + std::lock_guard l(l_); + captureId_ = id; + return; +} + +void DImageBuffer::SetValidFlag(const bool flag) +{ + std::lock_guard l(l_); + valid_ = flag; + return; +} + +void DImageBuffer::SetFenceId(const int32_t fence) +{ + std::lock_guard l(l_); + fenceId_ = fence; + return; +} + +void DImageBuffer::SetEncodeType(const int32_t type) +{ + std::lock_guard l(l_); + encodeType_ = type; + return; +} + +void DImageBuffer::SetBufferHandle(const BufferHandle* bufHandle) +{ + std::lock_guard l(l_); + bufHandle_ = const_cast(bufHandle); + return; +} + +void DImageBuffer::Free() +{ + index_ = -1; + width_ = 0; + height_ = 0; + stride_ = 0; + format_ = OHOS_CAMERA_FORMAT_INVALID; + size_ = 0; + usage_ = 0; + bufHandle_ = nullptr; + phyAddr_ = 0; + fd_ = -1; + + return; +} + +bool DImageBuffer::operator==(const DImageBuffer& u) +{ + if (u.GetPhyAddress() == 0 || phyAddr_ == 0) { + return u.GetIndex() == index_; + } + return u.GetPhyAddress() == phyAddr_; +} +} // end namespace DistributedHardware +} // end namespace OHOS diff --git a/camera_hdf/hdi_impl/src/dstream_operator/doffline_stream_operator.cpp b/camera_hdf/hdi_impl/src/dstream_operator/doffline_stream_operator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bcd9d70585912aae66f1ee31010798f09e06acb --- /dev/null +++ b/camera_hdf/hdi_impl/src/dstream_operator/doffline_stream_operator.cpp @@ -0,0 +1,38 @@ +/* + * 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 "doffline_stream_operator.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +CamRetCode DOfflineStreamOperator::CancelCapture(int captureId) +{ + (void)captureId; + return CamRetCode::METHOD_NOT_SUPPORTED; +} + +CamRetCode DOfflineStreamOperator::ReleaseStreams(const std::vector& streamIds) +{ + (void)streamIds; + return CamRetCode::METHOD_NOT_SUPPORTED; +} + +CamRetCode DOfflineStreamOperator::Release() +{ + return CamRetCode::METHOD_NOT_SUPPORTED; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/dstream_operator/dstream_operator.cpp b/camera_hdf/hdi_impl/src/dstream_operator/dstream_operator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..362fa246f766e7593a8b23e2c2bc7b330cd34de6 --- /dev/null +++ b/camera_hdf/hdi_impl/src/dstream_operator/dstream_operator.cpp @@ -0,0 +1,753 @@ +/* + * 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 "dstream_operator.h" +#include "dbuffer_manager.h" +#include "dcamera_provider.h" +#include "dcamera_utils_tools.h" +#include "distributed_hardware_log.h" +#include "json/json.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +DStreamOperator::DStreamOperator(std::shared_ptr &dMetadataProcessor) + : dMetadataProcessor_(dMetadataProcessor) +{ + DHLOGI("DStreamOperator::ctor, instance = %p", this); +} + +CamRetCode DStreamOperator::IsStreamsSupported(OperationMode mode, + const std::shared_ptr &modeSetting, + const std::vector> &info, + StreamSupportType &type) +{ + (void)mode; + (void)type; + + if (modeSetting == nullptr) { + DHLOGE("Input invalid argument: modeSetting:%p.", + modeSetting.get()); + return CamRetCode::INVALID_ARGUMENT; + } + + for (auto it : info) { + int id = it->streamId_; + if (halStreamMap_.find(id) != halStreamMap_.end()) { + DHLOGE("Repeat streamId."); + return CamRetCode::INVALID_ARGUMENT; + } + } + return CamRetCode::METHOD_NOT_SUPPORTED; +} + +CamRetCode DStreamOperator::CreateStreams(const std::vector>& streamInfos) +{ + DHLOGI("DStreamOperator::CreateStreams, input stream info size=%d.", streamInfos.size()); + if (streamInfos.empty()) { + DHLOGE("DStreamOperator::CreateStreams, input stream info is empty."); + return CamRetCode::INVALID_ARGUMENT; + } + + for (auto info : streamInfos) { + if (halStreamMap_.find(info->streamId_) != halStreamMap_.end()) { + return CamRetCode::INVALID_ARGUMENT; + } + if (info->tunneledMode_ != true) { + return CamRetCode::METHOD_NOT_SUPPORTED; + } + + std::shared_ptr dcStream = std::make_shared(); + if (!dcStream) { + DHLOGE("Create distributed camera stream failed."); + return CamRetCode::INSUFFICIENT_RESOURCES; + } + DCamRetCode ret = dcStream->InitDCameraStream(info); + if (ret != SUCCESS) { + DHLOGE("Init distributed camera stream failed."); + return CamRetCode::INVALID_ARGUMENT; + } + halStreamMap_[info->streamId_] = dcStream; + + std::shared_ptr dcStreamInfo = std::make_shared(); + ConvertStreamInfo(info, dcStreamInfo); + dcStreamInfoMap_[info->streamId_] = dcStreamInfo; + + DHLOGI("Create stream info: id=%d, width=%d, height=%d, format=%d, intent=%d", info->streamId_, + info->width_, info->height_, info->format_, info->intent_); + } + DHLOGI("DStreamOperator::Create distributed camera streams success."); + return CamRetCode::NO_ERROR; +} + +CamRetCode DStreamOperator::ReleaseStreams(const std::vector& streamIds) +{ + DHLOGI("DStreamOperator::ReleaseStreams, input stream id list size=%d.", streamIds.size()); + if (IsCapturing()) { + DHLOGE("Can not release streams when capture."); + return CamRetCode::CAMERA_BUSY; + } + + for (int id : streamIds) { + auto iter = halStreamMap_.find(id); + if (iter != halStreamMap_.end()) { + auto stream = iter->second; + DCamRetCode ret = stream->ReleaseDCameraBufferQueue(); + if (ret != SUCCESS) { + DHLOGE("Release distributed camera buffer queue for stream %d failed.", id); + return MapToExternalRetCode(ret); + } else { + DHLOGE("Release distributed camera buffer queue for stream %d successs.", id); + } + stream = nullptr; + halStreamMap_.erase(id); + dcStreamInfoMap_.erase(id); + } else { + DHLOGE("Error streamId %d.", id); + return CamRetCode::INVALID_ARGUMENT; + } + } + + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider == nullptr) { + DHLOGE("Distributed camera provider not init."); + return CamRetCode::DEVICE_ERROR; + } + DCamRetCode ret = provider->ReleaseStreams(dhBase_, streamIds); + if (ret != SUCCESS) { + DHLOGE("Release distributed camera streams failed."); + return MapToExternalRetCode(ret); + } + + DHLOGI("DStreamOperator::Release distributed camera streams success."); + return CamRetCode::NO_ERROR; +} + +CamRetCode DStreamOperator::CommitStreams(OperationMode mode, + const std::shared_ptr& modeSetting) +{ + DHLOGI("DStreamOperator::CommitStreams, input operation mode=%d.", mode); + if (IsCapturing()) { + DHLOGE("Can not commit streams when capture."); + return CamRetCode::CAMERA_BUSY; + } + + if (currentOperMode_ != mode) { + currentOperMode_ = mode; + } + if (modeSetting == nullptr || modeSetting.get() == nullptr) { + DHLOGE("Input stream mode setting is invalid."); + } else { + latestStreamSetting_ = modeSetting; + } + + if (dcStreamInfoMap_.size() == 0) { + DHLOGE("No stream to commit."); + return CamRetCode::INVALID_ARGUMENT; + } + std::vector> dCameraStreams; + for (auto streamInfo : dcStreamInfoMap_) { + dCameraStreams.push_back(streamInfo.second); + } + + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider == nullptr) { + DHLOGE("Distributed camera provider not init."); + return CamRetCode::DEVICE_ERROR; + } + DCamRetCode ret = provider->ConfigureStreams(dhBase_, dCameraStreams); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Commit distributed camera streams failed."); + return MapToExternalRetCode(ret); + } + + for (size_t i = 0; i < dCameraStreams.size(); i++) { + auto streamInfo = dCameraStreams[i]; + for (auto halStream : halStreamMap_) { + if (streamInfo->streamId_ == halStream.first) { + ret = halStream.second->FinishCommitStream(); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Stream %d cannot init.", streamInfo->streamId_); + return MapToExternalRetCode(ret); + } + } + } + } + DHLOGI("DStreamOperator::Commit distributed camera streams success."); + return CamRetCode::NO_ERROR; +} + +CamRetCode DStreamOperator::GetStreamAttributes(std::vector>& attributes) +{ + attributes.clear(); + for (auto stream : halStreamMap_) { + std::shared_ptr attribute; + DCamRetCode ret = stream.second->GetDCameraStreamAttribute(attribute); + if (ret != SUCCESS) { + DHLOGE("Get distributed camera stream attribute failed."); + attributes.clear(); + return MapToExternalRetCode(ret); + } + attributes.push_back(attribute); + } + return CamRetCode::NO_ERROR; +} + +CamRetCode DStreamOperator::AttachBufferQueue(int streamId, const OHOS::sptr& producer) +{ + if (IsCapturing()) { + DHLOGE("Can not attach buffer queue when capture."); + return CamRetCode::CAMERA_BUSY; + } + + auto iter = halStreamMap_.find(streamId); + if (iter != halStreamMap_.end()) { + DCamRetCode ret = iter->second->SetDCameraBufferQueue(producer); + if (ret != SUCCESS) { + DHLOGE("Attach distributed camera buffer queue failed."); + } + return MapToExternalRetCode(ret); + } else { + DHLOGE("Not found stream id %d when attach bubfer queue.", streamId); + return CamRetCode::INVALID_ARGUMENT; + } +} + +CamRetCode DStreamOperator::DetachBufferQueue(int streamId) +{ + if (IsCapturing()) { + DHLOGE("Can not detach buffer queue when capture."); + return CamRetCode::CAMERA_BUSY; + } + + auto iter = halStreamMap_.find(streamId); + if (iter != halStreamMap_.end()) { + DCamRetCode ret = iter->second->ReleaseDCameraBufferQueue(); + if (ret != SUCCESS) { + DHLOGE("Detach distributed camera buffer queue failed."); + } + return MapToExternalRetCode(ret); + } else { + DHLOGE("Not found stream id %d when detach bubfer queue.", streamId); + return CamRetCode::INVALID_ARGUMENT; + } +} + +CamRetCode DStreamOperator::Capture(int captureId, const std::shared_ptr& captureInfo, bool isStreaming) +{ + if (captureId < 0 || halCaptureInfoMap_.find(captureId) != halCaptureInfoMap_.end()) { + DHLOGE("Input captureId %d is exist.", captureId); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!captureInfo) { + DHLOGE("Input capture info is null."); + return CamRetCode::INVALID_ARGUMENT; + } + + for (auto &id : captureInfo->streamIds_) { + if (halStreamMap_.find(id) == halStreamMap_.end()) { + DHLOGE("Invalid stream id %d", id); + return CamRetCode::INVALID_ARGUMENT; + } + auto iter = halStreamMap_.find(id); + if (!iter->second->HasBufferQueue()) { + DHLOGE("Stream %d has not bufferQueue.", iter->first); + return CamRetCode::INVALID_ARGUMENT; + } + enableShutterCbkMap_[id] = captureInfo->enableShutterCallback_; + DHLOGI("DStreamOperator::Capture info: captureId=%d, streamId=%d, isStreaming=%d", captureId, id, isStreaming); + } + + DCamRetCode ret = NegotiateSuitableCaptureInfo(captureInfo, isStreaming); + if (ret != SUCCESS) { + DHLOGE("Negotiate suitable capture info failed."); + return MapToExternalRetCode(ret); + } + + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider == nullptr) { + DHLOGE("Distributed camera provider not init."); + return CamRetCode::DEVICE_ERROR; + } + ret = provider->StartCapture(dhBase_, cachedDCaptureInfoList_); + if (ret != SUCCESS) { + DHLOGE("Start distributed camera capture failed."); + return MapToExternalRetCode(ret); + } + halCaptureInfoMap_[captureId] = captureInfo; + + if (dcStreamOperatorCallback_) { + dcStreamOperatorCallback_->OnCaptureStarted(captureId, captureInfo->streamIds_); + } + SetCapturing(true); + DHLOGI("DStreamOperator::Capture, start distributed camera capture success."); + + return CamRetCode::NO_ERROR; +} + +CamRetCode DStreamOperator::CancelCapture(int captureId) +{ + DHLOGI("DStreamOperator::CancelCapture, cancel distributed camera capture, captureId=%d.", captureId); + + std::unique_lock lock(requestLock_); + if (captureId < 0 || halCaptureInfoMap_.find(captureId) == halCaptureInfoMap_.end()) { + DHLOGE("Input captureId %d is exist.", captureId); + return CamRetCode::INVALID_ARGUMENT; + } + + SetCapturing(false); + std::shared_ptr provider = DCameraProvider::GetInstance(); + if (provider == nullptr) { + DHLOGE("Distributed camera provider not init."); + return CamRetCode::DEVICE_ERROR; + } + DCamRetCode ret = provider->StopCapture(dhBase_); + if (ret != SUCCESS) { + DHLOGE("Cancel distributed camera capture failed."); + return MapToExternalRetCode(ret); + } + + std::vector> info; + for (auto id : halCaptureInfoMap_[captureId]->streamIds_) { + auto iter = halStreamMap_.find(id); + if (iter != halStreamMap_.end()) { + iter->second->FlushDCameraBuffer(); + } + std::shared_ptr tmp = std::make_shared(); + tmp->frameCount_ = acceptedBufferNum_[std::make_pair(captureId, id)]; + tmp->streamId_ = id; + info.push_back(tmp); + acceptedBufferNum_.erase(std::make_pair(captureId, id)); + } + if (dcStreamOperatorCallback_) { + dcStreamOperatorCallback_->OnCaptureEnded(captureId, info); + } + cachedDCaptureInfoList_.clear(); + halCaptureInfoMap_.erase(captureId); + + return CamRetCode::NO_ERROR; +} + +CamRetCode DStreamOperator::ChangeToOfflineStream(const std::vector& streamIds, + OHOS::sptr& callback, OHOS::sptr& offlineOperator) +{ + (void)streamIds; + (void)callback; + offlineOperator = nullptr; + return CamRetCode::METHOD_NOT_SUPPORTED; +} + +DCamRetCode DStreamOperator::InitOutputConfigurations(const std::shared_ptr &dhBase, + const std::string &abilityInfo) +{ + dhBase_ = dhBase; + + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(abilityInfo.c_str(), abilityInfo.c_str() + abilityInfo.length(), &rootValue, &errs) || + !rootValue.isObject()) { + DHLOGE("Input ablity info is not json object."); + return INVALID_ARGUMENT; + } + + if (rootValue["CodecType"].isArray()) { + uint32_t size = rootValue["CodecType"].size(); + for (uint32_t i = 0; i < size; i++) { + std::string codeType = (rootValue["CodecType"][i]).asString(); + dcSupportedCodecType_.push_back(ConvertDCEncodeType(codeType)); + } + } + + std::set allFormats; + if (rootValue["OutputFormat"]["Preview"].isArray() && (rootValue["OutputFormat"]["Preview"].size() > 0)) { + std::vector previewFormats; + uint32_t size = rootValue["OutputFormat"]["Preview"].size(); + for (uint32_t i = 0; i < size; i++) { + previewFormats.push_back(rootValue["OutputFormat"]["Preview"][i].asInt()); + allFormats.insert((rootValue["OutputFormat"]["Preview"][i]).asInt()); + } + dcSupportedFormatMap_[DCSceneType::PREVIEW] = previewFormats; + } + + if (rootValue["OutputFormat"]["Video"].isArray() && (rootValue["OutputFormat"]["Video"].size() > 0)) { + std::vector videoFormats; + uint32_t size = rootValue["OutputFormat"]["Video"].size(); + for (uint32_t i = 0; i < size; i++) { + videoFormats.push_back(rootValue["OutputFormat"]["Video"][i].asInt()); + allFormats.insert((rootValue["OutputFormat"]["Video"][i]).asInt()); + } + dcSupportedFormatMap_[DCSceneType::VIDEO] = videoFormats; + } + + std::vector photoFormats; + if (rootValue["OutputFormat"]["Photo"].isArray() && (rootValue["OutputFormat"]["Photo"].size() > 0)) { + uint32_t size = rootValue["OutputFormat"]["Photo"].size(); + for (uint32_t i = 0; i < size; i++) { + photoFormats.push_back(rootValue["OutputFormat"]["Photo"][i].asInt()); + allFormats.insert((rootValue["OutputFormat"]["Photo"][i]).asInt()); + } + dcSupportedFormatMap_[DCSceneType::PHOTO] = photoFormats; + } + + for (const auto &format : allFormats) { + bool isPhotoFormat = count(photoFormats.begin(), photoFormats.end(), format); + std::string formatStr = std::to_string(format); + if (rootValue["Resolution"][formatStr].isArray() && rootValue["Resolution"][formatStr].size() > 0) { + std::vector resolutionVec; + uint32_t size = rootValue["Resolution"][formatStr].size(); + for (uint32_t i = 0; i < size; i++) { + std::string resoStr = rootValue["Resolution"][formatStr][i].asString(); + std::vector reso; + SplitString(resoStr, reso, STAR_SEPARATOR); + if (reso.size() != SIZE_FMT_LEN) { + continue; + } + uint32_t width = static_cast(std::atoi(reso[0].c_str())); + uint32_t height = static_cast(std::atoi(reso[1].c_str())); + if (height == 0 || width == 0 || + (isPhotoFormat && (width > MAX_SUPPORT_PHOTO_WIDTH || height > MAX_SUPPORT_PHOTO_HEIGHT)) || + (!isPhotoFormat && + (width > MAX_SUPPORT_PREVIEW_WIDTH || height > MAX_SUPPORT_PREVIEW_HEIGHT))) { + continue; + } + DCResolution resolution(width, height); + resolutionVec.push_back(resolution); + } + if (!resolutionVec.empty()) { + std::sort(resolutionVec.begin(), resolutionVec.end()); + dcSupportedResolutionMap_[format] = resolutionVec; + } + } + } + + if (dcSupportedCodecType_.empty() || dcSupportedFormatMap_.empty() || dcSupportedResolutionMap_.empty()) { + DHLOGE("Input ablity info is invalid."); + return DEVICE_NOT_INIT; + } + return SUCCESS; +} + +DCamRetCode DStreamOperator::AcquireBuffer(int streamId, std::shared_ptr &buffer) +{ + std::unique_lock lock(requestLock_); + if (!IsCapturing()) { + DHLOGE("Not in capturing state, can not acquire buffer."); + return DCamRetCode::CAMERA_OFFLINE; + } + + auto iter = halStreamMap_.find(streamId); + if (iter == halStreamMap_.end()) { + DHLOGE("streamId %d is invalid, can not acquire buffer.", streamId); + return DCamRetCode::INVALID_ARGUMENT; + } + + DCamRetCode ret = iter->second->GetDCameraBuffer(buffer); + if (ret == DCamRetCode::EXCEED_MAX_NUMBER) { + DHLOGE("Buffer list is full, cannot get new idle buffer."); + } else if (ret == DCamRetCode::INVALID_ARGUMENT) { + DHLOGE("Get distributed camera buffer failed, invalid buffer parameter."); + } + return ret; +} + +DCamRetCode DStreamOperator::ShutterBuffer(int streamId, const std::shared_ptr &buffer) +{ + DHLOGI("DStreamOperator::ShutterBuffer begin shutter buffer for streamId = %d", streamId); + + int32_t captureId = -1; + for (auto iter = halCaptureInfoMap_.begin(); iter != halCaptureInfoMap_.end(); iter++) { + std::shared_ptr captureInfo = iter->second; + std::vector streamIds = captureInfo->streamIds_; + if (std::find(streamIds.begin(), streamIds.end(), streamId) != streamIds.end()) { + captureId = iter->first; + break; + } + } + if (captureId == -1) { + DHLOGE("ShutterBuffer falied, invalid streamId = %d", streamId); + return DCamRetCode::INVALID_ARGUMENT; + } + + auto iter = halStreamMap_.find(streamId); + if (iter != halStreamMap_.end()) { + DCamRetCode ret = iter->second->ReturnDCameraBuffer(buffer); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Flush distributed camera buffer failed."); + return ret; + } + acceptedBufferNum_[std::make_pair(captureId, streamId)]++; + } + + uint64_t resultTimestamp = GetCurrentLocalTimeStamp(); + bool needReturn = false; + std::shared_ptr result = nullptr; + DCamRetCode ret = dMetadataProcessor_->UpdateResultMetadata(needReturn, result); + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Cannot handle result metadata."); + return ret; + } + if (needReturn) { + resultCallback_(resultTimestamp, result); + } + + auto anIter = enableShutterCbkMap_.find(streamId); + if (anIter->second) { + if (dcStreamOperatorCallback_ == nullptr) { + DHLOGE("DStreamOperator::ShutterBuffer failed, need shutter frame, but stream operator callback is null."); + return DCamRetCode::FAILED; + } + std::vector streamIds; + streamIds.push_back(anIter->first); + dcStreamOperatorCallback_->OnFrameShutter(captureId, streamIds, resultTimestamp); + } + return DCamRetCode::SUCCESS; +} + +DCamRetCode DStreamOperator::SetCallBack(OHOS::sptr const &callback) +{ + dcStreamOperatorCallback_ = callback; + return SUCCESS; +} + +DCamRetCode DStreamOperator::SetDeviceCallback( + std::function &errorCbk, + std::function)> &resultCbk) +{ + errorCallback_ = errorCbk; + resultCallback_ = resultCbk; + return SUCCESS; +} + +void DStreamOperator::Release() +{ + DHLOGI("DStreamOperator::Release, begin release stream operator."); + + std::unique_lock lock(requestLock_); + std::vector streamIds; + for (auto iter : halStreamMap_) { + streamIds.push_back(iter.first); + } + ReleaseStreams(streamIds); + if (latestStreamSetting_) { + latestStreamSetting_ = nullptr; + } + SetCapturing(false); + halStreamMap_.clear(); + dcStreamInfoMap_.clear(); + halCaptureInfoMap_.clear(); + enableShutterCbkMap_.clear(); + acceptedBufferNum_.clear(); + cachedDCaptureInfoList_.clear(); + dcStreamOperatorCallback_ = nullptr; +} + +bool DStreamOperator::IsCapturing() +{ + std::unique_lock lock(isCapturingLock_); + return isCapturing_; +} + +void DStreamOperator::SetCapturing(bool isCapturing) +{ + std::unique_lock lock(isCapturingLock_); + isCapturing_ = isCapturing; +} + +void DStreamOperator::ConvertStreamInfo(std::shared_ptr &srcInfo, std::shared_ptr &dstInfo) +{ + dstInfo->streamId_ = srcInfo->streamId_; + dstInfo->width_ = srcInfo->width_; + dstInfo->stride_ = srcInfo->width_; + dstInfo->height_ = srcInfo->height_; + dstInfo->dataspace_ = srcInfo->datasapce_; + dstInfo->encodeType_ = (DCEncodeType)srcInfo->encodeType_; + + if ((srcInfo->intent_ == STILL_CAPTURE) || (srcInfo->intent_ == POST_VIEW) || + (dstInfo->encodeType_ == ENCODE_TYPE_JPEG)) { + dstInfo->type_ = DCStreamType::SNAPSHOT_FRAME; + dstInfo->format_ = OHOS_CAMERA_FORMAT_JPEG; + } else { + dstInfo->type_ = DCStreamType::CONTINUOUS_FRAME; + dstInfo->format_ = + static_cast(DBufferManager::PixelFormatToDCameraFormat(static_cast(srcInfo->format_))); + } +} + +DCamRetCode DStreamOperator::NegotiateSuitableCaptureInfo(const std::shared_ptr& srcCaptureInfo, + bool isStreaming) +{ + std::vector> srcStreamInfo; + for (auto &id : srcCaptureInfo->streamIds_) { + auto iter = dcStreamInfoMap_.find(id); + if (iter != dcStreamInfoMap_.end()) { + srcStreamInfo.push_back(iter->second); + } + } + if (srcStreamInfo.empty()) { + DHLOGE("Input source stream info vector is empty."); + return INVALID_ARGUMENT; + } + + std::shared_ptr inputCaptureInfo = BuildSuitableCaptureInfo(srcCaptureInfo, srcStreamInfo); + inputCaptureInfo->type_ = isStreaming ? DCStreamType::CONTINUOUS_FRAME : DCStreamType::SNAPSHOT_FRAME; + inputCaptureInfo->isCapture_ = true; + + std::shared_ptr appendCaptureInfo = nullptr; + if (cachedDCaptureInfoList_.empty()) { + std::vector> appendStreamInfo; + auto iter = dcStreamInfoMap_.begin(); + while (iter != dcStreamInfoMap_.end()) { + if ((isStreaming && (iter->second->type_ == DCStreamType::SNAPSHOT_FRAME)) || + (!isStreaming && (iter->second->type_ == DCStreamType::CONTINUOUS_FRAME))) { + appendStreamInfo.push_back(iter->second); + } + iter++; + } + if (!appendStreamInfo.empty()) { + appendCaptureInfo = BuildSuitableCaptureInfo(srcCaptureInfo, appendStreamInfo); + appendCaptureInfo->type_ = isStreaming ? DCStreamType::SNAPSHOT_FRAME : DCStreamType::CONTINUOUS_FRAME; + appendCaptureInfo->isCapture_ = false; + } + } else { + for (auto cacheCapture : cachedDCaptureInfoList_) { + if ((isStreaming && (cacheCapture->type_ == DCStreamType::SNAPSHOT_FRAME)) || + (!isStreaming && (cacheCapture->type_ == DCStreamType::CONTINUOUS_FRAME))) { + cacheCapture->isCapture_ = false; + appendCaptureInfo = cacheCapture; + break; + } + } + } + cachedDCaptureInfoList_.clear(); + cachedDCaptureInfoList_.push_back(inputCaptureInfo); + if (appendCaptureInfo != nullptr) { + cachedDCaptureInfoList_.push_back(appendCaptureInfo); + } + return SUCCESS; +} + +std::shared_ptr DStreamOperator::BuildSuitableCaptureInfo(const shared_ptr& srcCaptureInfo, + std::vector> &srcStreamInfo) +{ + std::shared_ptr captureInfo = std::make_shared(); + + ChooseSuitableFormat(srcStreamInfo, captureInfo); + ChooseSuitableResolution(srcStreamInfo, captureInfo); + ChooseSuitableDataSpace(srcStreamInfo, captureInfo); + ChooseSuitableEncodeType(srcStreamInfo, captureInfo); + + std::shared_ptr dcSetting = std::make_shared(); + dcSetting->type_ = DCSettingsType::UPDATE_METADATA; + std::string settingStr = CameraStandard::MetadataUtils::EncodeToString(srcCaptureInfo->captureSetting_); + dcSetting->value_ = Base64Encode(reinterpret_cast(settingStr.c_str()), settingStr.length()); + + captureInfo->captureSettings_.push_back(dcSetting); + + return captureInfo; +} + +void DStreamOperator::ChooseSuitableFormat(std::vector> &streamInfo, + std::shared_ptr &captureInfo) +{ + for (auto stream : streamInfo) { + if (dcSupportedResolutionMap_.count(stream->format_) > 0) { + captureInfo->format_ = stream->format_; + return; + } + } + if ((streamInfo.at(0))->type_ == DCStreamType::CONTINUOUS_FRAME) { + if (dcSupportedFormatMap_.count(DCSceneType::PREVIEW) > 0) { + captureInfo->format_ = dcSupportedFormatMap_[DCSceneType::PREVIEW].at(0); + } else if (dcSupportedFormatMap_.count(DCSceneType::VIDEO) > 0) { + captureInfo->format_ = dcSupportedFormatMap_[DCSceneType::VIDEO].at(0); + } else { + captureInfo->format_ = OHOS_CAMERA_FORMAT_YCRCB_420_SP; + } + } else { + if (dcSupportedFormatMap_.count(DCSceneType::PHOTO) > 0) { + captureInfo->format_ = dcSupportedFormatMap_[DCSceneType::PHOTO].at(0); + } else { + captureInfo->format_ = OHOS_CAMERA_FORMAT_JPEG; + } + } +} + +void DStreamOperator::ChooseSuitableResolution(std::vector> &streamInfo, + std::shared_ptr &captureInfo) +{ + std::vector supportedResolutionList = dcSupportedResolutionMap_[captureInfo->format_]; + + DCResolution tempResolution = { 0, 0 }; + for (auto stream : streamInfo) { + for (auto resolution : supportedResolutionList) { + if ((resolution.width_ == stream->width_) && (resolution.height_ == stream->height_)) { + if (tempResolution < resolution) { + tempResolution = resolution; + break; + } + } + } + captureInfo->streamIds_.push_back(stream->streamId_); + }; + + if ((tempResolution.width_ == 0) || (tempResolution.height_ == 0)) { + captureInfo->width_ = MAX_SUPPORT_PREVIEW_WIDTH; + captureInfo->height_ = MAX_SUPPORT_PREVIEW_HEIGHT; + } else { + captureInfo->width_ = tempResolution.width_; + captureInfo->height_ = tempResolution.height_; + } +} + +void DStreamOperator::ChooseSuitableDataSpace(std::vector> &streamInfo, + std::shared_ptr &captureInfo) +{ + captureInfo->dataspace_ = (streamInfo.at(0))->dataspace_; +} + +void DStreamOperator::ChooseSuitableEncodeType(std::vector> &streamInfo, + std::shared_ptr &captureInfo) +{ + if ((streamInfo.at(0))->type_ == DCStreamType::CONTINUOUS_FRAME) { + if (count(dcSupportedCodecType_.begin(), dcSupportedCodecType_.end(), DCEncodeType::ENCODE_TYPE_H265)) { + captureInfo->encodeType_ = DCEncodeType::ENCODE_TYPE_H265; + } else if (count(dcSupportedCodecType_.begin(), dcSupportedCodecType_.end(), DCEncodeType::ENCODE_TYPE_H264)) { + captureInfo->encodeType_ = DCEncodeType::ENCODE_TYPE_H264; + } else { + captureInfo->encodeType_ = DCEncodeType::ENCODE_TYPE_NULL; + } + } else { + captureInfo->encodeType_ = DCEncodeType::ENCODE_TYPE_JPEG; + } +} + +DCEncodeType DStreamOperator::ConvertDCEncodeType(std::string &srcEncodeType) +{ + if (srcEncodeType == ENCODE_TYPE_STR_H264) { + return DCEncodeType::ENCODE_TYPE_H264; + } else if (srcEncodeType == ENCODE_TYPE_STR_H265) { + return DCEncodeType::ENCODE_TYPE_H265; + } else if (srcEncodeType == ENCODE_TYPE_STR_JPEG) { + return DCEncodeType::ENCODE_TYPE_JPEG; + } else { + return DCEncodeType::ENCODE_TYPE_NULL; + } +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/src/utils/dcamera.cpp b/camera_hdf/hdi_impl/src/utils/dcamera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1a836826fd16615a64745524d03a1f3fdf19760f --- /dev/null +++ b/camera_hdf/hdi_impl/src/utils/dcamera.cpp @@ -0,0 +1,89 @@ +/* + * 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 "dcamera.h" +#include + +namespace OHOS { +namespace DistributedHardware { +CamRetCode MapToExternalRetCode(DCamRetCode retCode) +{ + switch (retCode) { + case DCamRetCode::SUCCESS: + return CamRetCode::NO_ERROR; + case DCamRetCode::CAMERA_BUSY: + return CamRetCode::CAMERA_BUSY; + case DCamRetCode::INVALID_ARGUMENT: + return CamRetCode::INVALID_ARGUMENT; + case DCamRetCode::METHOD_NOT_SUPPORTED: + return CamRetCode::METHOD_NOT_SUPPORTED; + case DCamRetCode::CAMERA_OFFLINE: + return CamRetCode::CAMERA_CLOSED; + case DCamRetCode::EXCEED_MAX_NUMBER: + return CamRetCode::INSUFFICIENT_RESOURCES; + case DCamRetCode::FAILED: + return CamRetCode::DEVICE_ERROR; + default: + break; + } + return CamRetCode::DEVICE_ERROR; +} + +DCamRetCode MapToInternalRetCode(CamRetCode retCode) +{ + switch (retCode) { + case CamRetCode::NO_ERROR: + return DCamRetCode::SUCCESS; + case CamRetCode::CAMERA_BUSY: + return DCamRetCode::CAMERA_BUSY; + case CamRetCode::INSUFFICIENT_RESOURCES: + return DCamRetCode::EXCEED_MAX_NUMBER; + case CamRetCode::INVALID_ARGUMENT: + return DCamRetCode::INVALID_ARGUMENT; + case CamRetCode::METHOD_NOT_SUPPORTED: + return DCamRetCode::METHOD_NOT_SUPPORTED; + case CamRetCode::CAMERA_CLOSED: + return DCamRetCode::CAMERA_OFFLINE; + case CamRetCode::DEVICE_ERROR: + return DCamRetCode::FAILED; + default: + break; + } + return DCamRetCode::FAILED; +} + +uint64_t GetCurrentLocalTimeStamp() +{ + std::chrono::time_point tp = + std::chrono::time_point_cast(std::chrono::system_clock::now()); + auto tmp = std::chrono::duration_cast(tp.time_since_epoch()); + return static_cast(tmp.count()); +} + +void SplitString(const std::string &str, std::vector &tokens, const std::string &delimiters) +{ + std::string::size_type lastPos = 0; + std::string::size_type pos = str.find(delimiters); + while (std::string::npos != pos) { + tokens.push_back(str.substr(lastPos, pos - lastPos)); + lastPos = pos + delimiters.size(); + pos = str.find(delimiters, lastPos); + } + if (lastPos != str.length()) { + tokens.push_back(str.substr(lastPos)); + } +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/test/BUILD.gn b/camera_hdf/hdi_impl/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..04c5bca3e4b182bdd1c74fb96e80a3fecb8149fc --- /dev/null +++ b/camera_hdf/hdi_impl/test/BUILD.gn @@ -0,0 +1,83 @@ +# 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. + +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_executable("dcamera_hdi_sample") { + install_enable = false + sources = [ + "dcamera_hdi_sample.cpp", + "common.cpp" + ] + cflags = [ "-Wall" ] + cflags_cc = cflags + include_dirs = [ + "${distributedcamera_hdf_path}/interfaces/include", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/client/device", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/client/host", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/client/operator", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/client/provider", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/server/device", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/server/host", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/server/operator", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/server/provider", + "${distributedcamera_hdf_path}/hdi_impl/include/dcamera_device", + "${distributedcamera_hdf_path}/hdi_impl/include/dcamera_host", + "${distributedcamera_hdf_path}/hdi_impl/include/dcamera_provider", + "${distributedcamera_hdf_path}/hdi_impl/include/dstream_operator", + "${distributedcamera_hdf_path}/hdi_impl/include/utils", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include/", + "${common_path}/include/constants", + "${fwk_utils_path}/include", + "${fwk_utils_path}/include/log", + "${camera_hdf_path}/camera/interfaces/include", + "${hdf_framework_path}/include/utils", + "${hdf_uhdf_path}/include/hdi", + "${hdf_uhdf_path}/osal/include", + + #producer + "//foundation/graphic/standard/frameworks/surface/include", + "//foundation/graphic/standard/interfaces/kits/surface", + "//foundation/graphic/standard/utils/include", + "//foundation/communication/ipc/ipc/native/src/core/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/multimedia/camera_standard/frameworks/native/metadata/include", + + "${innerkits_path}/native_cpp/camera_source/include", + "${innerkits_path}/native_cpp/camera_source/include/callback", + "${fwk_common_path}/utils/include", + ] + + deps = [ + "${fwk_utils_path}:distributedhardwareutils", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/client:distributed_camera_hdf_client", + "${hdf_uhdf_path}/hdi:libhdi", + "${fwk_utils_path}:distributedhardwareutils", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + "//foundation/graphic/standard/frameworks/surface:surface", + "//drivers/peripheral/display/hal:hdi_display_gralloc", + "//foundation/multimedia/camera_standard/frameworks/native/metadata:metadata", + "${innerkits_path}/native_cpp/camera_source:distributed_camera_source_sdk", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "samgr_standard:samgr_proxy", + ] + + part_name = "distributed_camera" + subsystem_name = "distributedhardware" +} \ No newline at end of file diff --git a/camera_hdf/hdi_impl/test/common.cpp b/camera_hdf/hdi_impl/test/common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..178d893b1d7f8ca7ccc5a8152491282e87ebbba2 --- /dev/null +++ b/camera_hdf/hdi_impl/test/common.cpp @@ -0,0 +1,383 @@ +/* + * 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 "common.h" + +namespace OHOS { +namespace DistributedHardware { +uint64_t Test::GetCurrentLocalTimeStamp() +{ + std::chrono::time_point tp = + std::chrono::time_point_cast(std::chrono::system_clock::now()); + auto tmp = std::chrono::duration_cast(tp.time_since_epoch()); + return static_cast(tmp.count()); +} + +int32_t Test::SaveYUV(const char* type, const void* buffer, int32_t size) +{ + if (strncmp(type, "preview", strlen(type)) == 0) { + previewBufCnt += 1; + int cycNum = 8; + if (previewBufCnt % cycNum != 0) { + std::cout << "receive preview buffer not save" << std::endl; + return 0; + } + } + char path[PATH_MAX] = {0}; + if (strncmp(type, "preview", strlen(type)) == 0) { + system("mkdir -p /data/dcamera/preview"); + sprintf_s(path, sizeof(path) / sizeof(path[0]), "/data/dcamera/preview/%s_%lld.yuv", + type, GetCurrentLocalTimeStamp()); + } else { + system("mkdir -p /data/dcamera/capture"); + sprintf_s(path, sizeof(path) / sizeof(path[0]), "/data/dcamera/capture/%s_%lld.jpg", + type, GetCurrentLocalTimeStamp()); + } + std::cout << "save yuv to file:" << path << std::endl; + + int mode = 00766; + int imgFd = open(path, O_RDWR | O_CREAT, mode); + if (imgFd == -1) { + std::cout << "open file failed, errno = " << strerror(errno) << std::endl; + return -1; + } + + int ret = write(imgFd, buffer, size); + if (ret == -1) { + std::cout << "write file failed, error = " << strerror(errno) << std::endl; + close(imgFd); + return -1; + } + close(imgFd); + return 0; +} + +int32_t Test::SaveVideoFile(const char* type, const void* buffer, int32_t size, int32_t operationMode) +{ + if (operationMode == 0) { + char path[PATH_MAX] = {0}; + system("mkdir -p /data/dcamera/video"); + sprintf_s(path, sizeof(path) / sizeof(path[0]), "/data/dcamera/video/%s_%lld.h265", + type, GetCurrentLocalTimeStamp()); + std::cout << "save yuv to file " << std::string(path) << std::endl; + int mode = 00766; + videoFd = open(path, O_RDWR | O_CREAT, mode); + if (videoFd == -1) { + std::cout << "open file failed, errno = " << strerror(errno) << std::endl; + return -1; + } + } else if (operationMode == 1 && videoFd != -1) { + int32_t ret = write(videoFd, buffer, size); + if (ret == -1) { + std::cout << "write file failed, error = " << strerror(errno) << std::endl; + close(videoFd); + return -1; + } + } else { + if (videoFd != -1) { + close(videoFd); + } + } + return 0; +} + +void Test::Init() +{ + if (service == nullptr) { + service = ICameraHost::Get("distributed_camera_service"); + if (service == nullptr) { + std::cout << "==========[test log]ICameraHost get failed."<< std::endl; + return; + } else { + std::cout << "==========[test log]ICameraHost get success."<< std::endl; + } + } + hostCallback = new DCameraHostCallback(); + service->SetCallback(hostCallback); +} + +std::shared_ptr Test::GetCameraAbility() +{ + if (cameraDevice == nullptr) { + rc = service->GetCameraIds(cameraIds); + if (rc != Camera::NO_ERROR) { + std::cout << "==========[test log]GetCameraIds failed." << std::endl; + return ability; + } else { + std::cout << "==========[test log]GetCameraIds success." << std::endl; + } + if (cameraIds.size() == 0) { + std::cout << "==========[test log]camera device list is empty." << std::endl; + return ability; + } + GetCameraMetadata(); + } + return ability; +} + +void Test::GetCameraMetadata() +{ + rc = service->GetCameraAbility(cameraIds.front(), ability); + if (rc != Camera::NO_ERROR) { + std::cout << "==========[test log]GetCameraAbility failed, rc = " << rc << std::endl; + } + common_metadata_header_t* data = ability->get(); + camera_metadata_item_t entry; + int ret = CameraStandard::FindCameraMetadataItem(data, OHOS_CONTROL_AE_AVAILABLE_MODES, &entry); + if (ret == 0) { + std::cout << "==========[test log] get OHOS_CONTROL_AE_AVAILABLE_MODES success" << std::endl; + } +} + +void Test::Open() +{ + if (cameraDevice == nullptr) { + service->GetCameraIds(cameraIds); + if (cameraIds.size() == 0) { + std::cout << "==========[test log]camera device list empty." << std::endl; + return; + } + GetCameraMetadata(); + deviceCallback = new DCameraDeviceCallback(); + rc = service->OpenCamera(cameraIds.front(), deviceCallback, cameraDevice); + if (rc != Camera::NO_ERROR || cameraDevice == nullptr) { + std::cout << "==========[test log]OpenCamera failed, rc = " << rc << std::endl; + return; + } + std::cout << "==========[test log]OpenCamera success." << std::endl; + } +} + +void Test::Close() +{ + if (cameraDevice != nullptr) { + cameraDevice->Close(); + std::cout << "cameraDevice->Close" << std::endl; + cameraDevice = nullptr; + } + consumerMap_.clear(); + if (hostCallback != nullptr) { + delete hostCallback; + hostCallback = nullptr; + } + if (deviceCallback != nullptr) { + delete deviceCallback; + deviceCallback = nullptr; + } + if (streamOperatorCallback != nullptr) { + delete streamOperatorCallback; + streamOperatorCallback = nullptr; + } +} + +void Test::StartStream(std::vector intents) +{ + streamOperatorCallback = new DStreamOperatorCallback(); + rc = cameraDevice->GetStreamOperator(streamOperatorCallback, streamOperator); + if (rc == Camera::NO_ERROR) { + std::cout << "==========[test log]GetStreamOperator success." << std::endl; + } else { + std::cout << "==========[test log]GetStreamOperator fail, rc = " << rc << std::endl; + } + int datasapce = 8; + int tunneledMode = 5; + int bufferQueueSize = 8; + streamInfo_pre = std::make_shared(); + streamInfo_video = std::make_shared(); + streamInfo_capture = std::make_shared(); + for (auto& intent : intents) { + if (intent == 0) { + streamInfo_pre->streamId_ = streamId_preview; + streamInfo_pre->width_ = preview_width; + streamInfo_pre->height_ = preview_height; + streamInfo_pre->format_ = preview_format; + streamInfo_pre->datasapce_ = datasapce; + streamInfo_pre->intent_ = intent; + streamInfo_pre->tunneledMode_ = tunneledMode; + std::shared_ptr consumer_pre = std::make_shared(); + std::cout << "==========[test log]received a preview buffer ... 0" << std::endl; + streamInfo_pre->bufferQueue_ = consumer_pre->CreateProducer([this](void* addr, uint32_t size) { + SaveYUV("preview", addr, size); + }); + streamInfo_pre->bufferQueue_->SetQueueSize(bufferQueueSize); + consumerMap_[intent] = consumer_pre; + streamInfos.push_back(streamInfo_pre); + } else if (intent == 1) { + streamInfo_video->streamId_ = streamId_video; + streamInfo_video->width_ = video_width; + streamInfo_video->height_ = video_height; + streamInfo_video->format_ = video_format; + streamInfo_video->datasapce_ = datasapce; + streamInfo_video->intent_ = intent; + streamInfo_video->encodeType_ = OHOS::Camera::ENCODE_TYPE_H265; + streamInfo_video->tunneledMode_ = tunneledMode; + std::shared_ptr consumer_video = std::make_shared(); + std::cout << "==========[test log]received a video buffer ... 1" << std::endl; + SaveVideoFile("video", nullptr, 0, 0); + streamInfo_video->bufferQueue_ = consumer_video->CreateProducer([this](void* addr, uint32_t size) { + SaveVideoFile("video", addr, size, 1); + }); + streamInfo_video->bufferQueue_->SetQueueSize(bufferQueueSize); + consumerMap_[intent] = consumer_video; + streamInfos.push_back(streamInfo_video); + } else { + streamInfo_capture->streamId_ = streamId_capture; + streamInfo_capture->width_ = snapshot_width; + streamInfo_capture->height_ = snapshot_height; + streamInfo_capture->format_ = snapshot_format; + streamInfo_capture->datasapce_ = datasapce; + streamInfo_capture->intent_ = intent; + streamInfo_capture->encodeType_ = OHOS::Camera::ENCODE_TYPE_JPEG; + streamInfo_capture->tunneledMode_ = tunneledMode; + std::shared_ptr consumer_capture = std::make_shared(); + std::cout << "==========[test log]received a capture buffer ... 2" << std::endl; + streamInfo_capture->bufferQueue_ = consumer_capture->CreateProducer([this](void* addr, uint32_t size) { + SaveYUV("capture", addr, size); + }); + streamInfo_capture->bufferQueue_->SetQueueSize(bufferQueueSize); + consumerMap_[intent] = consumer_capture; + streamInfos.push_back(streamInfo_capture); + } + } + + rc = streamOperator->CreateStreams(streamInfos); + if (rc == Camera::NO_ERROR) { + std::cout << "==========[test log]CreateStreams success." << std::endl; + } else { + std::cout << "==========[test log]CreateStreams fail, rc = " << rc << std::endl; + } + rc = streamOperator->CommitStreams(Camera::NORMAL, ability); + if (rc == Camera::NO_ERROR) { + std::cout << "==========[test log]CommitStreams success." << std::endl; + } else { + std::cout << "==========[test log]CommitStreams fail, rc = " << rc << std::endl; + } + unsigned int sleepSeconds = 2; + sleep(sleepSeconds); + std::vector>().swap(streamInfos); +} + +void Test::StartCapture(int streamId, int captureId, bool shutterCallback, bool isStreaming) +{ + captureInfo = std::make_shared(); + captureInfo->streamIds_ = {streamId}; + captureInfo->captureSetting_ = ability; + captureInfo->enableShutterCallback_ = shutterCallback; + rc = streamOperator->Capture(captureId, captureInfo, isStreaming); + if (rc == Camera::NO_ERROR) { + std::cout << "==========[test log]check Capture: Capture success, " << captureId << std::endl; + } else { + std::cout << "==========[test log]check Capture: Capture fail, rc = " << rc << std::endl; + } + unsigned int sleepSeconds = 5; + sleep(sleepSeconds); +} + +void Test::StopStream(std::vector& captureIds, std::vector& streamIds) +{ + if (sizeof(captureIds) > 0) { + for (auto &captureId : captureIds) { + rc = streamOperator->CancelCapture(captureId); + if (rc == Camera::NO_ERROR) { + std::cout << "==========[test log]check Capture: CancelCapture success," << captureId << std::endl; + } else { + std::cout << "==========[test log]check Capture: CancelCapture fail, rc = " << rc; + std::cout << "captureId = " << captureId << std::endl; + } + } + } + int32_t operationMode = 2; + SaveVideoFile("video", nullptr, 0, operationMode); + if (sizeof(streamIds) > 0) { + rc = streamOperator->ReleaseStreams(streamIds); + if (rc == Camera::NO_ERROR) { + std::cout << "==========[test log]check Capture: ReleaseStreams success." << std::endl; + } else { + std::cout << "==========[test log]check Capture: ReleaseStreams fail, rc = " << rc << std::endl; + } + } +} + +void Test::StopOfflineStream(int captureId) +{ + rc = offlineStreamOperator->CancelCapture(captureId); + if (rc == Camera::NO_ERROR) { + std::cout << "==========[test log]check offline: CancelCapture success," << captureId << std::endl; + } else { + std::cout << "==========[test log]check offline: CancelCapture fail, rc = " << rc; + std::cout << "captureId = " << captureId << std::endl; + } + rc = offlineStreamOperator->Release(); + if (rc == Camera::NO_ERROR) { + std::cout << "==========[test log]Check offline stream: offline Release success." << std::endl; + } else { + std::cout << "==========[test log]Check offline stream: offline Release fail, rc = " << rc << std::endl; + } +} + +OHOS::sptr Test::StreamConsumer::CreateProducer(std::function callback) +{ + consumer_ = OHOS::Surface::CreateSurfaceAsConsumer(); + if (consumer_ == nullptr) { + return nullptr; + } + sptr listener = new TestBufferConsumerListener(); + consumer_->RegisterConsumerListener(listener); + auto producer = consumer_->GetProducer(); + std::cout << "create a buffer queue producer:" << producer.GetRefPtr() << std::endl; + if (producer == nullptr) { + return nullptr; + } + callback_ = callback; + consumerThread_ = new std::thread([this] { + int32_t flushFence = 0; + int64_t timestamp = 0; + OHOS::Rect damage; + while (running_ == true) { + OHOS::sptr buffer = nullptr; + consumer_->AcquireBuffer(buffer, flushFence, timestamp, damage); + if (buffer != nullptr) { + void* addr = buffer->GetVirAddr(); + uint32_t size = buffer->GetSize(); + + int32_t gotSize = 0; + int32_t isKey = 0; + int64_t timestamp; + buffer->ExtraGet("dataSize", gotSize); + buffer->ExtraGet("isKeyFrame", isKey); + buffer->ExtraGet("timeStamp", timestamp); + if (gotSize) { + std::cout << "dataSize: " << gotSize << ", isKeyFrame: " + << isKey << " timeStamp:" << timestamp << endl; + } + + callback_(addr, size); + consumer_->ReleaseBuffer(buffer, -1); + shotCount_--; + if (shotCount_ == 0) { + std::unique_lock l(l_); + cv_.notify_one(); + } + } + if (running_ == false) { + break; + } + std::this_thread::sleep_for(1ms); + } + }); + return producer; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/hdi_impl/test/common.h b/camera_hdf/hdi_impl/test/common.h new file mode 100644 index 0000000000000000000000000000000000000000..5a24763857cb4fff46c90fbb55993a4ccc9ced77 --- /dev/null +++ b/camera_hdf/hdi_impl/test/common.h @@ -0,0 +1,178 @@ +/* + * 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 DISTRIBUTED_CAMERA_TEST_COMMON_H +#define DISTRIBUTED_CAMERA_TEST_COMMON_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "camera_metadata_info.h" +#include "display_type.h" +#include "distributed_hardware_log.h" +#include "drivers/peripheral/adapter/camera/interfaces/include/types.h" +#include "foundation/distributedhardware/distributedcamera/camera_hdf/interfaces/include/types.h" +#include "icamera_device.h" +#include "icamera_host.h" +#include "idistributed_hardware_source.h" +#include "ioffline_stream_operator.h" +#include "iservice_registry.h" +#include "istream_operator.h" +#include "securec.h" +#include "surface.h" + +#include "constants.h" +#include "dcamera.h" +#include "dcamera_device_callback.h" +#include "dcamera_host.h" +#include "dcamera_host_callback.h" +#include "dcamera_host_proxy.h" +#include "dstream_operator_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class Test { +public: + void Init(); + void Open(); + void Close(); + std::shared_ptr GetCameraAbility(); + uint64_t GetCurrentLocalTimeStamp(); + int32_t SaveYUV(const char* type, const void* buffer, int32_t size); + int32_t SaveVideoFile(const char* type, const void* buffer, int32_t size, int32_t operationMode); + void StartStream(std::vector intents); + void StartCapture(int streamId, int captureId, bool shutterCallback, bool isStreaming); + void StopStream(std::vector& captureIds, std::vector& streamIds); + void StopOfflineStream(int captureId); + void GetCameraMetadata(); + + OHOS::sptr streamOperatorCallback = nullptr; + OHOS::sptr hostCallback = nullptr; + OHOS::sptr deviceCallback = nullptr; + OHOS::sptr streamOperator = nullptr; + OHOS::sptr offlineStreamOperator = nullptr; + OHOS::sptr offlineStreamOperatorCallback = nullptr; + std::shared_ptr captureInfo = nullptr; + std::vector> streamInfos; + std::shared_ptr streamInfo = nullptr; + std::shared_ptr streamInfo2 = nullptr; + std::shared_ptr streamInfo_pre = nullptr; + std::shared_ptr streamInfo_video = nullptr; + std::shared_ptr streamInfo_capture = nullptr; + std::vector cameraIds; + int streamId_preview = 1000; + int streamId_preview_double = 1001; + int streamId_capture = 1010; + int streamId_video = 1020; + int captureId_preview = 2000; + int captureId_preview_double = 2001; + int captureId_capture = 2010; + int captureId_video = 2020; + int preview_format = PIXEL_FMT_YCRCB_420_SP; + int video_format = PIXEL_FMT_YCRCB_420_SP; + int snapshot_format = PIXEL_FMT_YCRCB_420_SP; + int preview_width = 1920; + int preview_height = 1080; + int snapshot_width = 4160; + int snapshot_height = 3120; + int video_width = 1920; + int video_height = 1080; + std::vector captureIds; + std::vector streamIds; + std::vector intents; + OHOS::Camera::CamRetCode rc; + OHOS::sptr service = nullptr; + std::shared_ptr ability = nullptr; + OHOS::sptr cameraDevice = nullptr; + bool status; + int previewBufCnt = 0; + int32_t videoFd = -1; + class StreamConsumer; + std::map> consumerMap_ = {}; + + class TestBufferConsumerListener : public IBufferConsumerListener { + public: + TestBufferConsumerListener() {} + ~TestBufferConsumerListener() {} + void OnBufferAvailable() {} + }; + + class StreamConsumer { + public: + OHOS::sptr CreateProducer(std::function callback); + void TakeSnapshot() + { + shotCount_++; + } + void WaitSnapshotEnd() + { + std::cout << "ready to wait" << std::endl; + std::unique_lock l(l_); + cv_.wait(l, [this]() { return shotCount_ == 0; }); + } + ~StreamConsumer() + { + running_ = false; + if (consumerThread_ != nullptr) { + consumerThread_->join(); + delete consumerThread_; + } + } + public: + std::atomic shotCount_ = 0; + std::mutex l_; + std::condition_variable cv_; + bool running_ = true; + OHOS::sptr consumer_ = nullptr; + std::thread* consumerThread_ = nullptr; + std::function callback_ = nullptr; + }; +}; + +class DCameraMockRegisterCallback : public RegisterCallback { +public: + virtual ~DCameraMockRegisterCallback() = default; + int32_t OnRegisterResult(const std::string &devId, const std::string &dhId, int32_t status, + const std::string &data) + { + cout << "Register devId: " << devId << " dhId: " << dhId << " status:" << status << endl; + return 0; + } +}; + +class DCameraMockUnRegisterCallback : public UnregisterCallback { +public: + virtual ~DCameraMockUnRegisterCallback() = default; + int32_t OnUnregisterResult(const std::string &devId, const std::string &dhId, int32_t status, + const std::string &data) + { + cout << "UnRegister devId: " << devId << " dhId: " << dhId << " status:" << status << endl; + return 0; + } +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif diff --git a/camera_hdf/hdi_impl/test/dcamera_hdi_sample.cpp b/camera_hdf/hdi_impl/test/dcamera_hdi_sample.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c460db0907faa9102371dbb3acf5bf142a07bcf --- /dev/null +++ b/camera_hdf/hdi_impl/test/dcamera_hdi_sample.cpp @@ -0,0 +1,95 @@ +/* + * 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 +#include "common.h" +#include "dcamera_source_handler.h" + +using namespace std; +using namespace OHOS::DistributedHardware; + +const std::string TEST_DEV_ID = "11111111111111111111111111111111"; +const std::string TEST_CAM_ID = "camera_0"; +const std::string TEST_ATTR = R"({"CodecType":["avenc_mpeg4"], + "OutputFormat":{"Photo":[4],"Preview":[2,3],"Video":[2,3]}, + "Position":"BACK", + "ProtocolVer":"1.0", + "MetaData":"", + "Resolution":{ + "2":["1920*1080","1504*720","1440*1080","1280*960","1280*720","1232*768","1152*720","960*720","960*544", + "880*720","720*720","720*480","640*480","352*288","320*240"], + "3":["1920*1080","1504*720","1440*1080","1280*960","1280*720","1232*768","1152*720","960*720","960*544", + "880*720","720*720","720*480","640*480","352*288","320*240"], + "4":["3840*2160","3264*2448","3264*1840","2304*1728","2048*1536","1920*1440","1920*1080","1744*1088", + "1280*720","1232*768","1152*720","640*480","320*240"]}})"; + +int main() +{ + cout << "distributed camera hdf start" << endl; + + IDistributedHardwareSource *sourceSA = GetSourceHardwareHandler(); + EnableParam param; + param.version = "1.0"; + param.attrs = TEST_ATTR; + std::shared_ptr regCb = + std::make_shared(); + int32_t ret = sourceSA->InitSource("1.0"); + cout << "Init Source " << ret << endl; + ret = sourceSA->RegisterDistributedHardware(TEST_DEV_ID, TEST_CAM_ID, param, regCb); + unsigned int sleepSeconds = 2; + sleep(sleepSeconds); + cout << "sleep" << sleepSeconds << "second wait register end: " << ret << endl; + + std::shared_ptr test = std::make_shared(); + test->Init(); + test->Open(); + sleepSeconds = 1; + sleep(sleepSeconds); + cout << "sleep" << sleepSeconds << "second wait open camera end." << endl; + + std::cout << "==========[test log]Preview stream, 640*480, expected success." << std::endl; + // 启动流 + test->intents = {OHOS::Camera::PREVIEW}; + test->StartStream(test->intents); + sleepSeconds = 1; + sleep(sleepSeconds); + cout << "sleep" << sleepSeconds << "second wait start stream end." << endl; + + // 获取预览图 + test->StartCapture(test->streamId_preview, test->captureId_preview, false, true); + // 释放流 + test->captureIds = {test->captureId_preview}; + test->streamIds = {test->streamId_preview}; + sleepSeconds = 1; + sleep(sleepSeconds); + cout << "sleep" << sleepSeconds << "second wait start capture end." << endl; + + test->StopStream(test->captureIds, test->streamIds); + sleepSeconds = 1; + sleep(sleepSeconds); + cout << "sleep" << sleepSeconds << "second wait stop stream end." << endl; + + test->Close(); + sleepSeconds = 1; + sleep(sleepSeconds); + cout << "sleep" << sleepSeconds << "second wait close end." << endl; + + std::shared_ptr unRegCb = + std::make_shared(); + ret = sourceSA->UnregisterDistributedHardware(TEST_DEV_ID, TEST_CAM_ID, unRegCb); + cout << "distributed camera hdf end ret: " << ret << endl; + + return 0; +} \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/BUILD.gn b/camera_hdf/interfaces/hdi_ipc/client/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7353b562c7eff529eb24307be1680476e2e8dc46 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/BUILD.gn @@ -0,0 +1,81 @@ +# 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. + +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_hdf_client") { + include_dirs = [ + "../", + "../../include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include/", + "${fwk_utils_path}/include", + "${fwk_utils_path}/include/log", + "${camera_hdf_path}/camera/interfaces/include", + "${hdf_framework_path}/include/utils", + "${hdf_uhdf_path}/include/hdi", + "${hdf_uhdf_path}/osal/include", + "//drivers/peripheral/base", + + #producer + "//foundation/graphic/standard/frameworks/surface/include", + "//foundation/graphic/standard/interfaces/kits/surface", + "//foundation/graphic/standard/utils/include", + "//foundation/communication/ipc/ipc/native/src/core/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/multimedia/camera_standard/frameworks/native/metadata/include", + ] + + sources = [ + "device/dcamera_device_callback_stub.cpp", + "device/dcamera_device_callback.cpp", + "device/dcamera_device_proxy.cpp", + "host/dcamera_host_callback_stub.cpp", + "host/dcamera_host_callback.cpp", + "host/dcamera_host_proxy.cpp", + "operator/doffline_stream_operator_proxy.cpp", + "operator/dstream_operator_callback_stub.cpp", + "operator/dstream_operator_callback.cpp", + "operator/dstream_operator_proxy.cpp", + "provider/dcamera_provider_callback_stub.cpp", + "provider/dcamera_provider_callback.cpp", + "provider/dcamera_provider_proxy.cpp", + ] + + deps = [ + "//utils/native/base:utils", + "${hdf_uhdf_path}/hdi:libhdi", + "${fwk_utils_path}:distributedhardwareutils", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + "//foundation/graphic/standard/frameworks/surface:surface", + "//drivers/peripheral/display/hal:hdi_display_gralloc", + "//foundation/multimedia/camera_standard/frameworks/native/metadata:metadata", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"distributedcamerahdf\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + ] + + subsystem_name = "distributedhardware" + part_name = "distributed_camera" +} diff --git a/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback.cpp b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..935a83edb6989d9a9f95aaee8a7d875060d3b740 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback.cpp @@ -0,0 +1,31 @@ +/* + * 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 "dcamera_device_callback.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +void DCameraDeviceCallback::OnError(ErrorType type, int32_t errorMsg) +{ + DHLOGW("DCameraDeviceCallback::OnError enter."); +} + +void DCameraDeviceCallback::OnResult(uint64_t timestamp, const std::shared_ptr &result) +{ + DHLOGW("DCameraDeviceCallback::OnResult enter."); +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback.h b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..ec4081c9dc2262bed2abdc9d297659957aa78d07 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback.h @@ -0,0 +1,35 @@ +/* + * 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 DISTRIBUTED_CAMERA_DEVICE_CALLBACK_H +#define DISTRIBUTED_CAMERA_DEVICE_CALLBACK_H + +#include "dcamera_device_callback_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraDeviceCallback : public DCameraDeviceCallbackStub { +public: + DCameraDeviceCallback() = default; + virtual ~DCameraDeviceCallback() = default; + +public: + virtual void OnError(ErrorType type, int32_t errorMsg) override; + virtual void OnResult(uint64_t timestamp, const std::shared_ptr &result) override; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_DEVICE_CALLBACK_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback_stub.cpp b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e86fd0dfe2a98f78a4720e31cf52f1677260dd7 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback_stub.cpp @@ -0,0 +1,62 @@ +/* + * 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 "dcamera_device_callback_stub.h" +#include "dcamera_device_callback.h" +#include "distributed_hardware_log.h" +#include "ipc_data_utils.h" +#include "metadata_utils.h" + +#include + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraDeviceCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + switch (code) { + case CMD_CAMERA_DEVICE_CALLBACK_ON_ERROR: { + if (data.ReadInterfaceToken() != DCameraDeviceCallbackStub::GetDescriptor()) { + DHLOGI("DCameraDeviceCallbackStub::OnError token failed."); + return HDF_FAILURE; + } + + ErrorType type = static_cast(data.ReadUint32()); + int32_t errorMsg = data.ReadInt32(); + DHLOGI("DCameraDeviceCallbackStub::OnError entry."); + OnError(type, errorMsg); + break; + } + case CMD_CAMERA_DEVICE_CALLBACK_ON_RESULT: { + if (data.ReadInterfaceToken() != DCameraDeviceCallbackStub::GetDescriptor()) { + DHLOGI("DCameraDeviceCallbackStub::OnResult token failed."); + return HDF_FAILURE; + } + + uint64_t timestamp = data.ReadUint64(); + std::shared_ptr result = nullptr; + CameraStandard::MetadataUtils::DecodeCameraMetadata(data, result); + DHLOGI("DCameraDeviceCallbackStub::OnResult entry."); + OnResult(timestamp, result); + break; + } + default: { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + return 0; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback_stub.h b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..50312699e8b7d9d4eba3ff2a1b8dfb1ff1b5c783 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_callback_stub.h @@ -0,0 +1,36 @@ +/* + * 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 DISTRIBUTED_CAMERA_DEVICE_CALLBACK_CLIENT_STUB_H +#define DISTRIBUTED_CAMERA_DEVICE_CALLBACK_CLIENT_STUB_H + +#include "icamera_device_callback.h" +#include "iremote_stub.h" +#include "message_parcel.h" +#include "parcel.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraDeviceCallbackStub : public IRemoteStub { +public: + virtual ~DCameraDeviceCallbackStub() = default; + + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) override; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_DEVICE_CALLBACK_CLIENT_STUB_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..badfd01fc323670c6b0a4f1e943ef3d534a63852 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_proxy.cpp @@ -0,0 +1,205 @@ +/* + * 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 "dcamera_device_proxy.h" +#include +#include +#include "distributed_hardware_log.h" +#include "ipc_data_utils.h" +#include "istream_operator.h" +#include "istream_operator_callback.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +CamRetCode DCameraDeviceProxy::GetStreamOperator( + const OHOS::sptr &callback, + OHOS::sptr &streamOperator) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceProxy::GetDescriptor())) { + DHLOGE("Write stream operator descriptor failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + bool nullFlag = (callback != nullptr); + if (!data.WriteBool(nullFlag)) { + DHLOGE("Write stream operator callback flag failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (nullFlag && !data.WriteRemoteObject(callback->AsObject())) { + DHLOGE("Write stream operator object failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_REMOTE_GET_STREAM_OPERATOR, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + + CamRetCode retCode = static_cast(reply.ReadInt32()); + bool flag = reply.ReadBool(); + if (flag) { + sptr remoteStreamOperator = reply.ReadRemoteObject(); + streamOperator = OHOS::iface_cast(remoteStreamOperator); + } + return retCode; +} + +CamRetCode DCameraDeviceProxy::UpdateSettings(const std::shared_ptr &settings) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceProxy::GetDescriptor())) { + DHLOGE("Write stream operator descriptor failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + bool bRet = CameraStandard::MetadataUtils::EncodeCameraMetadata(settings, data); + if (!bRet) { + DHLOGE("Write update settings metadata failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_UPDATE_SETTINGS, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DCameraDeviceProxy::SetResultMode(const ResultCallbackMode &mode) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceProxy::GetDescriptor())) { + DHLOGE("Write stream operator descriptor failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(static_cast(mode))) { + DHLOGE("Write result callback mode failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_REMOTE_SET_RESULT_MODE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DCameraDeviceProxy::GetEnabledResults(std::vector &results) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceProxy::GetDescriptor())) { + DHLOGE("Write stream operator descriptor failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_REMOTE_GET_ENABLED_RESULTS, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + + CamRetCode retCode = static_cast(reply.ReadInt32()); + if (!reply.ReadInt32Vector(&results)) { + DHLOGE("Read results failed."); + return CamRetCode::INVALID_ARGUMENT; + } + return retCode; +} + +CamRetCode DCameraDeviceProxy::EnableResult(const std::vector &results) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceProxy::GetDescriptor())) { + DHLOGE("Write stream operator descriptor failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32Vector(results)) { + DHLOGE("Write results failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_REMOTE_ENABLE_RESULT, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DCameraDeviceProxy::DisableResult(const std::vector &results) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceProxy::GetDescriptor())) { + DHLOGE("Write stream operator descriptor failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32Vector(results)) { + DHLOGE("Write results failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_REMOTE_DISABLE_RESULT, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +void DCameraDeviceProxy::Close() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceProxy::GetDescriptor())) { + DHLOGE("Write stream operator descriptor failed."); + return; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_REMOTE_CLOSE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + } +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_proxy.h b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..985f2c036d29a5180cef3fb7440cdb7e5da9c9ae --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/device/dcamera_device_proxy.h @@ -0,0 +1,53 @@ +/* + * 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 DISTRIBUTED_CAMERA_DEVICE_CLIENT_PROXY_H +#define DISTRIBUTED_CAMERA_DEVICE_CLIENT_PROXY_H + +#include "iremote_proxy.h" +#include "icamera_device.h" +#include "istream_operator_callback.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraDeviceProxy : public IRemoteProxy { +public: + explicit DCameraDeviceProxy(const sptr &impl) : IRemoteProxy(impl) {} + virtual ~DCameraDeviceProxy() = default; + + virtual CamRetCode GetStreamOperator(const OHOS::sptr &callback, + OHOS::sptr &streamOperator) override; + virtual CamRetCode UpdateSettings(const std::shared_ptr &settings) override; + virtual CamRetCode SetResultMode(const ResultCallbackMode &mode) override; + virtual CamRetCode GetEnabledResults(std::vector &results) override; + virtual CamRetCode EnableResult(const std::vector &results) override; + virtual CamRetCode DisableResult(const std::vector &results) override; + virtual void Close() override; + +private: + static constexpr int CMD_CAMERA_DEVICE_REMOTE_GET_STREAM_OPERATOR = 0; + static constexpr int CMD_CAMERA_DEVICE_REMOTE_UPDATE_SERTTINGS = 1; + static constexpr int CMD_CAMERA_DEVICE_REMOTE_SET_RESULT_MODE = 2; + static constexpr int CMD_CAMERA_DEVICE_REMOTE_GET_ENABLED_RESULTS = 3; + static constexpr int CMD_CAMERA_DEVICE_REMOTE_ENABLE_RESULT = 4; + static constexpr int CMD_CAMERA_DEVICE_REMOTE_DISABLE_RESULT = 5; + static constexpr int CMD_CAMERA_DEVICE_REMOTE_CLOSE = 6; + + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_DEVICE_CLIENT_PROXY_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback.cpp b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b85c50c6cf2c3766f6ae4054ac05ea59e7d0713d --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback.cpp @@ -0,0 +1,36 @@ +/* + * 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 "dcamera_host_callback.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +void DCameraHostCallback::OnCameraStatus(const std::string &cameraId, CameraStatus status) +{ + DHLOGW("DCameraHostCallback::OnCameraStatus enter."); +} + +void DCameraHostCallback::OnFlashlightStatus(const std::string &cameraId, FlashlightStatus status) +{ + DHLOGW("DCameraHostCallback::OnFlashlightStatus enter."); +} + +void DCameraHostCallback::OnCameraEvent(const std::string &cameraId, CameraEvent event) +{ + DHLOGW("DCameraHostCallback::OnCameraEvent enter."); +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback.h b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..5bf37cf606a0132fb629daa52b3369be64c8eec2 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback.h @@ -0,0 +1,36 @@ +/* + * 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 DISTRIBUTED_CAMERA_HOST_CALLBACK_H +#define DISTRIBUTED_CAMERA_HOST_CALLBACK_H + +#include "dcamera_host_callback_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraHostCallback : public DCameraHostCallbackStub { +public: + DCameraHostCallback() = default; + virtual ~DCameraHostCallback() = default; + +public: + virtual void OnCameraStatus(const std::string &cameraId, CameraStatus status) override; + virtual void OnFlashlightStatus(const std::string &cameraId, FlashlightStatus status) override; + virtual void OnCameraEvent(const std::string &cameraId, CameraEvent event) override; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_HOST_CALLBACK_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback_stub.cpp b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36e27e2cec78c908ef61d0b5f87b2533a53db7e1 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback_stub.cpp @@ -0,0 +1,71 @@ +/* + * 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 "dcamera_host_callback_stub.h" +#include "dcamera_host_callback.h" +#include "distributed_hardware_log.h" + +#include + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraHostCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + switch (code) { + case CMD_CAMERA_HOST_CALLBACK_ON_STATUS: { + DHLOGI("DCameraHostCallbackStub::OnCameraStatus entry."); + if (data.ReadInterfaceToken() != DCameraHostCallbackStub::GetDescriptor()) { + DHLOGI("DCameraDeviceCallbackStub::OnCameraStatus token failed."); + return HDF_FAILURE; + } + + std::string cameraId = data.ReadString(); + CameraStatus status = static_cast(data.ReadInt32()); + OnCameraStatus(cameraId, status); + break; + } + case CMD_CAMERA_HOST_CALLBACK_ON_FLASHLIGHT_STATUS: { + DHLOGI("DCameraHostCallbackStub::OnFlashlightStatus entry."); + if (data.ReadInterfaceToken() != DCameraHostCallbackStub::GetDescriptor()) { + DHLOGI("DCameraDeviceCallbackStub::OnFlashlightStatus token failed."); + return HDF_FAILURE; + } + + std::string cameraId = data.ReadString(); + FlashlightStatus status = static_cast(data.ReadInt32()); + OnFlashlightStatus(cameraId, status); + break; + } + case CMD_CAMERA_HOST_CALLBACK_ON_CAMERA_EVENT: { + DHLOGI("DCameraHostCallbackStub::OnCameraEvent entry."); + if (data.ReadInterfaceToken() != DCameraHostCallbackStub::GetDescriptor()) { + DHLOGI("DCameraDeviceCallbackStub::OnCameraEvent token failed."); + return HDF_FAILURE; + } + + std::string cameraId = data.ReadString(); + CameraEvent event = static_cast(data.ReadInt32()); + OnCameraEvent(cameraId, event); + break; + } + default: { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + return 0; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback_stub.h b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..232a3f31617a82a3e43c0135be89159312ebcaef --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_callback_stub.h @@ -0,0 +1,36 @@ +/* + * 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 DISTRIBUTED_CAMERA_HOST_CALLBACK_CLIENT_STUB_H +#define DISTRIBUTED_CAMERA_HOST_CALLBACK_CLIENT_STUB_H + +#include "icamera_host_callback.h" +#include "iremote_stub.h" +#include "message_parcel.h" +#include "parcel.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraHostCallbackStub : public IRemoteStub { +public: + virtual ~DCameraHostCallbackStub() = default; + + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) override; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_HOST_CALLBACK_CLIENT_STUB_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9565f39e53d0eda59ca95e1daf79df10b6de8dbc --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_proxy.cpp @@ -0,0 +1,206 @@ +/* + * 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 "dcamera_host_proxy.h" +#include +#include +#include "distributed_hardware_log.h" +#include "icamera_device.h" +#include "icamera_device_callback.h" +#include "icamera_host_callback.h" +#include "ipc_data_utils.h" +#include "metadata_utils.h" + +OHOS::sptr OHOS::Camera::ICameraHost::Get(const char *serviceName) +{ + using namespace OHOS::HDI::ServiceManager::V1_0; + OHOS::sptr serviceMgr = IServiceManager::Get(); + if (serviceMgr == nullptr) { + HDF_LOGE("%{public}s: IServiceManager failed!", __func__); + return nullptr; + } + + OHOS::sptr remote = serviceMgr->GetService(serviceName); + if (remote == nullptr) { + HDF_LOGE("%{public}s: get %{public}s failed!", __func__, serviceName); + return nullptr; + } + + return iface_cast(remote); +} + +namespace OHOS { +namespace DistributedHardware { +CamRetCode DCameraHostProxy::SetCallback(const OHOS::sptr &callback) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraHostProxy::GetDescriptor())) { + DHLOGE("Write remote token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + bool callbackFlag = (callback != nullptr); + if (!data.WriteBool(callbackFlag)) { + DHLOGE("Set callback flag failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (callbackFlag && !data.WriteRemoteObject(callback->AsObject())) { + DHLOGE("Write remote callback object failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_REMOTE_SET_CALLBACK, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DCameraHostProxy::GetCameraIds(std::vector &cameraIds) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraHostProxy::GetDescriptor())) { + DHLOGE("Write remote token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_REMOTE_GET_CAMERAID, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + + CamRetCode retCode = static_cast(reply.ReadInt32()); + if (retCode == CamRetCode::NO_ERROR && !reply.ReadStringVector(&cameraIds)) { + DHLOGE("Read camera ids failed."); + return CamRetCode::INVALID_ARGUMENT; + } + return retCode; +} + +CamRetCode DCameraHostProxy::GetCameraAbility(const std::string &cameraId, + std::shared_ptr &ability) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraHostProxy::GetDescriptor())) { + DHLOGE("Write remote token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(cameraId)) { + DHLOGE("Write cameraId failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_REMOTE_GET_CAMERA_ABILITY, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + + CamRetCode retCode = static_cast(reply.ReadInt32()); + if (retCode == CamRetCode::NO_ERROR) { + CameraStandard::MetadataUtils::DecodeCameraMetadata(reply, ability); + } + return retCode; +} + +CamRetCode DCameraHostProxy::OpenCamera(const std::string &cameraId, + const OHOS::sptr &callback, OHOS::sptr &pDevice) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraHostProxy::GetDescriptor())) { + DHLOGE("Write remote token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(cameraId)) { + DHLOGE("Write cameraId failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + bool callbackFlag = (callback != nullptr); + if (!data.WriteBool(callbackFlag)) { + DHLOGE("Write camera callback flag failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (callbackFlag && !data.WriteRemoteObject(callback->AsObject())) { + DHLOGE("Write camera device callback failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_REMOTE_OPEN_CAMERA, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + + CamRetCode retCode = static_cast(reply.ReadInt32()); + bool flag = reply.ReadBool(); + if (flag) { + sptr remoteCameraDevice = reply.ReadRemoteObject(); + if (remoteCameraDevice == nullptr) { + DHLOGE("Read remote camera device is null."); + } + pDevice = OHOS::iface_cast(remoteCameraDevice); + } + return retCode; +} + +CamRetCode DCameraHostProxy::SetFlashlight(const std::string &cameraId, bool &isEnable) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraHostProxy::GetDescriptor())) { + DHLOGE("Write remote token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(cameraId)) { + DHLOGE("Write cameraId failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteBool(isEnable)) { + DHLOGE("Write isEnable failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_REMOTE_SET_FLASH_LIGHT, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_proxy.h b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..e851ae0fc6f85733ff19a67eb356916b41cc9b09 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/host/dcamera_host_proxy.h @@ -0,0 +1,50 @@ +/* + * 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 DISTRIBUTED_CAMERA_HOST_CLIENT_PROXY_H +#define DISTRIBUTED_CAMERA_HOST_CLIENT_PROXY_H + +#include "iremote_proxy.h" +#include "icamera_host.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraHostProxy : public IRemoteProxy { +public: + explicit DCameraHostProxy(const sptr &impl) : IRemoteProxy(impl) {} + virtual ~DCameraHostProxy() {} + + virtual CamRetCode SetCallback(const OHOS::sptr &callback) override; + virtual CamRetCode GetCameraIds(std::vector &cameraIds) override; + virtual CamRetCode GetCameraAbility(const std::string &cameraId, + std::shared_ptr &ability) override; + virtual CamRetCode OpenCamera(const std::string &cameraId, + const OHOS::sptr &callback, + OHOS::sptr &pDevice) override; + virtual CamRetCode SetFlashlight(const std::string &cameraId, bool &isEnable) override; + +private: + static constexpr int CMD_CAMERA_HOST_REMOTE_SET_CALLBACK = 0; + static constexpr int CMD_CAMERA_HOST_REMOTE_GET_CAMERAID = 1; + static constexpr int CMD_CAMERA_HOST_REMOTE_GET_CAMERA_ABILITY = 2; + static constexpr int CMD_CAMERA_HOST_REMOTE_OPEN_CAMERA = 3; + static constexpr int CMD_CAMERA_HOST_REMOTE_SET_FLASH_LIGHT = 4; + + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_HOST_CLIENT_PROXY_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/operator/doffline_stream_operator_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/client/operator/doffline_stream_operator_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5500c5d0ebe4a31068cda895f3de29a23f8247d7 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/operator/doffline_stream_operator_proxy.cpp @@ -0,0 +1,91 @@ +/* + * 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 "doffline_stream_operator_proxy.h" +#include +#include +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +CamRetCode DOfflineStreamOperatorProxy::CancelCapture(int captureId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DOfflineStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(static_cast(captureId))) { + DHLOGE("Write captureId object failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_OFFLINE_STREAM_OPERATOR_CANCEL_CAPTURE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DOfflineStreamOperatorProxy::ReleaseStreams(const std::vector &streamIds) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DOfflineStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + std::vector pxyStreamIds = streamIds; + if (!data.WriteInt32Vector(pxyStreamIds)) { + DHLOGE("Write streamIds object failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_OFFLINE_STREAM_OPERATOR_RELEASE_STREAMS, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DOfflineStreamOperatorProxy::Release() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DOfflineStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_OFFLINE_STREAM_OPERATOR_RELEASE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/operator/doffline_stream_operator_proxy.h b/camera_hdf/interfaces/hdi_ipc/client/operator/doffline_stream_operator_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..6984eb8d6d199ca996c257a6c281cf03168d2239 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/operator/doffline_stream_operator_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 DISTRIBUTED_OFFLINE_STREAM_OPERATOR_CLIENT_PROXY_H +#define DISTRIBUTED_OFFLINE_STREAM_OPERATOR_CLIENT_PROXY_H + +#include "iremote_proxy.h" +#include "ioffline_stream_operator.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DOfflineStreamOperatorProxy : public IRemoteProxy { +public: + explicit DOfflineStreamOperatorProxy(const sptr& impl) + : IRemoteProxy(impl) {} + virtual ~DOfflineStreamOperatorProxy() {} + + virtual CamRetCode CancelCapture(int captureId) override; + virtual CamRetCode ReleaseStreams(const std::vector& streamIds) override; + virtual CamRetCode Release() override; + +private: + static constexpr int CMD_OFFLINE_STREAM_OPERATOR_CANCEL_CAPTURE = 0; + static constexpr int CMD_OFFLINE_STREAM_OPERATOR_RELEASE_STREAMS = 1; + static constexpr int CMD_OFFLINE_STREAM_OPERATOR_RELEASE = 2; + + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_OFFLINE_STREAM_OPERATOR_CLIENT_PROXY_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback.cpp b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5bc0d758f13e122b36b0aa47c6b86dc9189d82ad --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback.cpp @@ -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. + */ + +#include "dstream_operator_callback.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +void DStreamOperatorCallback::OnCaptureStarted(int32_t captureId, const std::vector &streamId) +{ + DHLOGW("DStreamOperatorCallback::OnCaptureStarted enter."); +} + +void DStreamOperatorCallback::OnCaptureEnded(int32_t captureId, + const std::vector> &info) +{ + DHLOGW("DStreamOperatorCallback::OnCaptureEnded enter."); +} + +void DStreamOperatorCallback::OnCaptureError(int32_t captureId, + const std::vector> &info) +{ + DHLOGW("DStreamOperatorCallback::OnCaptureError enter."); +} + +void DStreamOperatorCallback::OnFrameShutter(int32_t captureId, const std::vector &streamId, + uint64_t timestamp) +{ + DHLOGW("DStreamOperatorCallback::OnFrameShutter enter."); +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback.h b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..7c4145a2eb9f119d7cfcef5d75db852f30ac4f33 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback.h @@ -0,0 +1,40 @@ +/* + * 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 DISTRIBUTED_STREAM_OPERATOR_CALLBACK_H +#define DISTRIBUTED_STREAM_OPERATOR_CALLBACK_H + +#include "dstream_operator_callback_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DStreamOperatorCallback : public DStreamOperatorCallbackStub { +public: + DStreamOperatorCallback() = default; + virtual ~DStreamOperatorCallback() = default; + +public: + virtual void OnCaptureStarted(int32_t captureId, const std::vector &streamId) override; + virtual void OnCaptureEnded(int32_t captureId, + const std::vector> &info) override; + virtual void OnCaptureError(int32_t captureId, + const std::vector> &info) override; + virtual void OnFrameShutter(int32_t captureId, + const std::vector &streamId, uint64_t timestamp) override; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_STREAM_OPERATOR_CALLBACK_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback_stub.cpp b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c22c28b9260a903b321ab757d29e78c29ac4933 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback_stub.cpp @@ -0,0 +1,148 @@ +/* + * 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 "dstream_operator_callback_stub.h" +#include +#include +#include "distributed_hardware_log.h" +#include "dstream_operator_callback.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DStreamOperatorCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + int32_t ret = HDF_SUCCESS; + switch (code) { + case CMD_STREAM_OPERATOR_CALLBACK_ON_CAPTURE_STARTED: { + ret = OnCaptureStartedStub(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_CALLBACK_ON_CAPTURE_ENDED: { + ret = OnCaptureEndedStub(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_CALLBACK_ON_CAPTURE_ERROR: { + ret = OnCaptureErrorStub(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_CALLBACK_ON_FRAME_SHUTTER: { + ret = OnFrameShutterStub(data, reply, option); + break; + } + default: { + ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + return ret; +} + +int32_t DStreamOperatorCallbackStub::OnCaptureStartedStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorCallbackStub::OnCaptureStartedStub entry."); + if (data.ReadInterfaceToken() != DStreamOperatorCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + int32_t captureId = data.ReadInt32(); + std::vector streamIds; + if (!data.ReadInt32Vector(&streamIds)) { + DHLOGE("OnCaptureStarted read streamIds failed."); + return HDF_FAILURE; + } + OnCaptureStarted(captureId, streamIds); + return HDF_SUCCESS; +} + +int32_t DStreamOperatorCallbackStub::OnCaptureEndedStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorCallbackStub::OnCaptureEndedStub entry."); + if (data.ReadInterfaceToken() != DStreamOperatorCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + int32_t captureId = data.ReadInt32(); + int32_t count = data.ReadInt32(); + std::vector> info; + for (int32_t i = 0; i < count; i++) { + const CaptureEndedInfo *pInfo = reinterpret_cast( + data.ReadBuffer(sizeof(CaptureEndedInfo))); + if (pInfo == nullptr) { + DHLOGE("Read ended info failed."); + return HDF_FAILURE; + } + std::shared_ptr captureEndedInfo = std::make_shared(); + captureEndedInfo->streamId_ = pInfo->streamId_; + captureEndedInfo->frameCount_ = pInfo->frameCount_; + info.push_back(captureEndedInfo); + } + OnCaptureEnded(captureId, info); + return HDF_SUCCESS; +} + +int32_t DStreamOperatorCallbackStub::OnCaptureErrorStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorCallbackStub::OnCaptureErrorStub entry."); + if (data.ReadInterfaceToken() != DStreamOperatorCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + int32_t captureId = data.ReadInt32(); + int32_t count = data.ReadInt32(); + std::vector> info; + for (int32_t i = 0; i < count; i++) { + const CaptureErrorInfo *pInfo = reinterpret_cast( + data.ReadBuffer(sizeof(CaptureErrorInfo))); + if (pInfo == nullptr) { + DHLOGE("Read error info failed."); + return HDF_FAILURE; + } + std::shared_ptr captureErrorInfo = std::make_shared(); + captureErrorInfo->streamId_ = pInfo->streamId_; + captureErrorInfo->error_ = pInfo->error_; + info.push_back(captureErrorInfo); + } + + OnCaptureError(captureId, info); + return HDF_SUCCESS; +} + +int32_t DStreamOperatorCallbackStub::OnFrameShutterStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorCallbackStub::OnFrameShutterStub entry."); + if (data.ReadInterfaceToken() != DStreamOperatorCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + int32_t captureId = data.ReadInt32(); + std::vector streamIds; + if (!data.ReadInt32Vector(&streamIds)) { + DHLOGE("Read streamIds failed."); + return HDF_FAILURE; + } + uint64_t timestamp = data.ReadUint64(); + OnFrameShutter(captureId, streamIds, timestamp); + return HDF_SUCCESS; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback_stub.h b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..095132bef6330b20abb5e833d9b9778480dc7802 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_callback_stub.h @@ -0,0 +1,41 @@ +/* + * 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 DISTRIBUTED_STREAM_OPERATOR_CALLBACK_CLIENT_STUB_H +#define DISTRIBUTED_STREAM_OPERATOR_CALLBACK_CLIENT_STUB_H + +#include "iremote_stub.h" +#include "istream_operator_callback.h" +#include "message_parcel.h" +#include "parcel.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DStreamOperatorCallbackStub : public IRemoteStub { +public: + virtual ~DStreamOperatorCallbackStub() = default; + +private: + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) override; + int32_t OnCaptureStartedStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t OnCaptureEndedStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t OnCaptureErrorStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t OnFrameShutterStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_STREAM_OPERATOR_CALLBACK_CLIENT_STUB_H diff --git a/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5937f82ac881db082cbdecea3663344b18b2438 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_proxy.cpp @@ -0,0 +1,383 @@ +/* + * 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 "dstream_operator_proxy.h" +#include +#include +#include "distributed_hardware_log.h" +#include "ioffline_stream_operator.h" +#include "ipc_data_utils.h" +#include "istream_operator_callback.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +CamRetCode DStreamOperatorProxy::IsStreamsSupported(OperationMode mode, + const std::shared_ptr &modeSetting, + const std::vector> &info, + StreamSupportType &type) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(mode)) { + DHLOGE("Write operation mode failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + bool nullFlag = (modeSetting != nullptr); + if (!data.WriteBool(nullFlag)) { + DHLOGE("Write mode null flag failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (nullFlag && !CameraStandard::MetadataUtils::EncodeCameraMetadata(modeSetting, data)) { + DHLOGE("Write metadata failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + nullFlag = info.size(); + if (!data.WriteBool(nullFlag)) { + DHLOGE("Write streaminfo null flag failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + size_t count = info.size(); + if (!data.WriteInt32(static_cast(count))) { + HDF_LOGE("%s: write info count failed", __func__); + return CamRetCode::INVALID_ARGUMENT; + } + + for (size_t i = 0; i < count; i++) { + std::shared_ptr streamInfo = info.at(i); + bool ret = IpcDataUtils::EncodeStreamInfo(streamInfo, data); + if (!ret) { + HDF_LOGE("%s: write streamInfo failed. index = %zu", __func__, i); + return CamRetCode::INVALID_ARGUMENT; + } + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_IS_STREAMS_SUPPORTED, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d", ret); + return CamRetCode::INVALID_ARGUMENT; + } + + CamRetCode retCode = static_cast(reply.ReadInt32()); + type = static_cast(reply.ReadInt32()); + return retCode; +} + +CamRetCode DStreamOperatorProxy::CreateStreams(const std::vector> &streamInfos) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + size_t count = streamInfos.size(); + if (!data.WriteInt32(static_cast(count))) { + DHLOGE("Write streamInfos count failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + for (size_t i = 0; i < count; i++) { + std::shared_ptr streamInfo = streamInfos.at(i); + bool bRet = IpcDataUtils::EncodeStreamInfo(streamInfo, data); + if (!bRet) { + DHLOGE("Write streamInfo failed. index = %d", i); + return CamRetCode::INVALID_ARGUMENT; + } + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_CREATE_STREAMS, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DStreamOperatorProxy::ReleaseStreams(const std::vector &streamIds) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + std::vector pxyStreamIds = streamIds; + if (!data.WriteInt32Vector(pxyStreamIds)) { + DHLOGE("Write streamIds failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_RELEASE_STREAMS, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DStreamOperatorProxy::CommitStreams(OperationMode mode, + const std::shared_ptr &modeSetting) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(mode)) { + DHLOGE("Write operation mode failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + bool bRet = CameraStandard::MetadataUtils::EncodeCameraMetadata(modeSetting, data); + if (!bRet) { + DHLOGE("Write metadata failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_COMMIT_STREAMS, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DStreamOperatorProxy::GetStreamAttributes(std::vector> &attributes) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_GET_STREAM_ATTRIBUTES, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t retCode = reply.ReadInt32(); + int32_t count = reply.ReadInt32(); + for (int i = 0; i < count; i++) { + const uint8_t *buffer = data.ReadBuffer(sizeof(StreamAttribute)); + std::shared_ptr attribute = std::shared_ptr( + reinterpret_cast( + const_cast(buffer))); + attributes.push_back(attribute); + } + return static_cast(retCode); +} + +CamRetCode DStreamOperatorProxy::AttachBufferQueue(int streamId, const OHOS::sptr &producer) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (producer == nullptr) { + DHLOGE("Input producer is NULL."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(static_cast(streamId))) { + DHLOGE("Write streamId failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteRemoteObject(producer->AsObject())) { + DHLOGE("Write buffer producer failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_ATTACH_BUFFER_QUEUE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DStreamOperatorProxy::DetachBufferQueue(int streamId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(static_cast(streamId))) { + DHLOGE("Write streamId failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_DETACH_BUFFER_QUEUE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DStreamOperatorProxy::Capture(int captureId, + const std::shared_ptr &info, bool isStreaming) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (info == nullptr) { + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(static_cast(captureId))) { + DHLOGE("Write captureId failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + std::vector pxyStreamIds = info->streamIds_; + if (!data.WriteInt32Vector(pxyStreamIds)) { + DHLOGE("Write streamIds failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + bool bRet = CameraStandard::MetadataUtils::EncodeCameraMetadata(info->captureSetting_, data); + if (!bRet) { + DHLOGE("Write metadata failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteBool(info->enableShutterCallback_)) { + DHLOGE("Write enableShutterCallback_ failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteBool(isStreaming)) { + DHLOGE("Write isStreaming failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_CAPTURE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DStreamOperatorProxy::CancelCapture(int captureId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(static_cast(captureId))) { + DHLOGE("Write captureId failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest( + CMD_STREAM_OPERATOR_CANCEL_CAPTURE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +CamRetCode DStreamOperatorProxy::ChangeToOfflineStream( + const std::vector &streamIds, + OHOS::sptr &callback, + OHOS::sptr &offlineOperator) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (callback == nullptr) { + return CamRetCode::INVALID_ARGUMENT; + } + + std::vector pxyStreamIds = streamIds; + if (!data.WriteInt32Vector(pxyStreamIds)) { + DHLOGE("Write streamIds failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteRemoteObject(callback->AsObject())) { + DHLOGE("Write offline stream operator callback failed."); + return CamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_CHANGE_TO_OFFLINE_STREAM, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code = %d.", ret); + return CamRetCode::INVALID_ARGUMENT; + } + + CamRetCode retCode = static_cast(reply.ReadInt32()); + sptr remoteObj = reply.ReadRemoteObject(); + offlineOperator = OHOS::iface_cast(remoteObj); + return retCode; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_proxy.h b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..340b6cac13807e126985a4d6d565b6dfa96bbf3a --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/operator/dstream_operator_proxy.h @@ -0,0 +1,65 @@ +/* + * 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 DISTRIBUTED_STREAM_OPERATOR_CLIENT_PROXY_H +#define DISTRIBUTED_STREAM_OPERATOR_CLIENT_PROXY_H + +#include "iremote_proxy.h" +#include "istream_operator.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DStreamOperatorProxy : public IRemoteProxy { +public: + explicit DStreamOperatorProxy(const sptr &impl) : IRemoteProxy(impl) {} + virtual ~DStreamOperatorProxy() = default; + + virtual CamRetCode IsStreamsSupported(OperationMode mode, + const std::shared_ptr &modeSetting, + const std::vector> &info, + StreamSupportType &type) override; + virtual CamRetCode CreateStreams(const std::vector> &streamInfos) override; + virtual CamRetCode ReleaseStreams(const std::vector &streamIds) override; + virtual CamRetCode CommitStreams(OperationMode mode, + const std::shared_ptr &modeSetting) override; + virtual CamRetCode GetStreamAttributes(std::vector> &attributes) override; + virtual CamRetCode AttachBufferQueue(int streamId, + const OHOS::sptr &producer) override; + virtual CamRetCode DetachBufferQueue(int streamId) override; + virtual CamRetCode Capture(int captureId, + const std::shared_ptr &info, bool isStreaming) override; + virtual CamRetCode CancelCapture(int captureId) override; + virtual CamRetCode ChangeToOfflineStream(const std::vector &streamIds, + OHOS::sptr &callback, + OHOS::sptr &offlineOperator) override; + +private: + static constexpr int CMD_STREAM_OPERATOR_IS_STREAMS_SUPPORTED = 0; + static constexpr int CMD_STREAM_OPERATOR_CREATE_STREAMS = 1; + static constexpr int CMD_STREAM_OPERATOR_RELEASE_STREAMS = 2; + static constexpr int CMD_STREAM_OPERATOR_COMMIT_STREAMS = 3; + static constexpr int CMD_STREAM_OPERATOR_GET_STREAM_ATTRIBUTES = 4; + static constexpr int CMD_STREAM_OPERATOR_ATTACH_BUFFER_QUEUE = 5; + static constexpr int CMD_STREAM_OPERATOR_DETACH_BUFFER_QUEUE = 6; + static constexpr int CMD_STREAM_OPERATOR_CAPTURE = 7; + static constexpr int CMD_STREAM_OPERATOR_CANCEL_CAPTURE = 8; + static constexpr int CMD_STREAM_OPERATOR_CHANGE_TO_OFFLINE_STREAM = 9; + + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_STREAM_OPERATOR_CLIENT_PROXY_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback.cpp b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d7683da35f45004b896174f6194bb192915c36f --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback.cpp @@ -0,0 +1,67 @@ +/* + * 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 "dcamera_provider_callback.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCamRetCode DCameraProviderCallback::OpenSession(const std::shared_ptr &dhBase) +{ + DHLOGW("DCameraProviderCallback::OpenSession enter."); + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraProviderCallback::CloseSession(const std::shared_ptr &dhBase) +{ + DHLOGW("DCameraProviderCallback::CloseSession enter."); + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraProviderCallback::ConfigureStreams(const std::shared_ptr &dhBase, + const std::vector> &streamInfos) +{ + DHLOGW("DCameraProviderCallback::ConfigureStreams enter."); + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraProviderCallback::ReleaseStreams(const std::shared_ptr &dhBase, + const std::vector &streamIds) +{ + DHLOGW("DCameraProviderCallback::ReleaseStreams enter."); + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraProviderCallback::StartCapture(const std::shared_ptr &dhBase, + const std::vector> &captureInfos) +{ + DHLOGW("DCameraProviderCallback::StartCapture enter."); + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraProviderCallback::StopCapture(const std::shared_ptr &dhBase) +{ + DHLOGW("DCameraProviderCallback::StopCapture enter."); + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraProviderCallback::UpdateSettings(const std::shared_ptr &dhBase, + const std::vector> &settings) +{ + DHLOGW("DCameraProviderCallback::UpdateSettings enter."); + return DCamRetCode::SUCCESS; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback.h b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..d2fc22cbf4ff2f107f57953b7346befe45f0697e --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback.h @@ -0,0 +1,43 @@ +/* + * 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 DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_H +#define DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_H + +#include "dcamera_provider_callback_stub.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraProviderCallback : public DCameraProviderCallbackStub { +public: + DCameraProviderCallback() = default; + virtual ~DCameraProviderCallback() = default; + +public: + virtual DCamRetCode OpenSession(const std::shared_ptr &dhBase) override; + virtual DCamRetCode CloseSession(const std::shared_ptr &dhBase) override; + virtual DCamRetCode ConfigureStreams(const std::shared_ptr &dhBase, + const std::vector> &streamInfos) override; + virtual DCamRetCode ReleaseStreams(const std::shared_ptr &dhBase, + const std::vector &streamIds) override; + virtual DCamRetCode StartCapture(const std::shared_ptr &dhBase, + const std::vector> &captureInfos) override; + virtual DCamRetCode StopCapture(const std::shared_ptr &dhBase) override; + virtual DCamRetCode UpdateSettings(const std::shared_ptr &dhBase, + const std::vector> &settings) override; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback_stub.cpp b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8145fe1f31f88a19280feba201c59923989a4a2 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback_stub.cpp @@ -0,0 +1,255 @@ +/* + * 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 "dcamera_provider_callback_stub.h" +#include +#include "dcamera_provider_callback.h" +#include "distributed_hardware_log.h" +#include "ipc_data_utils.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraProviderCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + int32_t ret = HDF_SUCCESS; + switch (code) { + case CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_OPEN_SESSION: { + ret = DCProviderOpenSessionStub(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CLOSE_SESSION: { + ret = DCProviderCloseSessionStub(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CONFIGURE_STREAMS: { + ret = DCProviderConfigureStreamsStub(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_RELEASE_STREAMS: { + ret = DCProviderReleaseStreamsStub(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_START_CAPTURE: { + ret = DCProviderStartCaptureStub(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_STOP_CAPTURE: { + ret = DCProviderStopCaptureStub(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_UPDATE_SETTINGS: { + ret = DCProviderUpdateSettingsStub(data, reply, option); + break; + } + default: { + ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + return ret; +} + +int32_t DCameraProviderCallbackStub::DCProviderOpenSessionStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraProviderCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + DCamRetCode ret = OpenSession(dhBase); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderCallbackStub::DCProviderCloseSessionStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraProviderCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + DCamRetCode ret = CloseSession(dhBase); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderCallbackStub::DCProviderConfigureStreamsStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraProviderCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + int32_t count = data.ReadInt32(); + std::vector> streamInfos; + for (int32_t i = 0; i < count; i++) { + const DCStreamInfo *pInfo = reinterpret_cast( + data.ReadBuffer(sizeof(DCStreamInfo))); + if (pInfo == nullptr) { + DHLOGE("Read distributed camera stream info failed."); + return HDF_FAILURE; + } + std::shared_ptr streamInfo = std::make_shared(); + streamInfo->streamId_ = pInfo->streamId_; + streamInfo->width_ = pInfo->width_; + streamInfo->height_ = pInfo->height_; + streamInfo->stride_ = pInfo->stride_; + streamInfo->format_ = pInfo->format_; + streamInfo->dataspace_ = pInfo->dataspace_; + streamInfo->encodeType_ = pInfo->encodeType_; + streamInfo->type_ = pInfo->type_; + streamInfos.push_back(streamInfo); + } + + DCamRetCode ret = ConfigureStreams(dhBase, streamInfos); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderCallbackStub::DCProviderReleaseStreamsStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraProviderCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + std::vector streamIds; + if (!data.ReadInt32Vector(&streamIds)) { + DHLOGE("Read streamIds failed."); + return HDF_FAILURE; + } + + DCamRetCode ret = ReleaseStreams(dhBase, streamIds); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderCallbackStub::DCProviderStartCaptureStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraProviderCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + int32_t count = data.ReadInt32(); + std::vector> captureInfos; + for (int32_t i = 0; i < count; i++) { + std::shared_ptr captureInfo = std::make_shared(); + std::vector streamIds; + if (!data.ReadInt32Vector(&streamIds)) { + DHLOGE("Read streamIds failed."); + return HDF_FAILURE; + } + captureInfo->streamIds_ = streamIds; + captureInfo->width_ = static_cast(data.ReadInt32()); + captureInfo->height_ = static_cast(data.ReadInt32()); + captureInfo->stride_ = static_cast(data.ReadInt32()); + captureInfo->format_ = static_cast(data.ReadInt32()); + captureInfo->dataspace_ = static_cast(data.ReadInt32()); + captureInfo->isCapture_ = data.ReadBool(); + captureInfo->encodeType_ = static_cast(data.ReadInt32()); + captureInfo->type_ = static_cast(data.ReadInt32()); + + int32_t settingsSize = data.ReadInt32(); + std::vector> capSettings; + for (int32_t k = 0; k < settingsSize; k++) { + std::shared_ptr metadata = std::make_shared(); + IpcDataUtils::DecodeDCameraSettings(data, metadata); + capSettings.push_back(metadata); + } + captureInfo->captureSettings_ = capSettings; + captureInfos.push_back(captureInfo); + } + + DCamRetCode ret = StartCapture(dhBase, captureInfos); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderCallbackStub::DCProviderStopCaptureStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraProviderCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + DCamRetCode ret = StopCapture(dhBase); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderCallbackStub::DCProviderUpdateSettingsStub(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraProviderCallbackStub::GetDescriptor()) { + DHLOGE("OnCaptureStarted invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + int32_t count = data.ReadInt32(); + std::vector> settings; + for (int32_t i = 0; i < count; i++) { + std::shared_ptr metadata = std::make_shared(); + IpcDataUtils::DecodeDCameraSettings(data, metadata); + settings.push_back(metadata); + } + + DCamRetCode ret = UpdateSettings(dhBase, settings); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback_stub.h b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..48f2fa5193b21faa846795343958a22aff1cd6c1 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_callback_stub.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 DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CLIENT_STUB_H +#define DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CLIENT_STUB_H + +#include "idistributed_camera_provider_callback.h" +#include "iremote_stub.h" +#include "message_parcel.h" +#include "parcel.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraProviderCallbackStub : public IRemoteStub { +public: + virtual ~DCameraProviderCallbackStub() = default; + + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) override; + +private: + int32_t DCProviderOpenSessionStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DCProviderCloseSessionStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DCProviderConfigureStreamsStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DCProviderReleaseStreamsStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DCProviderStartCaptureStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DCProviderStopCaptureStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DCProviderUpdateSettingsStub(MessageParcel &data, MessageParcel &reply, MessageOption &option); +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CLIENT_STUB_H diff --git a/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b67de6aaf3cefe902519543908f1b8bb66decab --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_proxy.cpp @@ -0,0 +1,315 @@ +/* + * 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 "dcamera_provider_proxy.h" +#include +#include +#include +#include +#include +#include "distributed_hardware_log.h" +#include "ipc_data_utils.h" +#include "iservmgr_hdi.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string DC_PROVIDER_HDI_SERVER_NAME = "distributed_camera_provider_service"; + +sptr IDCameraProvider::Get() +{ + using namespace OHOS::HDI::ServiceManager::V1_0; + OHOS::sptr serviceMgr = IServiceManager::Get(); + if (serviceMgr == nullptr) { + DHLOGE("Get IServiceManager failed."); + return nullptr; + } + + OHOS::sptr remote = serviceMgr->GetService(DC_PROVIDER_HDI_SERVER_NAME.c_str()); + if (remote == nullptr) { + DHLOGE("GetService failed! serviceName = %s", DC_PROVIDER_HDI_SERVER_NAME.c_str()); + return nullptr; + } + + return iface_cast(remote); +} + +DCamRetCode DCameraProviderProxy::EnableDCameraDevice(const std::shared_ptr &dhBase, + const std::string &abilityInfo, const sptr &callback) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_) || !data.WriteString(abilityInfo)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + bool nullFlag = (callback != nullptr); + if (!data.WriteBool(nullFlag)) { + DHLOGE("Write distributed camera provider callback null flag failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + if (nullFlag && !data.WriteRemoteObject(callback->AsObject())) { + DHLOGE("Set callback write remote obj failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_ENABLE_DEVICE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d", ret); + return DCamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderProxy::DisableDCameraDevice(const std::shared_ptr &dhBase) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_DISABLE_DEVICE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return DCamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderProxy::AcquireBuffer(const std::shared_ptr &dhBase, int streamId, + std::shared_ptr &buffer) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteInt32(static_cast(streamId))) { + DHLOGE("Write streamId failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_ACQUIRE_BUFFER, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return DCamRetCode::INVALID_ARGUMENT; + } + int32_t retCode = reply.ReadInt32(); + if (retCode != DCamRetCode::SUCCESS) { + DHLOGE("Acquire avaliable buffer from stub failed."); + return static_cast(retCode); + } + + buffer = std::make_shared(); + buffer->index_ = reply.ReadInt32(); + buffer->size_ = reply.ReadInt32(); + + BufferHandle* retHandle = ReadBufferHandle(reply); + if (retHandle == nullptr) { + DHLOGE("Read retrun buffer handle failed."); + FreeBufferHandle(buffer->bufferHandle_); + return DCamRetCode::INVALID_ARGUMENT; + } + retHandle->virAddr = DCameraMemoryMap(retHandle); + buffer->bufferHandle_ = retHandle; + + return DCamRetCode::SUCCESS; +} + +DCamRetCode DCameraProviderProxy::ShutterBuffer(const std::shared_ptr &dhBase, int streamId, + const std::shared_ptr &buffer) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + DCamRetCode ret = DCamRetCode::SUCCESS; + do { + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + ret = DCamRetCode::INVALID_ARGUMENT; + break; + } + + if (!data.WriteInt32(static_cast(streamId))) { + DHLOGE("Write streamId failed."); + ret = DCamRetCode::INVALID_ARGUMENT; + break; + } + + bool nullFlag = (buffer != nullptr); + if (!data.WriteBool(nullFlag)) { + DHLOGE("Write distributed camera buffer null flag failed."); + ret = DCamRetCode::INVALID_ARGUMENT; + break; + } + + if (!data.WriteInt32(buffer->index_) || !data.WriteInt32(buffer->size_)) { + DHLOGE("write buffer index and size parameter failed."); + ret = DCamRetCode::INVALID_ARGUMENT; + break; + } + + int32_t retCode = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_SHUTTER_BUFFER, data, reply, option); + if (retCode != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", retCode); + ret = DCamRetCode::FAILED; + } + } while (0); + + DCameraMemoryUnmap(buffer->bufferHandle_); + if (ret != DCamRetCode::SUCCESS) { + return ret; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderProxy::OnSettingsResult(const std::shared_ptr &dhBase, + const std::shared_ptr &result) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + bool nullFlag = (result != nullptr); + if (!data.WriteBool(nullFlag)) { + DHLOGE("Write distributed camera settings null flag failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + if (nullFlag && !IpcDataUtils::EncodeDCameraSettings(result, data)) { + DHLOGE("Write distributed camera settings failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_ON_SETTINGS_RESULT, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return DCamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderProxy::Notify(const std::shared_ptr &dhBase, + const std::shared_ptr &event) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + bool nullFlag = (event != nullptr); + if (!data.WriteBool(nullFlag)) { + DHLOGE("Write distributed camera hdf event null flag failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + if (nullFlag && !IpcDataUtils::EncodeDCameraHDFEvent(event, data)) { + DHLOGE("Write distributed camera hdf event failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_NOTIFY, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return DCamRetCode::INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +void* DCameraProviderProxy::DCameraMemoryMap(const BufferHandle *buffer) +{ + if (buffer == nullptr) { + DHLOGE("mmap the buffer handle is NULL"); + return nullptr; + } + if (buffer->reserveFds <= 0) { + DHLOGE("invalid file descriptor num : %d", buffer->reserveFds); + return nullptr; + } + void* virAddr = mmap(NULL, buffer->size, PROT_READ | PROT_WRITE, MAP_SHARED, buffer->reserve[0], 0); + if (virAddr == MAP_FAILED) { + DHLOGE("mmap failed errno %s, fd : %d", strerror(errno), buffer->fd); + return nullptr; + } + return virAddr; +} + +void DCameraProviderProxy::DCameraMemoryUnmap(BufferHandle *buffer) +{ + if (buffer == nullptr) { + DHLOGE("unmmap the buffer handle is NULL"); + return; + } + if (buffer->virAddr == nullptr) { + DHLOGE("virAddr is NULL , has not map the buffer"); + return; + } + int ret = munmap(buffer->virAddr, buffer->size); + if (ret != 0) { + DHLOGE("munmap failed err: %s", strerror(errno)); + } + buffer->virAddr = nullptr; + FreeBufferHandle(buffer); +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_proxy.h b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..5c41f33424aa79053a8eaec03cb7a3e8f19a178f --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/client/provider/dcamera_provider_proxy.h @@ -0,0 +1,59 @@ +/* + * 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 DISTRIBUTED_CAMERA_PROVIDER_CLIENT_PROXY_H +#define DISTRIBUTED_CAMERA_PROVIDER_CLIENT_PROXY_H + +#include "iremote_proxy.h" +#include "buffer_handle.h" +#include "idistributed_camera_provider.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraProviderProxy : public IRemoteProxy { +public: + explicit DCameraProviderProxy(const sptr &impl) : IRemoteProxy(impl) {} + virtual ~DCameraProviderProxy() = default; + + virtual DCamRetCode EnableDCameraDevice(const std::shared_ptr &dhBase, + const std::string &abilityInfo, + const sptr &callback) override; + virtual DCamRetCode DisableDCameraDevice(const std::shared_ptr &dhBase) override; + virtual DCamRetCode AcquireBuffer(const std::shared_ptr &dhBase, int streamId, + std::shared_ptr &buffer) override; + virtual DCamRetCode ShutterBuffer(const std::shared_ptr &dhBase, int streamId, + const std::shared_ptr &buffer) override; + virtual DCamRetCode OnSettingsResult(const std::shared_ptr &dhBase, + const std::shared_ptr &result) override; + virtual DCamRetCode Notify(const std::shared_ptr &dhBase, + const std::shared_ptr &event) override; + +private: + static void* DCameraMemoryMap(const BufferHandle *buffer); + static void DCameraMemoryUnmap(BufferHandle *buffer); + +private: + static constexpr int CMD_DISTRIBUTED_CAMERA_PROVIDER_ENABLE_DEVICE = 0; + static constexpr int CMD_DISTRIBUTED_CAMERA_PROVIDER_DISABLE_DEVICE = 1; + static constexpr int CMD_DISTRIBUTED_CAMERA_PROVIDER_ACQUIRE_BUFFER = 2; + static constexpr int CMD_DISTRIBUTED_CAMERA_PROVIDER_SHUTTER_BUFFER = 3; + static constexpr int CMD_DISTRIBUTED_CAMERA_PROVIDER_ON_SETTINGS_RESULT = 4; + static constexpr int CMD_DISTRIBUTED_CAMERA_PROVIDER_NOTIFY = 5; + + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_PROVIDER_CLIENT_PROXY_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/config/host/BUILD.gn b/camera_hdf/interfaces/hdi_ipc/config/host/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..77652f8a0aae979808aab370abeb36d930a342d1 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/config/host/BUILD.gn @@ -0,0 +1,73 @@ +# 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. + +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_host_config") { + include_dirs = [ + "${distributedcamera_hdf_path}/interfaces/include", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/server/host", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/server/device", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/server/operator", + "${distributedcamera_hdf_path}/hdi_impl/include/dcamera_host", + "${distributedcamera_hdf_path}/hdi_impl/include/dcamera_device", + "${distributedcamera_hdf_path}/hdi_impl/include/dstream_operator", + "${distributedcamera_hdf_path}/hdi_impl/include/utils", + "${common_path}/include/constants", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${camera_hdf_path}/camera/interfaces/include", + "${hdf_framework_path}/include/utils", + "${hdf_framework_path}/include/core", + "${hdf_framework_path}/include/osal", + "${hdf_uhdf_path}/include/hdi", + "${hdf_uhdf_path}/osal/include", + "${hdf_uhdf_path}/ipc/include", + "${hdf_uhdf_path}/include/host", + + #producer + "//foundation/graphic/standard/frameworks/surface/include", + "//foundation/graphic/standard/interfaces/kits/surface", + "//foundation/graphic/standard/utils/include", + "//foundation/communication/ipc/ipc/native/src/core/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/multimedia/camera_standard/frameworks/native/metadata/include", + ] + + sources = [ + "dcamera_host_config.cpp" + ] + + deps = [ + "//utils/native/base:utils", + "${distributedcamera_hdf_path}/hdi_impl:distributed_camera_hdf", + "//foundation/graphic/standard/frameworks/surface:surface", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"distributedcamerahdf\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + ] + install_images = [ chipset_base_dir ] + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} diff --git a/camera_hdf/interfaces/hdi_ipc/config/host/dcamera_host_config.cpp b/camera_hdf/interfaces/hdi_ipc/config/host/dcamera_host_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da30b84d40d0088b916be927a736851f95e2360a --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/config/host/dcamera_host_config.cpp @@ -0,0 +1,92 @@ +/* + * 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 "dcamera_host_stub.h" +#include +#include +#include +#include + +struct HdfDCameraService { + struct IDeviceIoService ioservice; + void *instance; +}; + +static int32_t DCameraServiceDispatch(struct HdfDeviceIoClient *client, int cmdId, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + HdfDCameraService *service = CONTAINER_OF(client->device->service, HdfDCameraService, ioservice); + return DCHostServiceOnRemoteRequest(service->instance, cmdId, data, reply); +} + +int HdfDCameraHostDriverInit(struct HdfDeviceObject *deviceObject) +{ + return HDF_SUCCESS; +} + +int HdfDCameraHostDriverBind(HdfDeviceObject *deviceObject) +{ + HDF_LOGI("HdfDCameraHostDriverBind enter!"); + if (deviceObject == nullptr) { + HDF_LOGE("HdfDCameraHostDriverBind: HdfDeviceObject is NULL !"); + return HDF_FAILURE; + } + + HdfDCameraService *service = reinterpret_cast(malloc(sizeof(HdfDCameraService))); + if (service == nullptr) { + HDF_LOGE("HdfDCameraHostDriverBind malloc HdfDCameraService failed!"); + return HDF_FAILURE; + } + + service->ioservice.Dispatch = DCameraServiceDispatch; + service->ioservice.Open = nullptr; + service->ioservice.Release = nullptr; + service->instance = DCameraHostStubInstance(); + + deviceObject->service = &service->ioservice; + return HDF_SUCCESS; +} + +void HdfDCameraHostDriverRelease(HdfDeviceObject *deviceObject) +{ + if (deviceObject == nullptr || deviceObject->service == nullptr) { + HDF_LOGE("HdfDCameraHostDriverRelease: deviceObject or deviceObject->service is NULL!"); + return; + } + HdfDCameraService *service = CONTAINER_OF(deviceObject->service, HdfDCameraService, ioservice); + if (service == nullptr) { + HDF_LOGE("HdfDCameraHostDriverRelease: service is NULL!"); + return; + } + free(service); +} + +struct HdfDriverEntry g_dCameraHostDriverEntry = { + .moduleVersion = 1, + .moduleName = "distributed_camera_service", + .Bind = HdfDCameraHostDriverBind, + .Init = HdfDCameraHostDriverInit, + .Release = HdfDCameraHostDriverRelease, +}; + +#ifndef __cplusplus +extern "C" { +#endif + +HDF_INIT(g_dCameraHostDriverEntry); + +#ifndef __cplusplus +} +#endif \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/config/provider/BUILD.gn b/camera_hdf/interfaces/hdi_ipc/config/provider/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8c2f45ee5ff54f7727e255facd999cc9217d1b16 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/config/provider/BUILD.gn @@ -0,0 +1,68 @@ +# 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. + +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_provider_config") { + include_dirs = [ + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/server/provider", + "${distributedcamera_hdf_path}/interfaces/include", + "${distributedcamera_hdf_path}/hdi_impl/include/dcamera_provider", + "${distributedcamera_hdf_path}/hdi_impl/include/utils", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${camera_hdf_path}/camera/interfaces/include", + "${hdf_framework_path}/include/utils", + "${hdf_framework_path}/include/core", + "${hdf_framework_path}/include/osal", + "${hdf_uhdf_path}/include/hdi", + "${hdf_uhdf_path}/osal/include", + "${hdf_uhdf_path}/ipc/include", + "${hdf_uhdf_path}/include/host", + + #producer + "//foundation/graphic/standard/frameworks/surface/include", + "//foundation/graphic/standard/interfaces/kits/surface", + "//foundation/graphic/standard/utils/include", + "//foundation/communication/ipc/ipc/native/src/core/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/multimedia/camera_standard/frameworks/native/metadata/include", + ] + + sources = [ + "dcamera_provider_config.cpp" + ] + + deps = [ + "//utils/native/base:utils", + "${distributedcamera_hdf_path}/hdi_impl:distributed_camera_hdf", + "//foundation/graphic/standard/frameworks/surface:surface", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"distributedcamerahdf\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + ] + install_images = [ chipset_base_dir ] + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} diff --git a/camera_hdf/interfaces/hdi_ipc/config/provider/dcamera_provider_config.cpp b/camera_hdf/interfaces/hdi_ipc/config/provider/dcamera_provider_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..75933736168a8ab714802213931d925027a07024 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/config/provider/dcamera_provider_config.cpp @@ -0,0 +1,93 @@ +/* + * 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 "dcamera_provider_stub.h" +#include +#include +#include +#include + +struct HdfDCameraProviderService { + struct IDeviceIoService ioservice; + void *instance; +}; + +static int32_t DCameraProviderServiceDispatch(struct HdfDeviceIoClient *client, int cmdId, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + HdfDCameraProviderService *service = CONTAINER_OF(client->device->service, HdfDCameraProviderService, ioservice); + return DCProviderServiceOnRemoteRequest(service->instance, cmdId, data, reply); +} + +int HdfDCameraProviderConfigInit(struct HdfDeviceObject *deviceObject) +{ + return HDF_SUCCESS; +} + +int HdfDCameraProviderConfigBind(HdfDeviceObject *deviceObject) +{ + HDF_LOGI("HdfDCameraProviderConfigBind enter!"); + if (deviceObject == nullptr) { + HDF_LOGE("HdfDCameraProviderConfigBind: HdfDeviceObject is NULL !"); + return HDF_FAILURE; + } + + HdfDCameraProviderService *service = + reinterpret_cast(malloc(sizeof(HdfDCameraProviderService))); + if (service == nullptr) { + HDF_LOGE("HdfDCameraProviderConfigBind malloc HdfDCameraProviderService failed!"); + return HDF_FAILURE; + } + + service->ioservice.Dispatch = DCameraProviderServiceDispatch; + service->ioservice.Open = nullptr; + service->ioservice.Release = nullptr; + service->instance = DCameraProviderStubInstance(); + + deviceObject->service = &service->ioservice; + return HDF_SUCCESS; +} + +void HdfDCameraProviderConfigRelease(HdfDeviceObject *deviceObject) +{ + if (deviceObject == nullptr || deviceObject->service == nullptr) { + HDF_LOGE("HdfDCameraProviderConfigRelease: deviceObject or deviceObject->service is NULL!"); + return; + } + HdfDCameraProviderService *service = CONTAINER_OF(deviceObject->service, HdfDCameraProviderService, ioservice); + if (service == nullptr) { + HDF_LOGE("HdfDCameraProviderConfigRelease: service is NULL!"); + return; + } + free(service); +} + +struct HdfDriverEntry g_dCameraProviderConfigEntry = { + .moduleVersion = 1, + .moduleName = "distributed_camera_provider_service", + .Bind = HdfDCameraProviderConfigBind, + .Init = HdfDCameraProviderConfigInit, + .Release = HdfDCameraProviderConfigRelease, +}; + +#ifndef __cplusplus +extern "C" { +#endif + +HDF_INIT(g_dCameraProviderConfigEntry); + +#ifndef __cplusplus +} +#endif diff --git a/camera_hdf/interfaces/hdi_ipc/ipc_data_utils.h b/camera_hdf/interfaces/hdi_ipc/ipc_data_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..b57c44e680477465c248996ca1121f5c29f8e6bf --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/ipc_data_utils.h @@ -0,0 +1,102 @@ +/* + * 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 HDI_IPC_DATA_UTILS_H +#define HDI_IPC_DATA_UTILS_H + +#include +#include +#include +#include +#include +#include +#include "camera_metadata_info.h" +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class IpcDataUtils { +static const uint32_t RATIONAL_TYPE_STEP = 2; +public: + static bool EncodeStreamInfo(const std::shared_ptr &pInfo, MessageParcel &parcel) + { + bool bRet = true; + bRet = (bRet && parcel.WriteInt32(static_cast(pInfo->streamId_))); + bRet = (bRet && parcel.WriteInt32(static_cast(pInfo->width_))); + bRet = (bRet && parcel.WriteInt32(static_cast(pInfo->height_))); + bRet = (bRet && parcel.WriteInt32(static_cast(pInfo->format_))); + bRet = (bRet = (bRet && parcel.WriteInt32(pInfo->intent_))); + bRet = (bRet && parcel.WriteBool(pInfo->tunneledMode_)); + bool bufferQueueFlag = (pInfo->bufferQueue_ != nullptr) ? true : false; + bRet = (bRet && parcel.WriteBool(bufferQueueFlag)); + if (bufferQueueFlag) { + bRet = (bRet && parcel.WriteRemoteObject(pInfo->bufferQueue_->AsObject())); + } + bRet = (bRet && parcel.WriteInt32(static_cast(pInfo->minFrameDuration_))); + bRet = (bRet && parcel.WriteInt32(pInfo->encodeType_)); + return bRet; + } + + static void DecodeStreamInfo(MessageParcel &parcel, std::shared_ptr &pInfo) + { + pInfo->streamId_ = static_cast(parcel.ReadInt32()); + pInfo->width_ = static_cast(parcel.ReadInt32()); + pInfo->height_ = static_cast(parcel.ReadInt32()); + pInfo->format_ = static_cast(parcel.ReadInt32()); + pInfo->intent_ = static_cast(parcel.ReadInt32()); + pInfo->tunneledMode_ = parcel.ReadBool(); + bool bufferQueueFlag = parcel.ReadBool(); + if (bufferQueueFlag) { + sptr remoteBufferProducer = parcel.ReadRemoteObject(); + pInfo->bufferQueue_ = OHOS::iface_cast(remoteBufferProducer); + } + pInfo->minFrameDuration_ = static_cast(parcel.ReadInt32()); + pInfo->encodeType_ = static_cast(parcel.ReadInt32()); + } + + static bool EncodeDCameraSettings(const std::shared_ptr &pSettings, MessageParcel &parcel) + { + bool bRet = true; + bRet = (bRet && parcel.WriteInt32(pSettings->type_)); + bRet = (bRet && parcel.WriteString(pSettings->value_)); + return bRet; + } + + static void DecodeDCameraSettings(MessageParcel &parcel, std::shared_ptr &pSettings) + { + pSettings->type_ = (DCSettingsType)(parcel.ReadInt32()); + pSettings->value_ = parcel.ReadString(); + } + + static bool EncodeDCameraHDFEvent(const std::shared_ptr &pEvent, MessageParcel &parcel) + { + bool bRet = true; + bRet = (bRet && parcel.WriteInt32(pEvent->type_)); + bRet = (bRet && parcel.WriteInt32(pEvent->result_)); + bRet = (bRet && parcel.WriteString(pEvent->content_)); + return bRet; + } + + static void DecodeDCameraHDFEvent(MessageParcel &parcel, std::shared_ptr &pEvent) + { + pEvent->type_ = parcel.ReadInt32(); + pEvent->result_ = parcel.ReadInt32(); + pEvent->content_ = parcel.ReadString(); + } +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // HDI_IPC_DATA_UTILS_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_callback_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_callback_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1d7c6586d6889f2abc5b26dbcc57eceb506745e --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_callback_proxy.cpp @@ -0,0 +1,85 @@ +/* + * 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 "dcamera_device_callback_proxy.h" +#include +#include +#include "distributed_hardware_log.h" +#include "ipc_data_utils.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +void DCameraDeviceCallbackProxy::OnError(ErrorType type, int32_t errorMsg) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (!data.WriteUint32(type)) { + DHLOGE("Write error type failed."); + return; + } + + if (!data.WriteInt32(errorMsg)) { + DHLOGE("Write error message failed."); + return; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_CALLBACK_ON_ERROR, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + } +} + +void DCameraDeviceCallbackProxy::OnResult(uint64_t timestamp, + const std::shared_ptr &result) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraDeviceCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (result == nullptr) { + return; + } + + if (!data.WriteUint64(timestamp)) { + DHLOGE("Write timestamp failed."); + return; + } + + if (!CameraStandard::MetadataUtils::EncodeCameraMetadata(result, data)) { + DHLOGE("Write metadata failed."); + return; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_DEVICE_CALLBACK_ON_RESULT, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return; + } +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_callback_proxy.h b/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..764feb4a1e642109de1a602dae0ea93d6e5b38ab --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_callback_proxy.h @@ -0,0 +1,40 @@ +/* + * 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 DISTRIBUTED_CAMERA_DEVICE_CALLBACK_PROXY_H +#define DISTRIBUTED_CAMERA_DEVICE_CALLBACK_PROXY_H + +#include "iremote_proxy.h" +#include "icamera_device_callback.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraDeviceCallbackProxy : public IRemoteProxy { +public: + explicit DCameraDeviceCallbackProxy(const sptr &impl) + : IRemoteProxy(impl) {} + + virtual ~DCameraDeviceCallbackProxy() = default; + + virtual void OnError(ErrorType type, int32_t errorMsg) override; + virtual void OnResult(uint64_t timestamp, const std::shared_ptr &result) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_DEVICE_CALLBACK_PROXY_H diff --git a/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_stub.cpp b/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81be1631ebac2fd3e96b7be6912da1937349b2ba --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_stub.cpp @@ -0,0 +1,232 @@ +/* + * 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 "dcamera_device_stub.h" +#include +#include +#include "distributed_hardware_log.h" +#include "ipc_data_utils.h" +#include "istream_operator.h" +#include "istream_operator_callback.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraDeviceStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + int32_t ret = HDF_SUCCESS; + switch (code) { + case CMD_CAMERA_DEVICE_GET_STREAM_OPERATOR: { + ret = DCDeviceStubGetStreamOperator(data, reply, option); + break; + } + case CMD_CAMERA_DEVICE_UPDATE_SETTINGS: { + ret = DCDeviceStubUpdateSettings(data, reply, option); + break; + } + case CMD_CAMERA_DEVICE_SET_RESULT_MODE: { + ret = DCDeviceStubSetResultMode(data, reply, option); + break; + } + case CMD_CAMERA_DEVICE_GET_ENABLED_RESULTS: { + ret = DCDeviceStubGetEnabledReuslts(data, reply, option); + break; + } + case CMD_CAMERA_DEVICE_ENABLE_RESULT: { + ret = DCDeviceStubEnableResult(data, reply, option); + break; + } + case CMD_CAMERA_DEVICE_DISABLE_RESULT: { + ret = DCDeviceStubDisableResult(data, reply, option); + break; + } + case CMD_CAMERA_DEVICE_CLOSE: { + ret = DCDeviceStubClose(data, reply, option); + break; + } + default: { + ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + return ret; +} + +int32_t DCameraDeviceStub::DCDeviceStubGetStreamOperator(MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + DHLOGI("DCameraDeviceStub::DCDeviceStubGetStreamOperator entry."); + if (data.ReadInterfaceToken() != DCameraDeviceStub::GetDescriptor()) { + DHLOGE("Invalid token."); + return HDF_FAILURE; + } + + sptr spStreamOperatorCallback = nullptr; + bool flag = data.ReadBool(); + if (flag) { + sptr remoteObj = data.ReadRemoteObject(); + spStreamOperatorCallback = OHOS::iface_cast(remoteObj); + if (spStreamOperatorCallback == nullptr) { + DHLOGE("Read operator callback failed."); + return HDF_FAILURE; + } + } + + OHOS::sptr streamOperator = nullptr; + CamRetCode ret = GetStreamOperator(spStreamOperatorCallback, streamOperator); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Get stream operator failed."); + return HDF_FAILURE; + } + + bool nullFlag = (streamOperator != nullptr); + if (!reply.WriteBool(nullFlag)) { + DHLOGE("Write stream operator flag failed."); + return INVALID_ARGUMENT; + } + + if (nullFlag && !reply.WriteRemoteObject(streamOperator->AsObject())) { + DHLOGE("Write stream operator failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraDeviceStub::DCDeviceStubUpdateSettings(MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + DHLOGI("DCameraDeviceStub::DCDeviceStubUpdateSettings entry."); + if (data.ReadInterfaceToken() != DCameraDeviceStub::GetDescriptor()) { + DHLOGE("Invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr metadata = nullptr; + CameraStandard::MetadataUtils::DecodeCameraMetadata(data, metadata); + + CamRetCode ret = UpdateSettings(metadata); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Get stream operator failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraDeviceStub::DCDeviceStubSetResultMode(MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + DHLOGI("DCameraDeviceStub::DCDeviceStubSetResultMode entry."); + if (data.ReadInterfaceToken() != DCameraDeviceStub::GetDescriptor()) { + DHLOGE("Invalid token."); + return HDF_FAILURE; + } + + ResultCallbackMode mode = static_cast(data.ReadInt32()); + CamRetCode ret = SetResultMode(mode); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraDeviceStub::DCDeviceStubGetEnabledReuslts(MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + DHLOGI("DCameraDeviceStub::DCDeviceStubGetEnabledReuslts entry."); + if (data.ReadInterfaceToken() != DCameraDeviceStub::GetDescriptor()) { + DHLOGE("Invalid token."); + return HDF_FAILURE; + } + + std::vector results; + CamRetCode ret = GetEnabledResults(results); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + + if (!reply.WriteInt32Vector(results)) { + DHLOGE("Write results failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraDeviceStub::DCDeviceStubEnableResult(MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + DHLOGI("DCameraDeviceStub::DCDeviceStubEnableResult entry."); + if (data.ReadInterfaceToken() != DCameraDeviceStub::GetDescriptor()) { + DHLOGE("Invalid token."); + return HDF_FAILURE; + } + + std::vector results; + if (!data.ReadInt32Vector(&results)) { + DHLOGE("Read results failed."); + return HDF_FAILURE; + } + + CamRetCode ret = EnableResult(results); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + + if (!reply.WriteInt32Vector(results)) { + DHLOGE("Write results failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraDeviceStub::DCDeviceStubDisableResult(MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + DHLOGI("DCameraDeviceStub::DCDeviceStubDisableResult entry."); + if (data.ReadInterfaceToken() != DCameraDeviceStub::GetDescriptor()) { + DHLOGE("Invalid token."); + return HDF_FAILURE; + } + + std::vector results; + if (!data.ReadInt32Vector(&results)) { + DHLOGE("Read results failed."); + return HDF_FAILURE; + } + + CamRetCode ret = DisableResult(results); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + + if (!reply.WriteInt32Vector(results)) { + DHLOGE("Write results failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraDeviceStub::DCDeviceStubClose(MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + DHLOGI("DCameraDeviceStub::DCDeviceStubClose entry."); + if (data.ReadInterfaceToken() != DCameraDeviceStub::GetDescriptor()) { + DHLOGE("Invalid token."); + return HDF_FAILURE; + } + + Close(); + return HDF_SUCCESS; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_stub.h b/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..7e8cf2edba30bad92cf1db65b4904e7af885b92f --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/device/dcamera_device_stub.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 DISTRIBUTED_CAMERA_DEVICE_SERVER_STUB_H +#define DISTRIBUTED_CAMERA_DEVICE_SERVER_STUB_H + +#include +#include +#include +#include "icamera_device.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraDeviceStub : public IRemoteStub { +public: + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) override; + +private: + int32_t DCDeviceStubGetStreamOperator(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCDeviceStubUpdateSettings(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCDeviceStubSetResultMode(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCDeviceStubGetEnabledReuslts(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCDeviceStubEnableResult(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCDeviceStubDisableResult(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCDeviceStubClose(MessageParcel& data, MessageParcel& reply, MessageOption& option); +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_DEVICE_SERVER_STUB_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_callback_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_callback_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eed9b4f4bcfa191c06a5e354ed070f46dfe93036 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_callback_proxy.cpp @@ -0,0 +1,104 @@ +/* + * 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 "dcamera_host_callback_proxy.h" +#include +#include +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +void DCameraHostCallbackProxy::OnCameraStatus(const std::string &cameraId, CameraStatus status) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraHostCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (!data.WriteString(cameraId)) { + DHLOGE("Write cameraId failed."); + return; + } + + if (!data.WriteInt32(status)) { + DHLOGE("Write status failed."); + return; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_CALLBACK_ON_STATUS, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + } +} + +void DCameraHostCallbackProxy::OnFlashlightStatus(const std::string &cameraId, FlashlightStatus status) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraHostCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (!data.WriteString(cameraId)) { + DHLOGE("Write cameraId failed."); + return; + } + + if (!data.WriteInt32(status)) { + DHLOGE("Write status failed."); + return; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_CALLBACK_ON_FLASHLIGHT_STATUS, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + } +} + +void DCameraHostCallbackProxy::OnCameraEvent(const std::string &cameraId, CameraEvent event) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraHostCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (!data.WriteString(cameraId)) { + DHLOGE("Write cameraId failed."); + return; + } + + if (!data.WriteInt32(event)) { + DHLOGE("Write event failed."); + return; + } + + int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_CALLBACK_ON_CAMERA_EVENT, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + } +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_callback_proxy.h b/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..07801f35f730efe7a58c0af1ed6a3c46cc516afb --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_callback_proxy.h @@ -0,0 +1,41 @@ +/* + * 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 DISTRIBUTED_CAMERA_HOST_CALLBACK_PROXY_H +#define DISTRIBUTED_CAMERA_HOST_CALLBACK_PROXY_H + +#include "iremote_proxy.h" +#include "icamera_host_callback.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DCameraHostCallbackProxy : public IRemoteProxy { +public: + explicit DCameraHostCallbackProxy(const sptr &impl) + : IRemoteProxy(impl) {} + + virtual ~DCameraHostCallbackProxy() = default; + + virtual void OnCameraStatus(const std::string &cameraId, CameraStatus status); + virtual void OnFlashlightStatus(const std::string &cameraId, FlashlightStatus status); + virtual void OnCameraEvent(const std::string &cameraId, CameraEvent event); + +private: + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_HOST_CALLBACK_PROXY_H diff --git a/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_stub.cpp b/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c11b7125142ea6021537921e05eae49da30355a --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_stub.cpp @@ -0,0 +1,259 @@ +/* + * 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 "dcamera_host_stub.h" +#include +#include +#include +#include "distributed_hardware_log.h" +#include "icamera_device.h" +#include "icamera_host_callback.h" +#include "ipc_data_utils.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraHostStub::DCameraHostStub() +{ +} + +int32_t DCameraHostStub::Init() +{ + dcameraHost_ = DCameraHost::GetInstance(); + if (dcameraHost_ == nullptr) { + DHLOGE("Distributed camera host service start failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraHostStub::DCHostStubSetCallback(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraHostStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + bool flag = data.ReadBool(); + sptr hostCallback = nullptr; + if (flag) { + sptr remoteObj = data.ReadRemoteObject(); + hostCallback = OHOS::iface_cast(remoteObj); + } + CamRetCode ret = dcameraHost_->SetCallback(hostCallback); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraHostStub::DCHostStubGetCameraIds(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraHostStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + if (dcameraHost_ == nullptr) { + return HDF_FAILURE; + } + + std::vector cameraIds; + CamRetCode ret = dcameraHost_->GetCameraIds(cameraIds); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + + if (ret == CamRetCode::NO_ERROR) { + if (!reply.WriteStringVector(cameraIds)) { + DHLOGE("Write cameraIds failed."); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int32_t DCameraHostStub::DCHostStubGetCameraAbility(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraHostStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + const std::string cameraId = data.ReadString(); + if (cameraId.empty()) { + DHLOGE("Read input param is empty."); + return HDF_ERR_INVALID_PARAM; + } + + std::shared_ptr ability = nullptr; + CamRetCode ret = dcameraHost_->GetCameraAbility(cameraId, ability); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + + if (ret == CamRetCode::NO_ERROR) { + bool bRet = CameraStandard::MetadataUtils::EncodeCameraMetadata(ability, reply); + if (!bRet) { + DHLOGE("Write ability failed."); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int32_t DCameraHostStub::DCHostStubOpenCamera(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraHostStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + const std::string cameraId = data.ReadString(); + if (cameraId.empty()) { + DHLOGE("Read input param is empty."); + return HDF_ERR_INVALID_PARAM; + } + + bool flag = data.ReadBool(); + OHOS::sptr deviceCallback = nullptr; + if (flag) { + OHOS::sptr remoteCallback = data.ReadRemoteObject(); + deviceCallback = OHOS::iface_cast(remoteCallback); + } + + OHOS::sptr cameraDevice = nullptr; + CamRetCode ret = dcameraHost_->OpenCamera(cameraId, deviceCallback, cameraDevice); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Get stream operator failed."); + return HDF_FAILURE; + } + + if (ret == CamRetCode::NO_ERROR) { + bool deviceFlag = (cameraDevice != nullptr); + if (!reply.WriteBool(deviceFlag)) { + DHLOGE("Write camera device flag failed."); + return HDF_FAILURE; + } + + if (deviceFlag && !reply.WriteRemoteObject(cameraDevice->AsObject())) { + DHLOGE("Write camera device failed."); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int32_t DCameraHostStub::DCHostStubSetFlashlight(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + if (data.ReadInterfaceToken() != DCameraHostStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + if (dcameraHost_ == nullptr) { + DHLOGE("Camera host is null."); + return HDF_FAILURE; + } + + std::string cameraId = data.ReadString(); + bool isEnable = data.ReadBool(); + CamRetCode ret = dcameraHost_->SetFlashlight(cameraId, isEnable); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraHostStub::OnRemoteRequest(int cmdId, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (cmdId) { + case CMD_CAMERA_HOST_SET_CALLBACK: { + return DCHostStubSetCallback(data, reply, option); + } + case CMD_CAMERA_HOST_GET_CAMERAID: { + return DCHostStubGetCameraIds(data, reply, option); + } + case CMD_CAMERA_HOST_GET_CAMERA_ABILITY: { + return DCHostStubGetCameraAbility(data, reply, option); + } + case CMD_CAMERA_HOST_OPEN_CAMERA: { + return DCHostStubOpenCamera(data, reply, option); + } + case CMD_CAMERA_HOST_SET_FLASH_LIGHT: { + return DCHostStubSetFlashlight(data, reply, option); + } + default: { + DHLOGE("Not support cmd %d.", cmdId); + return HDF_ERR_INVALID_PARAM; + } + } + return HDF_SUCCESS; +} +} // end namespace DistributedHardware +} // end namespace OHOS + +void *DCameraHostStubInstance() +{ + OHOS::DistributedHardware::DCameraHostStub *stub = new (std::nothrow) OHOS::DistributedHardware::DCameraHostStub(); + if (stub == nullptr) { + HDF_LOGE("%{public}s: camera host stub create failed.", __func__); + return nullptr; + } + + int32_t ret = stub->Init(); + if (ret != HDF_SUCCESS) { + delete stub; + stub = nullptr; + return nullptr; + } + return reinterpret_cast(stub); +} + +void DestroyDCameraHostStub(void *stubObj) +{ + delete reinterpret_cast(stubObj); +} + +int32_t DCHostServiceOnRemoteRequest(void *stub, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (stub == nullptr) { + HDF_LOGE("%{public}s:stub is null", __func__); + return HDF_FAILURE; + } + + OHOS::DistributedHardware::DCameraHostStub *dcameraHostStub = + reinterpret_cast(stub); + OHOS::MessageParcel *dataParcel = nullptr; + OHOS::MessageParcel *replyParcel = nullptr; + + if (SbufToParcel(reply, &replyParcel) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:invalid reply sbuf object to dispatch", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:invalid data sbuf object to dispatch", __func__); + return HDF_ERR_INVALID_PARAM; + } + + OHOS::MessageOption option; + return dcameraHostStub->OnRemoteRequest(cmdId, *dataParcel, *replyParcel, option); +} diff --git a/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_stub.h b/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..4939a8c34f18d46f956b7acaa69f8f3401d0ac91 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/host/dcamera_host_stub.h @@ -0,0 +1,69 @@ +/* + * 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 DISTRIBUTED_CAMERA_HOST_SERVER_STUB_H +#define DISTRIBUTED_CAMERA_HOST_SERVER_STUB_H + +#include +#include +#include +#include +#include "dcamera_host.h" +#include "icamera_device_callback.h" +#include "icamera_host_callback.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +enum { + CMD_CAMERA_HOST_SET_CALLBACK = 0, + CMD_CAMERA_HOST_GET_CAMERAID, + CMD_CAMERA_HOST_GET_CAMERA_ABILITY, + CMD_CAMERA_HOST_OPEN_CAMERA, + CMD_CAMERA_HOST_SET_FLASH_LIGHT, +}; + +class DCameraHostStub { +public: + DCameraHostStub(); + virtual ~DCameraHostStub() {} + int32_t Init(); + int32_t OnRemoteRequest(int cmdId, MessageParcel& data, MessageParcel& reply, MessageOption& option); + +private: + int32_t DCHostStubSetCallback(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCHostStubGetCameraIds(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCHostStubGetCameraAbility(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCHostStubOpenCamera(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCHostStubSetFlashlight(MessageParcel& data, MessageParcel& reply, MessageOption& option); + static inline const std::u16string metaDescriptor_ = u"HDI.Camera.V1_0.Host"; + static inline const std::u16string &GetDescriptor() + { + return metaDescriptor_; + } + +private: + std::shared_ptr dcameraHost_ = nullptr; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +void* DCameraHostStubInstance(); + +void DestroyDCameraHostStub(void* obj); + +int32_t DCHostServiceOnRemoteRequest(void* stub, int cmdId, struct HdfSBuf* data, struct HdfSBuf* reply); + +#endif // DISTRIBUTED_CAMERA_HOST_SERVER_STUB_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/operator/doffline_stream_operator_stub.cpp b/camera_hdf/interfaces/hdi_ipc/server/operator/doffline_stream_operator_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d378f32b4bd89f873f70be2e3824736904570ab9 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/operator/doffline_stream_operator_stub.cpp @@ -0,0 +1,104 @@ +/* + * 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 "doffline_stream_operator_stub.h" +#include +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DOfflineStreamOperatorStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + int32_t ret = HDF_SUCCESS; + switch (code) { + case CMD_OFFLINE_STREAM_OPERATOR_CANCEL_CAPTURE: { + ret = DOfflineStreamOperatorStubCancelCapture(data, reply, option); + break; + } + case CMD_OFFLINE_STREAM_OPERATOR_RELEASE_STREAMS: { + ret = DOfflineStreamOperatorStubReleaseStreams(data, reply, option); + break; + } + case CMD_OFFLINE_STREAM_OPERATOR_RELEASE: { + ret = DOfflineStreamOperatorStubRelease(data, reply, option); + break; + } + default: { + ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + return ret; +} + +int32_t DOfflineStreamOperatorStub::DOfflineStreamOperatorStubCancelCapture(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DOfflineStreamOperatorStub::DOfflineStreamOperatorStubCancelCapture entry."); + if (data.ReadInterfaceToken() != DOfflineStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + int32_t captureId = data.ReadInt32(); + CamRetCode ret = CancelCapture(captureId); + if (reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DOfflineStreamOperatorStub::DOfflineStreamOperatorStubReleaseStreams(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DOfflineStreamOperatorStub::DOfflineStreamOperatorStubReleaseStreams entry."); + if (data.ReadInterfaceToken() != DOfflineStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::vector streamIds; + if (!data.ReadInt32Vector(&streamIds)) { + DHLOGE("Read streamIds failed."); + return HDF_FAILURE; + } + + CamRetCode ret = ReleaseStreams(streamIds); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DOfflineStreamOperatorStub::DOfflineStreamOperatorStubRelease(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DOfflineStreamOperatorStub::DOfflineStreamOperatorStubRelease entry."); + if (data.ReadInterfaceToken() != DOfflineStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + CamRetCode ret = Release(); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("%s: write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/operator/doffline_stream_operator_stub.h b/camera_hdf/interfaces/hdi_ipc/server/operator/doffline_stream_operator_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..53d1a8e13141e8b3f486e767b93687b703505db9 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/operator/doffline_stream_operator_stub.h @@ -0,0 +1,39 @@ +/* + * 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 DISTRIBUTED_OFFLINE_STREAM_OPERATOR_SERVER_STUB_H +#define DISTRIBUTED_OFFLINE_STREAM_OPERATOR_SERVER_STUB_H + +#include +#include +#include +#include "ioffline_stream_operator.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DOfflineStreamOperatorStub : public IRemoteStub { +public: + int32_t OnRemoteRequest(uint32_t code, + MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + int32_t DOfflineStreamOperatorStubCancelCapture(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DOfflineStreamOperatorStubReleaseStreams(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DOfflineStreamOperatorStubRelease(MessageParcel &data, MessageParcel &reply, MessageOption &option); +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_OFFLINE_STREAM_OPERATOR_SERVER_STUB_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_callback_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_callback_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e206856f551acc04ea7af3803105e781404b577 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_callback_proxy.cpp @@ -0,0 +1,159 @@ +/* + * 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 "dstream_operator_callback_proxy.h" +#include +#include +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +void DStreamOperatorCallbackProxy::OnCaptureStarted(int32_t captureId, const std::vector &streamId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (!data.WriteInt32(captureId)) { + DHLOGE("Write captureId failed."); + return; + } + + if (!data.WriteInt32Vector(streamId)) { + DHLOGE("Write streamIds failed."); + return; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_CALLBACK_ON_CAPTURE_STARTED, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + } +} + +void DStreamOperatorCallbackProxy::OnCaptureEnded(int32_t captureId, + const std::vector> &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (!data.WriteInt32(captureId)) { + DHLOGE("Write captureId failed."); + return; + } + + size_t size = info.size(); + if (!data.WriteInt32(static_cast(size))) { + DHLOGE("Write info size failed."); + return; + } + for (size_t i = 0; i < size; i++) { + auto captureEndInfo = info.at(i); + bool bRet = data.WriteBuffer((void *)captureEndInfo.get(), sizeof(CaptureEndedInfo)); + if (!bRet) { + DHLOGE("Write info index = %d failed.", i); + return; + } + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_CALLBACK_ON_CAPTURE_ENDED, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return; + } +} + +void DStreamOperatorCallbackProxy::OnCaptureError(int32_t captureId, + const std::vector> &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (!data.WriteInt32(captureId)) { + DHLOGE("Write captureId failed."); + return; + } + + size_t size = info.size(); + if (!data.WriteInt32(static_cast(size))) { + DHLOGE("Write info size failed."); + return; + } + for (size_t i = 0; i < size; i++) { + auto captureErrorInfo = info.at(i); + bool bRet = data.WriteBuffer((void *)captureErrorInfo.get(), sizeof(CaptureErrorInfo)); + if (!bRet) { + DHLOGE("Write info index = %d failed.", i); + return; + } + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_CALLBACK_ON_CAPTURE_ERROR, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return; + } +} + +void DStreamOperatorCallbackProxy::OnFrameShutter(int32_t captureId, + const std::vector &streamId, uint64_t timestamp) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DStreamOperatorCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return; + } + + if (!data.WriteInt32(captureId)) { + DHLOGE("Write captureId failed."); + return; + } + + if (!data.WriteInt32Vector(streamId)) { + DHLOGE("Write streamId failed."); + return; + } + + if (!data.WriteUint64(timestamp)) { + DHLOGE("Write streamId failed."); + return; + } + + int32_t ret = Remote()->SendRequest(CMD_STREAM_OPERATOR_CALLBACK_ON_FRAME_SHUTTER, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + } +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_callback_proxy.h b/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..15d270cd7d7af55421a25c69dfb46b2c54c48d73 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_callback_proxy.h @@ -0,0 +1,45 @@ +/* + * 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 DISTRIBUTED_STREAM_OPERATOR_CALLBACK_PROXY_H +#define DISTRIBUTED_STREAM_OPERATOR_CALLBACK_PROXY_H + +#include "iremote_proxy.h" +#include "istream_operator_callback.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DStreamOperatorCallbackProxy : public IRemoteProxy { +public: + explicit DStreamOperatorCallbackProxy(const sptr &impl) + : IRemoteProxy(impl) {} + + virtual ~DStreamOperatorCallbackProxy() = default; + + virtual void OnCaptureStarted(int32_t captureId, const std::vector &streamId) override; + virtual void OnCaptureEnded(int32_t captureId, + const std::vector> &info) override; + virtual void OnCaptureError(int32_t captureId, + const std::vector> &info) override; + virtual void OnFrameShutter(int32_t captureId, + const std::vector &streamId, uint64_t timestamp) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_STREAM_OPERATOR_CALLBACK_PROXY_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_stub.cpp b/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8dc46ad819a98eac292f94e9e835c3412135968 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_stub.cpp @@ -0,0 +1,352 @@ +/* + * 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 "dstream_operator_stub.h" +#include +#include "distributed_hardware_log.h" +#include "ioffline_stream_operator.h" +#include "ipc_data_utils.h" +#include "istream_operator_callback.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DStreamOperatorStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + int32_t ret = HDF_SUCCESS; + switch (code) { + case CMD_STREAM_OPERATOR_IS_STREAMS_SUPPORTED: { + ret = DStreamOperatorStubIsStreamsSupported(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_CREATE_STREAMS: { + ret = DStreamOperatorStubCreateStreams(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_RELEASE_STREAMS: { + ret = DStreamOperatorStubReleaseStreams(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_COMMIT_STREAMS: { + ret = DStreamOperatorStubCommitStreams(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_GET_STREAM_ATTRIBUTES: { + ret = DStreamOperatorStubGetStreamAttributes(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_ATTACH_BUFFER_QUEUE: { + ret = DStreamOperatorStubAttachBufferQueue(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_DETACH_BUFFER_QUEUE: { + ret = DStreamOperatorStubDetachBufferQueue(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_CAPTURE: { + ret = DStreamOperatorStubCapture(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_CANCEL_CAPTURE: { + ret = DStreamOperatorStubCancelCapture(data, reply, option); + break; + } + case CMD_STREAM_OPERATOR_CHANGE_TO_OFFLINE_STREAM: { + ret = DStreamOperatorStubChangeToOfflineStream(data, reply, option); + break; + } + default: { + ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + return ret; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubIsStreamsSupported(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubIsStreamsSupported entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + OperationMode operationMode = static_cast(data.ReadInt32()); + + std::shared_ptr metadata = nullptr; + bool nullFlag = data.ReadBool(); + if (nullFlag) { + CameraStandard::MetadataUtils::DecodeCameraMetadata(data, metadata); + } + + int32_t count = data.ReadInt32(); + std::vector> streamInfos; + for (int i = 0; i < count; i++) { + std::shared_ptr streamInfo = std::make_shared(); + IpcDataUtils::DecodeStreamInfo(data, streamInfo); + streamInfos.push_back(streamInfo); + } + + StreamSupportType streamSupportType; + CamRetCode ret = IsStreamsSupported(operationMode, metadata, streamInfos, streamSupportType); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + + if (!reply.WriteInt32(static_cast(streamSupportType))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubCreateStreams(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubCreateStreams entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + int32_t count = data.ReadInt32(); + std::vector> streamInfos; + for (int i = 0; i < count; i++) { + std::shared_ptr streamInfo = std::make_shared(); + IpcDataUtils::DecodeStreamInfo(data, streamInfo); + streamInfos.push_back(streamInfo); + } + + CamRetCode ret = CreateStreams(streamInfos); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubReleaseStreams(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubReleaseStreams entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::vector streamIds; + if (!data.ReadInt32Vector(&streamIds)) { + DHLOGE("Read streamIds failed."); + return HDF_FAILURE; + } + + CamRetCode ret = ReleaseStreams(streamIds); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubCommitStreams(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubCommitStreams entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + OperationMode mode = static_cast(data.ReadInt32()); + + std::shared_ptr metadata = nullptr; + CameraStandard::MetadataUtils::DecodeCameraMetadata(data, metadata); + + CamRetCode ret = CommitStreams(mode, metadata); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubGetStreamAttributes(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubGetStreamAttributes entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::vector> attributes; + CamRetCode ret = GetStreamAttributes(attributes); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + + size_t count = attributes.size(); + if (!reply.WriteInt32(static_cast(count))) { + DHLOGE("Write attributes count failed."); + return HDF_FAILURE; + } + + for (size_t i = 0; i < count; i++) { + if (!reply.WriteBuffer((void *)(attributes[i].get()), sizeof(StreamAttribute))) { + DHLOGE("Write attribute failed. index = %d.", i); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubAttachBufferQueue(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubAttachBufferQueue entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + int32_t streamId = data.ReadInt32(); + sptr remoteObj = data.ReadRemoteObject(); + const sptr bufferProducer = OHOS::iface_cast(remoteObj); + + CamRetCode ret = AttachBufferQueue(streamId, bufferProducer); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubDetachBufferQueue( + MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubDetachBufferQueue entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + int32_t streamId = data.ReadInt32(); + CamRetCode ret = DetachBufferQueue(streamId); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubCapture(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubCapture entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + int captureId = static_cast(data.ReadInt32()); + + std::vector streamIds; + if (!data.ReadInt32Vector(&streamIds)) { + DHLOGE("Write streamIds failed."); + return HDF_FAILURE; + } + + std::shared_ptr metadata = nullptr; + CameraStandard::MetadataUtils::DecodeCameraMetadata(data, metadata); + + bool enableShutterCallback = data.ReadBool(); + std::shared_ptr pInfo = std::make_shared(); + pInfo->streamIds_ = streamIds; + pInfo->captureSetting_ = metadata; + pInfo->enableShutterCallback_ = enableShutterCallback; + + bool isStreaming = data.ReadBool(); + + CamRetCode ret = Capture(captureId, pInfo, isStreaming); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubCancelCapture(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubCancelCapture entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + int32_t captureId = data.ReadInt32(); + CamRetCode ret = CancelCapture(captureId); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DStreamOperatorStub::DStreamOperatorStubChangeToOfflineStream(MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DStreamOperatorStub::DStreamOperatorStubChangeToOfflineStream entry."); + if (data.ReadInterfaceToken() != DStreamOperatorStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::vector streamIds; + if (!data.ReadInt32Vector(&streamIds)) { + DHLOGE("Read streamIds failed."); + return HDF_FAILURE; + } + + sptr remoteObj = data.ReadRemoteObject(); + sptr spStreamOperatorCallback = OHOS::iface_cast(remoteObj); + if (spStreamOperatorCallback == nullptr) { + DHLOGE("Read operator callback failed."); + return HDF_FAILURE; + } + + OHOS::sptr offlineOperator = nullptr; + CamRetCode ret = ChangeToOfflineStream(streamIds, spStreamOperatorCallback, offlineOperator); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("%s: write retcode failed."); + return HDF_FAILURE; + } + + if (offlineOperator == nullptr) { + DHLOGE("Change to offline stream failed, offlineOperator is null."); + return HDF_FAILURE; + } + + if (!reply.WriteRemoteObject(offlineOperator->AsObject())) { + DHLOGE("Write offline stream operator failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_stub.h b/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..654c2ce111fab8a0fc205d3b147f945516e6322c --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/operator/dstream_operator_stub.h @@ -0,0 +1,47 @@ +/* + * 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 DISTRIBUTED_STREAM_OPERATOR_SERVER_STUB_H +#define DISTRIBUTED_STREAM_OPERATOR_SERVER_STUB_H + +#include +#include +#include +#include "iremote_stub.h" +#include "istream_operator.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Camera; +class DStreamOperatorStub : public IRemoteStub { +public: + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) override; + +private: + int32_t DStreamOperatorStubIsStreamsSupported(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubCreateStreams(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubReleaseStreams(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubCommitStreams(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubGetStreamAttributes(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubAttachBufferQueue(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubDetachBufferQueue(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubCapture(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubCancelCapture(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DStreamOperatorStubChangeToOfflineStream(MessageParcel &data, MessageParcel &reply, MessageOption &option); +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_STREAM_OPERATOR_SERVER_STUB_H \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_callback_proxy.cpp b/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_callback_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a9acc630467a1e942f6707d0bc6fe38c05bff1a --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_callback_proxy.cpp @@ -0,0 +1,267 @@ +/* + * 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 "dcamera_provider_callback_proxy.h" +#include +#include +#include "distributed_hardware_log.h" +#include "ipc_data_utils.h" + +namespace OHOS { +namespace DistributedHardware { +DCamRetCode DCameraProviderCallbackProxy::OpenSession(const std::shared_ptr &dhBase) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_OPEN_SESSION, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderCallbackProxy::CloseSession(const std::shared_ptr &dhBase) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CLOSE_SESSION, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderCallbackProxy::ConfigureStreams(const std::shared_ptr &dhBase, + const std::vector> &streamInfos) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + size_t size = streamInfos.size(); + if (!data.WriteInt32(static_cast(size))) { + DHLOGE("Write stream info size failed."); + return INVALID_ARGUMENT; + } + for (size_t i = 0; i < size; i++) { + auto streamInfo = streamInfos.at(i); + bool bRet = data.WriteBuffer((void *)streamInfo.get(), sizeof(DCStreamInfo)); + if (!bRet) { + DHLOGE("Write stream info index = %d failed.", i); + return INVALID_ARGUMENT; + } + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CONFIGURE_STREAMS, + data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderCallbackProxy::ReleaseStreams(const std::shared_ptr &dhBase, + const std::vector &streamIds) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + std::vector pxyStreamIds = streamIds; + if (!data.WriteInt32Vector(pxyStreamIds)) { + DHLOGE("Write streamId failed."); + return INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_RELEASE_STREAMS, + data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d", ret); + return INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderCallbackProxy::StartCapture(const std::shared_ptr &dhBase, + const std::vector> &captureInfos) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + size_t size = captureInfos.size(); + if (!data.WriteInt32(static_cast(size))) { + DHLOGE("Write distributed camera capture info size failed."); + return INVALID_ARGUMENT; + } + for (size_t i = 0; i < size; i++) { + auto captureInfo = captureInfos.at(i); + if (!data.WriteInt32Vector(captureInfo->streamIds_)) { + DHLOGE("Write streamIds vector failed."); + return INVALID_ARGUMENT; + } + data.WriteInt32(static_cast(captureInfo->width_)); + data.WriteInt32(static_cast(captureInfo->height_)); + data.WriteInt32(static_cast(captureInfo->stride_)); + data.WriteInt32(static_cast(captureInfo->format_)); + data.WriteInt32(static_cast(captureInfo->dataspace_)); + data.WriteBool(static_cast(captureInfo->isCapture_)); + data.WriteInt32(static_cast(captureInfo->encodeType_)); + data.WriteInt32(static_cast(captureInfo->type_)); + + std::vector> capSettings = captureInfo->captureSettings_; + size_t settingsSize = capSettings.size(); + if (!data.WriteInt32(static_cast(settingsSize))) { + DHLOGE("Write distributed camera capture settings size failed."); + return INVALID_ARGUMENT; + } + for (size_t k = 0; k < settingsSize; k++) { + bool bRet = IpcDataUtils::EncodeDCameraSettings(capSettings.at(k), data); + if (!bRet) { + DHLOGE("Write distributed camera capture settings failed."); + return INVALID_ARGUMENT; + } + } + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_START_CAPTURE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d", ret); + return INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderCallbackProxy::StopCapture(const std::shared_ptr &dhBase) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_STOP_CAPTURE, data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} + +DCamRetCode DCameraProviderCallbackProxy::UpdateSettings(const std::shared_ptr &dhBase, + const std::vector> &settings) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DCameraProviderCallbackProxy::GetDescriptor())) { + DHLOGE("Write token failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + if (!data.WriteString(dhBase->deviceId_) || !data.WriteString(dhBase->dhId_)) { + DHLOGE("Write distributed camera base info or ability info failed."); + return DCamRetCode::INVALID_ARGUMENT; + } + + size_t size = settings.size(); + if (!data.WriteInt32(static_cast(size))) { + DHLOGE("Write distributed camera settings size failed."); + return INVALID_ARGUMENT; + } + for (size_t i = 0; i < size; i++) { + bool bRet = IpcDataUtils::EncodeDCameraSettings(settings.at(i), data); + if (!bRet) { + DHLOGE("Write distributed camera settings index = %d failed.", i); + return INVALID_ARGUMENT; + } + } + + int32_t ret = Remote()->SendRequest(CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_UPDATE_SETTINGS, + data, reply, option); + if (ret != HDF_SUCCESS) { + DHLOGE("SendRequest failed, error code is %d.", ret); + return INVALID_ARGUMENT; + } + return static_cast(reply.ReadInt32()); +} +} // end namespace DistributedHardware +} // end namespace OHOS \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_callback_proxy.h b/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..4930eed68a06767f0e4915ae0e3e9612fb24fd3a --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_callback_proxy.h @@ -0,0 +1,48 @@ +/* + * 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 DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_PROXY_H +#define DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_PROXY_H + +#include "iremote_proxy.h" +#include "idistributed_camera_provider_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraProviderCallbackProxy : public IRemoteProxy { +public: + explicit DCameraProviderCallbackProxy(const sptr &impl) + : IRemoteProxy(impl) {} + + virtual ~DCameraProviderCallbackProxy() = default; + + virtual DCamRetCode OpenSession(const std::shared_ptr &dhBase); + virtual DCamRetCode CloseSession(const std::shared_ptr &dhBase); + virtual DCamRetCode ConfigureStreams(const std::shared_ptr &dhBase, + const std::vector> &streamInfos); + virtual DCamRetCode ReleaseStreams(const std::shared_ptr &dhBase, + const std::vector &streamIds); + virtual DCamRetCode StartCapture(const std::shared_ptr &dhBase, + const std::vector> &captureInfos); + virtual DCamRetCode StopCapture(const std::shared_ptr &dhBase); + virtual DCamRetCode UpdateSettings(const std::shared_ptr &dhBase, + const std::vector> &settings); + +private: + static inline BrokerDelegator delegator_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS +#endif // DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_PROXY_H diff --git a/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_stub.cpp b/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb1245a9a162ee92061191549dad639e4789fcd3 --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_stub.cpp @@ -0,0 +1,295 @@ +/* + * 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 "dcamera_provider_stub.h" +#include +#include +#include +#include "distributed_hardware_log.h" +#include "idistributed_camera_provider.h" +#include "ipc_data_utils.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraProviderStub::DCameraProviderStub() +{ +} + +int32_t DCameraProviderStub::Init() +{ + dcameraProvider_ = DCameraProvider::GetInstance(); + if (dcameraProvider_ == nullptr) { + DHLOGE("Get distributed camera provider instance failed."); + return HDF_FAILURE; + } + DHLOGI("Get distributed camera provider instance success."); + return HDF_SUCCESS; +} + +int32_t DCameraProviderStub::DCProviderStubEnableDCameraDevice(MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + if (data.ReadInterfaceToken() != DCameraProviderStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + const std::string abilitySet = data.ReadString(); + if (abilitySet.empty()) { + DHLOGE("Read input param is empty."); + return HDF_ERR_INVALID_PARAM; + } + + sptr dcProviderCallback = nullptr; + bool flag = data.ReadBool(); + if (flag) { + sptr remoteObj = data.ReadRemoteObject(); + if (remoteObj == nullptr) { + DHLOGE("Read distributed camera provider callback failed."); + return HDF_FAILURE; + } + dcProviderCallback = OHOS::iface_cast(remoteObj); + } + + DCamRetCode ret = dcameraProvider_->EnableDCameraDevice(dhBase, abilitySet, dcProviderCallback); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderStub::DCProviderStubDisableDCameraDevice(MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + if (data.ReadInterfaceToken() != DCameraProviderStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + DCamRetCode ret = dcameraProvider_->DisableDCameraDevice(dhBase); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderStub::DCProviderStubAcquireBuffer(MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + if (data.ReadInterfaceToken() != DCameraProviderStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + int32_t streamId = data.ReadInt32(); + + std::shared_ptr dCamerabuffer = std::make_shared(); + DCamRetCode ret = dcameraProvider_->AcquireBuffer(dhBase, streamId, dCamerabuffer); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + if (ret != DCamRetCode::SUCCESS) { + DHLOGE("Acquire avaliable buffer failed."); + return HDF_SUCCESS; + } + if (!reply.WriteInt32(dCamerabuffer->index_) || !reply.WriteInt32(dCamerabuffer->size_)) { + DHLOGE("write buffer index and size parameter failed."); + return HDF_FAILURE; + } + + BufferHandle* bufferHandle = dCamerabuffer->bufferHandle_; + if (!WriteBufferHandle(reply, *bufferHandle)) { + DHLOGE("Write buffer handle failed."); + FreeBufferHandle(bufferHandle); + return HDF_ERR_INVALID_PARAM; + } + + return HDF_SUCCESS; +} + +int32_t DCameraProviderStub::DCProviderStubShutterBuffer(MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + if (data.ReadInterfaceToken() != DCameraProviderStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + int32_t streamId = data.ReadInt32(); + + std::shared_ptr buffer = nullptr; + bool flag = data.ReadBool(); + if (flag) { + buffer = std::make_shared(); + buffer->index_ = data.ReadInt32(); + buffer->size_ = data.ReadInt32(); + buffer->bufferHandle_ = nullptr; + } + DCamRetCode ret = dcameraProvider_->ShutterBuffer(dhBase, streamId, buffer); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderStub::DCProviderStubOnSettingsResult(MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + if (data.ReadInterfaceToken() != DCameraProviderStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + std::shared_ptr dCameraSettings = std::make_shared(); + bool flag = data.ReadBool(); + if (flag) { + IpcDataUtils::DecodeDCameraSettings(data, dCameraSettings); + if (dCameraSettings == nullptr) { + DHLOGE("Read distributed camera settings failed."); + return HDF_FAILURE; + } + } + DCamRetCode ret = dcameraProvider_->OnSettingsResult(dhBase, dCameraSettings); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderStub::DCProviderStubNotify(MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + if (data.ReadInterfaceToken() != DCameraProviderStub::GetDescriptor()) { + DHLOGE("invalid token."); + return HDF_FAILURE; + } + + std::shared_ptr dhBase = std::make_shared(data.ReadString(), data.ReadString()); + + std::shared_ptr dCameraEvent = std::make_shared(); + bool flag = data.ReadBool(); + if (flag) { + IpcDataUtils::DecodeDCameraHDFEvent(data, dCameraEvent); + if (dCameraEvent == nullptr) { + DHLOGE("Read distributed camera hdf event failed."); + return HDF_FAILURE; + } + } + DCamRetCode ret = dcameraProvider_->Notify(dhBase, dCameraEvent); + if (!reply.WriteInt32(static_cast(ret))) { + DHLOGE("Write retcode failed."); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t DCameraProviderStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + int32_t ret = HDF_SUCCESS; + switch (code) { + case CMD_DISTRIBUTED_CAMERA_PROVIDER_ENABLE_DEVICE: { + ret = DCProviderStubEnableDCameraDevice(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_DISABLE_DEVICE: { + ret = DCProviderStubDisableDCameraDevice(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_ACQUIRE_BUFFER: { + ret = DCProviderStubAcquireBuffer(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_SHUTTER_BUFFER: { + ret = DCProviderStubShutterBuffer(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_ON_SETTINGS_RESULT: { + ret = DCProviderStubOnSettingsResult(data, reply, option); + break; + } + case CMD_DISTRIBUTED_CAMERA_PROVIDER_NOTIFY: { + ret = DCProviderStubNotify(data, reply, option); + break; + } + default: { + DHLOGE("Unknown remote request code=%d.", code); + } + } + return ret; +} +} // end namespace DistributedHardware +} // end namespace OHOS + +void *DCameraProviderStubInstance() +{ + OHOS::DistributedHardware::DCameraProviderStub *stub = + new (std::nothrow) OHOS::DistributedHardware::DCameraProviderStub(); + if (stub == nullptr) { + HDF_LOGE("%{public}s: camera provider stub create failed.", __func__); + return nullptr; + } + + int32_t ret = stub->Init(); + if (ret != HDF_SUCCESS) { + delete stub; + stub = nullptr; + return nullptr; + } + return reinterpret_cast(stub); +} + +void DestroyDCameraProviderStub(void *stubObj) +{ + delete reinterpret_cast(stubObj); +} + +int32_t DCProviderServiceOnRemoteRequest(void *stub, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (stub == nullptr) { + HDF_LOGE("%{public}s:stub is null", __func__); + return HDF_FAILURE; + } + + OHOS::DistributedHardware::DCameraProviderStub *providerStub = + reinterpret_cast(stub); + OHOS::MessageParcel *dataParcel = nullptr; + OHOS::MessageParcel *replyParcel = nullptr; + + if (SbufToParcel(reply, &replyParcel) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:invalid reply sbuf object to dispatch", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:invalid data sbuf object to dispatch", __func__); + return HDF_ERR_INVALID_PARAM; + } + + OHOS::MessageOption option; + return providerStub->OnRemoteRequest(cmdId, *dataParcel, *replyParcel, option); +} \ No newline at end of file diff --git a/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_stub.h b/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..e5170a167b733a11bf740467dab7c56736cac16f --- /dev/null +++ b/camera_hdf/interfaces/hdi_ipc/server/provider/dcamera_provider_stub.h @@ -0,0 +1,60 @@ +/* + * 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 DISTRIBUTED_CAMERA_PROVIDER_SERVER_STUB_H +#define DISTRIBUTED_CAMERA_PROVIDER_SERVER_STUB_H + +#include +#include +#include +#include "dcamera_provider.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraProviderStub { +public: + DCameraProviderStub(); + virtual ~DCameraProviderStub() {} + int32_t Init(); + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option); + +private: + int32_t DCProviderStubEnableDCameraDevice(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCProviderStubDisableDCameraDevice(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCProviderStubAcquireBuffer(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCProviderStubShutterBuffer(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCProviderStubOnSettingsResult(MessageParcel& data, MessageParcel& reply, MessageOption& option); + int32_t DCProviderStubNotify(MessageParcel& data, MessageParcel& reply, MessageOption& option); + static inline const std::u16string metaDescriptor_ = u"HDI.DCamera.V1_0.Provider"; + static inline const std::u16string &GetDescriptor() + { + return metaDescriptor_; + } + +private: + std::shared_ptr dcameraProvider_ = nullptr; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +void* DCameraProviderStubInstance(); + +void DestroyDCameraProviderStub(void* obj); + +int32_t DCProviderServiceOnRemoteRequest(void* stub, int cmdId, struct HdfSBuf* data, struct HdfSBuf* reply); + +#endif // DISTRIBUTED_CAMERA_PROVIDER_SERVER_STUB_H \ No newline at end of file diff --git a/camera_hdf/interfaces/include/idistributed_camera_provider.h b/camera_hdf/interfaces/include/idistributed_camera_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..e9365b5b30f0060586a92db1a04296c29604cc9c --- /dev/null +++ b/camera_hdf/interfaces/include/idistributed_camera_provider.h @@ -0,0 +1,164 @@ +/* + * 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. + */ + +/** + * @file idistributed_camera_provider.h + * + * @brief Transfer interfaces call between distributed camera SA service and distributed camera HDF service, + * and provide Hardware Driver Interfaces (HDIs) for the upper layer. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDI_DISTRIBUTED_CAMERA_PROVIDER_H +#define HDI_DISTRIBUTED_CAMERA_PROVIDER_H + +#include "idistributed_camera_provider_callback.h" + +namespace OHOS { +namespace DistributedHardware { +enum { + CMD_DISTRIBUTED_CAMERA_PROVIDER_ENABLE_DEVICE = 0, + CMD_DISTRIBUTED_CAMERA_PROVIDER_DISABLE_DEVICE, + CMD_DISTRIBUTED_CAMERA_PROVIDER_ACQUIRE_BUFFER, + CMD_DISTRIBUTED_CAMERA_PROVIDER_SHUTTER_BUFFER, + CMD_DISTRIBUTED_CAMERA_PROVIDER_ON_SETTINGS_RESULT, + CMD_DISTRIBUTED_CAMERA_PROVIDER_NOTIFY, +}; + +class IDCameraProvider : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"HDI.DCamera.V1_0.Provider"); + virtual ~IDCameraProvider() {} + +public: + /** + * @brief Obtains an IDCameraProvider instance. + * This function provides the entry to the distributed camera SA service. + * You must use this function to obtain an IDCameraProvider instance before performing other operations. + * + * @return Returns the IDCameraProvider instance if the operation is successful, + * returns nullptr otherwise. + * + * @since 1.0 + * @version 1.0 + */ + static sptr Get(); + + /** + * @brief Enable distributed camera device and set callback. For details about the callbacks, + * see {@link IDCameraProviderCallback}. + * + * @param dhBase [in] Distributed hardware device base info. + * + * @param abilityInfo [in] The static capability info of the distributed camera device to be enabled. + * + * @param callback [in] Indicates the callbacks to set. + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode EnableDCameraDevice(const std::shared_ptr &dhBase, + const std::string &abilityInfo, const sptr &callback) = 0; + + /** + * @brief Disable distributed camera device. + * + * @param dhBase [in] Distributed hardware device base info + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode DisableDCameraDevice(const std::shared_ptr &dhBase) = 0; + + /** + * @brief Acquire a frame buffer from the procedure handle which attached to the streamId. + * + * @param dhBase [in] Distributed hardware device base info + * + * @param streamId [in] Indicates the ID of the stream to which the procedure handle is to be attached. + * + * @param buffer [out] A frame buffer + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode AcquireBuffer(const std::shared_ptr &dhBase, int streamId, + std::shared_ptr &buffer) = 0; + + /** + * @brief Notify distributed camera HDF service when a frame buffer has been filled. + * + * @param dhBase [in] Distributed hardware device base info + * + * @param streamId [in] Indicates the ID of the stream to which the frame buffer is to be attached. + * + * @param buffer [out] output frame buffer + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode ShutterBuffer(const std::shared_ptr &dhBase, int streamId, + const std::shared_ptr &buffer) = 0; + + /** + * @brief Called to report metadata related to the distributed camera device. + * + * @param dhBase [in] Distributed hardware device base info + * + * @param result Indicates the metadata reported. + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode OnSettingsResult(const std::shared_ptr &dhBase, + const std::shared_ptr &result) = 0; + + /** + * @brief Called to notify some events from distributed camera SA service to distributed camera HDF service. + * + * @param dhBase [in] Distributed hardware device base info + * + * @param event [in] Detail event contents + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode Notify(const std::shared_ptr &dhBase, + const std::shared_ptr &event) = 0; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +#endif // HDI_DISTRIBUTED_CAMERA_PROVIDER_H \ No newline at end of file diff --git a/camera_hdf/interfaces/include/idistributed_camera_provider_callback.h b/camera_hdf/interfaces/include/idistributed_camera_provider_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..a6ec4d76174516232d6551a2936155327607c395 --- /dev/null +++ b/camera_hdf/interfaces/include/idistributed_camera_provider_callback.h @@ -0,0 +1,161 @@ +/* + * 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. + */ + +/** + * @file idistributed_camera_provider_callback.h + * + * @brief Declares callbacks for distributed camera SA service. The caller needs to implement the callbacks. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef HDI_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_H +#define HDI_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_H + +#include +#include +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +enum { + CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_OPEN_SESSION = 0, + CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CLOSE_SESSION, + CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_CONFIGURE_STREAMS, + CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_RELEASE_STREAMS, + CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_START_CAPTURE, + CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_STOP_CAPTURE, + CMD_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_UPDATE_SETTINGS, +}; + +class IDCameraProviderCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"HDI.DCamera.V1_0.ProviderCallback"); + virtual ~IDCameraProviderCallback() {} + +public: + /** + * @brief Create the transmission channel between the source device and the sink device. + * Open and initialize the distributed camera session. + * + * @param dhBase [in] Distributed hardware device base info + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode OpenSession(const std::shared_ptr &dhBase) = 0; + + /** + * @brief Close the distributed camera session, and destroy the transmission channel between + * the source device and the sink device. + * + * @param dhBase [in] Distributed hardware device base info + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode CloseSession(const std::shared_ptr &dhBase) = 0; + + /** + * @brief Configures streams. + * + * @param dhBase [in] Distributed hardware device base info + * + * @param streamInfos [in] Indicates the list of stream information, which is defined by {@link DCStreamInfo}. + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode ConfigureStreams(const std::shared_ptr &dhBase, + const std::vector> &streamInfos) = 0; + + /** + * @brief Releases streams. + * + * @param dhBase [in] Distributed hardware device base info + * + * @param streamIds [IN] Indicates the IDs of the streams to release. + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode ReleaseStreams(const std::shared_ptr &dhBase, const std::vector &streamIds) = 0; + + /** + * @brief Start capture images. + * This function must be called after {@link ConfigStreams}. + * There are two image capture modes: continuous capture and single capture. + * + * @param dhBase [in] Distributed hardware device base info + * + * @param captureInfos [in] Indicates the capture request configuration information. + * For details, see {@link DCCaptureInfo}. + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode StartCapture(const std::shared_ptr &dhBase, + const std::vector> &captureInfos) = 0; + + /** + * @brief Stop capture images. + * + * @param dhBase [in] Distributed hardware device base info + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode StopCapture(const std::shared_ptr &dhBase) = 0; + + /** + * @brief Updates distributed camera device control parameters. + * + * @param dhBase [in] Distributed hardware device base info + * + * @param settings [in] Indicates the camera parameters, including the sensor frame rate and 3A parameters. + * For details about the settings, see {@link DCameraSettings}. + * + * @return Returns NO_ERROR if the operation is successful, + * returns an error code defined in {@link DCamRetCode} otherwise. + * + * @since 1.0 + * @version 1.0 + */ + virtual DCamRetCode UpdateSettings(const std::shared_ptr &dhBase, + const std::vector> &settings) = 0; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +#endif // HDI_DISTRIBUTED_CAMERA_PROVIDER_CALLBACK_H \ No newline at end of file diff --git a/camera_hdf/interfaces/include/types.h b/camera_hdf/interfaces/include/types.h new file mode 100644 index 0000000000000000000000000000000000000000..d49e2d955dfaefbc562f91c35da77c281f080823 --- /dev/null +++ b/camera_hdf/interfaces/include/types.h @@ -0,0 +1,307 @@ +/* + * 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. + */ + +/** + * @file types.h + * + * @brief Declares data types used by the Hardware Driver Interfaces (HDIs) of this module. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef DISTRIBUTED_CAMERA_PROVIDER_TYPES_H +#define DISTRIBUTED_CAMERA_PROVIDER_TYPES_H + +#include +#include +#include "buffer_handle.h" + +namespace OHOS { +namespace DistributedHardware { +/** + * @brief Enumerates distributed camera metadata updating types. + */ +using DCSettingsType = enum _DCSettingsType : int32_t { + /** + * Set the whole package metadata. + */ + UPDATE_METADATA = 0, + /** + * Enable metadata. + */ + ENABLE_METADATA = 1, + /** + * Disable metadata. + */ + DISABLE_METADATA = 2, + /** + * Metadata result. + */ + METADATA_RESULT = 3, + /** + * Set flash light. + */ + SET_FLASH_LIGHT = 4, + /** + * Set fps range. + */ + FPS_RANGE = 5 +}; + +/** + * @brief Enumerates return values of the HDIs. + */ +using DCamRetCode = enum _DCamRetCode : int32_t { + /** + * Successful call. + */ + SUCCESS = 0, + /** + * The camera device is busy. + */ + CAMERA_BUSY = 1, + /** + * Invalid parameters. + */ + INVALID_ARGUMENT = 2, + /** + * Unsupported function. + */ + METHOD_NOT_SUPPORTED = 3, + /** + * The camera device is offlined. + */ + CAMERA_OFFLINE = 4, + /** + * The number of distributed camera devices enabled exceeds the limit. + */ + EXCEED_MAX_NUMBER = 5, + /** + * The device is not initialized. + */ + DEVICE_NOT_INIT = 6, + /** + * Failed call. + */ + FAILED = -1, +}; + + /** + * @brief Enumerates encoding types of stream data. + */ +using DCEncodeType = enum _DCEncodeType : int32_t { + /** + * Unspecified + */ + ENCODE_TYPE_NULL = 0, + + /** + * H.264 + */ + ENCODE_TYPE_H264 = 1, + + /** + * H.265 + */ + ENCODE_TYPE_H265 = 2, + + /** + * JPEG + */ + ENCODE_TYPE_JPEG = 3, +}; + +/** + * @brief Enumerates distributed camera inner stream types. + */ +using DCStreamType = enum _DCStreamType : int32_t { + /** + * Continuous capture stream. For example preview streams, video streams. + */ + CONTINUOUS_FRAME = 0, + /** + * Single capture stream. For example photographing streams. + */ + SNAPSHOT_FRAME = 1 +}; + +/** + * @brief Distributed hardware device base info. + */ +using DHBase = struct _DHBase { + /** + * The device id. + */ + std::string deviceId_; + /** + * The distributed hardware id. + */ + std::string dhId_; + + _DHBase() : deviceId_(""), dhId_("") {} + + _DHBase(const std::string &deviceId, const std::string &dhId) : deviceId_(deviceId), dhId_(dhId) {} + + bool operator ==(const _DHBase& others) const + { + return this->deviceId_ == others.deviceId_ && this->dhId_ == others.dhId_; + } + + bool operator < (const _DHBase& others) const + { + return (this->deviceId_ + this->dhId_) < (others.deviceId_ + others.dhId_); + } +}; + +/** + * @brief The control settings of the distributed camera device. + */ +using DCameraSettings = struct _DCameraSettings { + /** + * Settings type. + */ + DCSettingsType type_; + /** + * Settings value. Serialized from bool, array, structure, etc. + */ + std::string value_; +}; + +/** + * @brief Defines the inner stream information of the distributed camera, + * which is used to pass configuration parameters during stream creation. + */ +using DCStreamInfo = struct _DCStreamInfo { + /** + * Stream ID, which uniquely identifies a stream on a camera device. + */ + int streamId_; + /** + * Image width. + */ + int width_; + /** + * Image height. + */ + int height_; + /** + * Image stride. + */ + int stride_; + /** + * Image format. + */ + int format_; + /** + * Image color space. + */ + int dataspace_; + /** + * Encoding type. + */ + DCEncodeType encodeType_; + /** + * Stream type. + */ + DCStreamType type_; +}; + +/** + * @brief Defines the information about a inner capture request of the distributed camera. + */ +using DCCaptureInfo = struct _DCCaptureInfo { + /** + * IDs of captured streams. + */ + std::vector streamIds_; + /** + * Image width. + */ + int width_; + /** + * Image height. + */ + int height_; + /** + * Image stride. + */ + int stride_; + /** + * Image format. + */ + int format_; + /** + * Image color space. + */ + int dataspace_; + /** + * Capture Info + */ + bool isCapture_; + /** + * Encoding type. + */ + DCEncodeType encodeType_; + /** + * Stream type. + */ + DCStreamType type_; + /** + * Stream settings. + */ + std::vector> captureSettings_; +}; + +/** + * @brief Defines the inner buffer of the distributed camera, + * which is used to acquire buffer during procesing capture requests. + */ +using DCameraBuffer = struct _DCameraBuffer { + /** + * Buffer index. + */ + int32_t index_; + /** + * Buffer size. + */ + uint32_t size_; + /** + * Buffer handle. + */ + BufferHandle* bufferHandle_; +}; + +/** + * @brief Notification event of the distributed camera. + */ +using DCameraHDFEvent = struct _DCameraHDFEvent { + /** + * Event type. + */ + int32_t type_; + /** + * Event result. + */ + int32_t result_; + /** + * Extended content (optional). + */ + std::string content_; +}; +} // end namespace DistributedHardware +} // end namespace OHOS + +#endif // DISTRIBUTED_CAMERA_PROVIDER_TYPES_H \ No newline at end of file diff --git a/common/BUILD.gn b/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b8bb86a670cdbbe435f04c0cf9fdb659cb109d61 --- /dev/null +++ b/common/BUILD.gn @@ -0,0 +1,56 @@ +# 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. + +import("//build/ohos.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_utils") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include/", + "${fwk_utils_path}/include", + "${fwk_utils_path}/include/log", + ] + + include_dirs += [ + "include/constants", + "include/utils", + ] + + sources = [ + "src/utils/data_buffer.cpp", + "src/utils/dcamera_utils_tools.cpp", + ] + + deps = [ + "//utils/native/base:utils", + "${fwk_utils_path}:distributedhardwareutils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"distributedcamerautils\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "dsoftbus_standard:softbus_client", + "hiviewdfx_hilog_native:libhilog", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} diff --git a/common/include/constants/distributed_camera_constants.h b/common/include/constants/distributed_camera_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..bc1225101793a9cd30bd6d61bd5d24ea4eb4bd50 --- /dev/null +++ b/common/include/constants/distributed_camera_constants.h @@ -0,0 +1,117 @@ +/* + * 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_DISTRIBUTED_CAMERA_CONSTANTS_H +#define OHOS_DISTRIBUTED_CAMERA_CONSTANTS_H + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DCAMERA_SRV_STATE_NOT_START, + DCAMERA_SRV_STATE_RUNNING +} DCameraServiceState; + +typedef enum { + DCAMERA_AUTHORIZATION_DEFAULT = 0, + DCAMERA_AUTHORIZATION_AGREE = 1, + DCAMERA_AUTHORIZATION_REJECT = 2, + DCAMERA_AUTHORIZATION_TIMEOUT = 3, +} AuthorizationState; + +typedef enum { + DCAMERA_SAME_ACCOUNT = 0, + DCAMERA_DIFF_ACCOUNT = 1, + DCAMERA_NO_ACCOUNT = 2, +} AccessControlType; + +typedef enum { + DCAMERA_MESSAGE = 0, + DCAMERA_OPERATION = 1, +} DCameraEventType; + +typedef enum { + DCAMERA_EVENT_CHANNEL_DISCONNECTED = 0, + DCAMERA_EVENT_CHANNEL_CONNECTED = 1, + DCAMERA_EVENT_CAMERA_SUCCESS = 2, + + DCAMERA_EVENT_CAMERA_ERROR = -1, + DCAMERA_EVENT_OPEN_CHANNEL_ERROR = -2, + DCAMERA_EVENT_CLOSE_CHANNEL_ERROR = -3, + DCAMERA_EVENT_CONFIG_STREAMS_ERROR = -4, + DCAMERA_EVENT_RELEASE_STREAMS_ERROR = -5, + DCAMERA_EVENT_START_CAPTURE_ERROR = -6, + DCAMERA_EVENT_STOP_CAPTURE_ERROR = -7, + DCAMERA_EVENT_UPDATE_SETTINGS_ERROR = -8, +} DCameraEventResult; + +typedef enum { + OHOS_CAMERA_FORMAT_INVALID = 0, + OHOS_CAMERA_FORMAT_RGBA_8888, + OHOS_CAMERA_FORMAT_YCBCR_420_888, + OHOS_CAMERA_FORMAT_YCRCB_420_SP, + OHOS_CAMERA_FORMAT_JPEG, +} DCameraFormat; + +const uint32_t DCAMERA_MAX_NUM = 1; +const uint32_t DCAMERA_PRODUCER_ONE_MINUTE_MS = 1000; +const uint32_t DCAMERA_PRODUCER_FPS_DEFAULT = 30; +const uint32_t DCAMERA_MAX_RECV_DATA_LEN = 104857600; +const uint32_t DISTRIBUTED_HARDWARE_CAMERA_SOURCE_SA_ID = 4803; +const uint32_t DISTRIBUTED_HARDWARE_CAMERA_SINK_SA_ID = 4804; +const std::string DCAMERA_PKG_NAME = "DBinderBus_" + std::to_string(getpid()); +const std::string SNAP_SHOT_SESSION_FLAG = "dataSnapshot"; +const std::string CONTINUE_SESSION_FLAG = "dataContinue"; + +const std::string DISTRIBUTED_HARDWARE_ID_KEY = "dhID"; +const std::string CAMERA_ID_PREFIX = "Camera_"; +const std::string CAMERA_PROTOCOL_VERSION_KEY = "ProtocolVer"; +const std::string CAMERA_PROTOCOL_VERSION_VALUE = "1.0"; +const std::string CAMERA_POSITION_KEY = "Position"; +const std::string CAMERA_POSITION_BACK = "BACK"; +const std::string CAMERA_POSITION_FRONT = "FRONT"; +const std::string CAMERA_POSITION_UNSPECIFIED = "UNSPECIFIED"; +const std::string CAMERA_METADATA_KEY = "MetaData"; +const std::string CAMERA_CODEC_TYPE_KEY = "CodecType"; +const std::string CAMERA_FORMAT_KEY = "OutputFormat"; +const std::string CAMERA_FORMAT_PREVIEW = "Preview"; +const std::string CAMERA_FORMAT_VIDEO = "Video"; +const std::string CAMERA_FORMAT_PHOTO = "Photo"; +const std::string CAMERA_RESOLUTION_KEY = "Resolution"; +const std::string CAMERA_SURFACE_FORMAT = "CAMERA_SURFACE_FORMAT"; + +const int32_t RESOLUTION_MAX_WIDTH_SNAPSHOT = 4096; +const int32_t RESOLUTION_MAX_HEIGHT_SNAPSHOT = 3072; +const int32_t RESOLUTION_MAX_WIDTH_CONTINUOUS = 1920; +const int32_t RESOLUTION_MAX_HEIGHT_CONTINUOUS = 1080; +const int32_t RESOLUTION_MIN_WIDTH = 320; +const int32_t RESOLUTION_MIN_HEIGHT = 240; + +const uint32_t DCAMERA_SHIFT_32 = 32; +const uint32_t DCAMERA_SHIFT_24 = 24; +const uint32_t DCAMERA_SHIFT_16 = 16; +const uint32_t DCAMERA_SHIFT_8 = 8; + +const uint32_t UINT32_SHIFT_MASK_24 = 0xff000000; +const uint32_t UINT32_SHIFT_MASK_16 = 0x00ff0000; +const uint32_t UINT32_SHIFT_MASK_8 = 0x0000ff00; +const uint32_t UINT32_SHIFT_MASK_0 = 0x000000ff; +const uint16_t UINT16_SHIFT_MASK_0 = 0x00ff; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_CAMERA_CONSTANTS_H \ No newline at end of file diff --git a/common/include/constants/distributed_camera_errno.h b/common/include/constants/distributed_camera_errno.h new file mode 100644 index 0000000000000000000000000000000000000000..0a1f7e99d39929a8209fe2e3780cc1cbf13e4509 --- /dev/null +++ b/common/include/constants/distributed_camera_errno.h @@ -0,0 +1,39 @@ +/* + * 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_DISTRIBUTED_CAMERA_ERRNO_H +#define OHOS_DISTRIBUTED_CAMERA_ERRNO_H + +namespace OHOS { +namespace DistributedHardware { + enum DistributedCameraErrno { + DCAMERA_OK = 0, + DCAMERA_MEMORY_OPT_ERROR = -1, + DCAMERA_BAD_VALUE = -2, + DCAMERA_BAD_TYPE = -3, + DCAMERA_ALREADY_EXISTS = -4, + DCAMERA_INIT_ERR = -5, + DCAMERA_NOT_FOUND = -6, + DCAMERA_WRONG_STATE = -7, + DCAMERA_BAD_OPERATE = -8, + DCAMERA_OPEN_CONFLICT = -9, + DCAMERA_DISABLE_PROCESS = -10, + DCAMERA_INDEX_OVERFLOW = -11, + DCAMERA_REGIST_HAL_FAILED = -12, + DCAMERA_UNREGIST_HAL_FAILED = -13, + }; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_CAMERA_ERRNO_H \ No newline at end of file diff --git a/common/include/utils/data_buffer.h b/common/include/utils/data_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..3c35a462cbcc4af7f7b193bf97a9794b51868166 --- /dev/null +++ b/common/include/utils/data_buffer.h @@ -0,0 +1,60 @@ +/* + * 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_DATA_BUFFER_H +#define OHOS_DATA_BUFFER_H + +#include +#include + +using std::string; +using std::map; + +namespace OHOS { +namespace DistributedHardware { +class DataBuffer { +public: + DataBuffer(size_t capacity); + + size_t Size() const; + size_t Offset() const; + size_t Capacity() const; + uint8_t *Data() const; + int32_t SetRange(size_t offset, size_t size); + + void SetInt32(const string name, int32_t value); + void SetInt64(const string name, int64_t value); + void SetString(const string name, string value); + bool FindInt32(const string& name, int32_t& value); + bool FindInt64(const string& name, int64_t& value); + bool FindString(const string& name, string& value); + + virtual ~DataBuffer(); +private: + size_t capacity_ = 0; + size_t rangeOffset_ = 0; + size_t rangeLength_ = 0; + uint8_t *data_ = nullptr; + + map int32Map_; + map int64Map_; + map stringMap_; + + DataBuffer(const DataBuffer &) = delete; + DataBuffer &operator = (const DataBuffer &) = delete; +}; +} +} +#endif \ No newline at end of file diff --git a/common/include/utils/dcamera_index.h b/common/include/utils/dcamera_index.h new file mode 100644 index 0000000000000000000000000000000000000000..d9c69cebd4b341aca4b130353b105c79528eb81d --- /dev/null +++ b/common/include/utils/dcamera_index.h @@ -0,0 +1,43 @@ +/* + * 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_DCAMERA_INDEX_H +#define OHOS_DCAMERA_INDEX_H + +#include + +namespace OHOS { +namespace DistributedHardware { +class DCameraIndex { +public: + DCameraIndex() = default; + explicit DCameraIndex(std::string devId, std::string dhId) : devId_(devId), dhId_(dhId) {} + ~DCameraIndex() = default; + + bool operator == (const DCameraIndex& index) const + { + return this->devId_ == index.devId_ && this->dhId_ == index.dhId_; + } + + bool operator < (const DCameraIndex& index) const + { + return (this->devId_ + this->dhId_) < (index.devId_ + index.dhId_); + } + + std::string devId_; + std::string dhId_; +}; +} +} +#endif \ No newline at end of file diff --git a/common/include/utils/dcamera_utils_tools.h b/common/include/utils/dcamera_utils_tools.h new file mode 100644 index 0000000000000000000000000000000000000000..4068f4e1c0bd8861714be2eb64980ccf8676dd57 --- /dev/null +++ b/common/include/utils/dcamera_utils_tools.h @@ -0,0 +1,35 @@ +/* + * 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_DCAMERA_UTILS_TOOL_H +#define OHOS_DCAMERA_UTILS_TOOL_H + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +const std::string BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +int32_t GetLocalDeviceNetworkId(std::string& networkId); +int64_t GetNowTimeStampMs(); +int64_t GetNowTimeStampUs(); +std::string Base64Encode(const unsigned char *toEncode, unsigned int len); +std::string Base64Decode(const std::string& basicString); +bool IsBase64(unsigned char c); +} +} +#endif \ No newline at end of file diff --git a/common/src/utils/data_buffer.cpp b/common/src/utils/data_buffer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e4ae71f05fcabdcb02fae8a4a490b5921baddda --- /dev/null +++ b/common/src/utils/data_buffer.cpp @@ -0,0 +1,119 @@ +/* + * 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 "data_buffer.h" +#include "distributed_camera_errno.h" + +namespace OHOS { +namespace DistributedHardware { +DataBuffer::DataBuffer(size_t capacity) +{ + if (capacity != 0) { + data_ = new uint8_t[capacity] {0}; + if (data_ != nullptr) { + capacity_ = capacity; + rangeLength_ = capacity; + } + } +} + +size_t DataBuffer::Capacity() const +{ + return capacity_; +} + +size_t DataBuffer::Size() const +{ + return rangeLength_; +} + +size_t DataBuffer::Offset() const +{ + return rangeOffset_; +} + +uint8_t *DataBuffer::Data() const +{ + return data_ + rangeOffset_; +} + +int32_t DataBuffer::SetRange(size_t offset, size_t size) +{ + if (!(offset <= capacity_) || !(offset + size <= capacity_)) { + return DCAMERA_BAD_VALUE; + } + + rangeOffset_ = offset; + rangeLength_ = size; + return DCAMERA_OK; +} + +void DataBuffer::SetInt32(const string name, int32_t value) +{ + int32Map_[name] = value; +} + +void DataBuffer::SetInt64(const string name, int64_t value) +{ + int64Map_[name] = value; +} + +void DataBuffer::SetString(const string name, string value) +{ + stringMap_[name] = value; +} + +bool DataBuffer::FindInt32(const string& name, int32_t& value) +{ + if (int32Map_.count(name) != 0) { + value = int32Map_[name]; + return true; + } else { + value = 0; + return false; + } +} + +bool DataBuffer::FindInt64(const string& name, int64_t& value) +{ + if (int64Map_.count(name) != 0) { + value = int64Map_[name]; + return true; + } else { + value = 0; + return false; + } +} + +bool DataBuffer::FindString(const string& name, string& value) +{ + if (stringMap_.count(name) != 0) { + value = stringMap_[name]; + return true; + } else { + value = ""; + return false; + } +} + +DataBuffer::~DataBuffer() +{ + if (data_ != nullptr) { + delete[] data_; + data_ = nullptr; + } +} +} +} \ No newline at end of file diff --git a/common/src/utils/dcamera_utils_tools.cpp b/common/src/utils/dcamera_utils_tools.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62513dcf0a160702cc48ab9d912846cb6530dd1b --- /dev/null +++ b/common/src/utils/dcamera_utils_tools.cpp @@ -0,0 +1,157 @@ +/* + * 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 "dcamera_utils_tools.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +#include "softbus_bus_center.h" + +namespace OHOS { +namespace DistributedHardware { +const int OFFSET2 = 2; +const int OFFSET4 = 4; +const int OFFSET6 = 6; +const int INDEX_FIRST = 0; +const int INDEX_SECOND = 1; +const int INDEX_THIRD = 2; +const int INDEX_FORTH = 3; +int32_t GetLocalDeviceNetworkId(std::string& networkId) +{ + NodeBasicInfo basicInfo = { { 0 } }; + int32_t ret = GetLocalNodeDeviceInfo(DCAMERA_PKG_NAME.c_str(), &basicInfo); + if (ret != DCAMERA_OK) { + DHLOGE("GetLocalDeviceNetworkId GetLocalNodeDeviceInfo failed ret: %d", ret); + return ret; + } + + networkId = std::string(basicInfo.networkId); + return DCAMERA_OK; +} + +int64_t GetNowTimeStampMs() +{ + std::chrono::milliseconds nowMs = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()); + return nowMs.count(); +} + +int64_t GetNowTimeStampUs() +{ + std::chrono::microseconds nowUs = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()); + return nowUs.count(); +} + +std::string Base64Encode(const unsigned char *toEncode, unsigned int len) +{ + std::string ret; + uint32_t i = 0; + unsigned char charArray3[3]; + unsigned char charArray4[4]; + + while (len--) { + charArray3[i++] = *(toEncode++); + if (i == sizeof(charArray3)) { + charArray4[INDEX_FIRST] = (charArray3[INDEX_FIRST] & 0xfc) >> OFFSET2; + charArray4[INDEX_SECOND] = ((charArray3[INDEX_FIRST] & 0x03) << OFFSET4) + + ((charArray3[INDEX_SECOND] & 0xf0) >> OFFSET4); + charArray4[INDEX_THIRD] = ((charArray3[INDEX_SECOND] & 0x0f) << OFFSET2) + + ((charArray3[INDEX_THIRD] & 0xc0) >> OFFSET6); + charArray4[INDEX_FORTH] = charArray3[INDEX_THIRD] & 0x3f; + for (i = 0; i < sizeof(charArray4); i++) { + ret += BASE_64_CHARS[charArray4[i]]; + } + i = 0; + } + } + + if (i) { + uint32_t j = 0; + for (j = i; j < sizeof(charArray3); j++) { + charArray3[j] = '\0'; + } + charArray4[INDEX_FIRST] = (charArray3[INDEX_FIRST] & 0xfc) >> OFFSET2; + charArray4[INDEX_SECOND] = ((charArray3[INDEX_FIRST] & 0x03) << OFFSET4) + + ((charArray3[INDEX_SECOND] & 0xf0) >> OFFSET4); + charArray4[INDEX_THIRD] = ((charArray3[INDEX_SECOND] & 0x0f) << OFFSET2) + + ((charArray3[INDEX_THIRD] & 0xc0) >> OFFSET6); + charArray4[INDEX_FORTH] = charArray3[INDEX_THIRD] & 0x3f; + for (j = 0; j < i + 1; j++) { + ret += BASE_64_CHARS[charArray4[j]]; + } + while (i++ < sizeof(charArray3)) { + ret += '='; + } + } + return ret; +} + +std::string Base64Decode(const std::string& basicString) +{ + std::string ret; + uint32_t i = 0; + int index = 0; + int len = static_cast(basicString.size()); + unsigned char charArray3[3]; + unsigned char charArray4[4]; + + while (len-- && (basicString[index] != '=') && IsBase64(basicString[index])) { + charArray4[i++] = basicString[index]; + index++; + if (i == sizeof(charArray4)) { + for (i = 0; i < sizeof(charArray4); i++) { + charArray4[i] = BASE_64_CHARS.find(charArray4[i]); + } + charArray3[INDEX_FIRST] = (charArray4[INDEX_FIRST] << OFFSET2) + + ((charArray4[INDEX_SECOND] & 0x30) >> OFFSET4); + charArray3[INDEX_SECOND] = ((charArray4[INDEX_SECOND] & 0xf) << OFFSET4) + + ((charArray4[INDEX_THIRD] & 0x3c) >> OFFSET2); + charArray3[INDEX_THIRD] = ((charArray4[INDEX_THIRD] & 0x3) << OFFSET6) + charArray4[INDEX_FORTH]; + for (i = 0; i < sizeof(charArray3); i++) { + ret += charArray3[i]; + } + i = 0; + } + } + + if (i) { + uint32_t j = 0; + for (j = i; j < sizeof(charArray4); j++) { + charArray4[j] = 0; + } + for (j = 0; j < sizeof(charArray4); j++) { + charArray4[j] = BASE_64_CHARS.find(charArray4[j]); + } + charArray3[INDEX_FIRST] = (charArray4[INDEX_FIRST] << OFFSET2) + + ((charArray4[INDEX_SECOND] & 0x30) >> OFFSET4); + charArray3[INDEX_SECOND] = ((charArray4[INDEX_SECOND] & 0xf) << OFFSET4) + + ((charArray4[INDEX_THIRD] & 0x3c) >> OFFSET2); + charArray3[INDEX_THIRD] = ((charArray4[INDEX_THIRD] & 0x3) << OFFSET6) + charArray4[INDEX_FORTH]; + for (j = 0; j < i - 1; j++) { + ret += charArray3[j]; + } + } + return ret; +} + +bool IsBase64(unsigned char c) +{ + return (isalnum(c) || (c == '+') || (c == '/')); +} +} +} \ No newline at end of file diff --git a/distributedcamera.gni b/distributedcamera.gni new file mode 100644 index 0000000000000000000000000000000000000000..8207be526f332bd3979d7fe5bf67a9282b71e7c4 --- /dev/null +++ b/distributedcamera.gni @@ -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. + +distributedcamera_path = "//foundation/distributedhardware/distributedcamera" + +distributedhardwarefwk_path = "//foundation/distributedhardware/distributedhardwarefwk" + +hdf_framework_path = "//drivers/framework" + +camera_hdf_path = "//drivers/peripheral/adapter" + +display_hdf_path = "//drivers/peripheral/display" + +camerastandard_path = "//foundation/multimedia/camera_standard" + +mediastandard_path = "//foundation/multimedia/media_standard" + +graphicstandard_path = "//foundation/graphic/standard" + +common_path = "${distributedcamera_path}/common" + +services_path = "${distributedcamera_path}/services" + +innerkits_path = "${distributedcamera_path}/interfaces/inner_kits" + +distributedcamera_hdf_path = "${distributedcamera_path}/camera_hdf" + +fwk_utils_path = "${distributedhardwarefwk_path}/utils" + +fwk_common_path = "${distributedhardwarefwk_path}/common" + +fwk_services_path = "${distributedhardwarefwk_path}/services" + +build_flags = [ "-Werror" ] diff --git a/figures/distributedcamera_arch.png b/figures/distributedcamera_arch.png new file mode 100644 index 0000000000000000000000000000000000000000..ed769ce56875747c86851dd4157fd82745eb8f26 Binary files /dev/null and b/figures/distributedcamera_arch.png differ diff --git a/interfaces/inner_kits/native_cpp/camera_sink/BUILD.gn b/interfaces/inner_kits/native_cpp/camera_sink/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8c8d618cf2eba5b354e07219be2154e452fd9c6d --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_sink/BUILD.gn @@ -0,0 +1,60 @@ +# 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. + +import("//build/ohos.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_sink_sdk") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + ] + + include_dirs += [ + "include", + "${common_path}/include/constants", + ] + + sources = [ + "src/dcamera_sink_handler_ipc.cpp", + "src/dcamera_sink_handler.cpp", + "src/distributed_camera_sink_proxy.cpp", + ] + + deps = [ + "//utils/native/base:utils", + "${fwk_utils_path}:distributedhardwareutils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dcamerasinkkits\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} + diff --git a/interfaces/inner_kits/native_cpp/camera_sink/include/dcamera_sink_handler.h b/interfaces/inner_kits/native_cpp/camera_sink/include/dcamera_sink_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..52b95b6e03c6ee35496fb1c81d7ae8908a973d86 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_sink/include/dcamera_sink_handler.h @@ -0,0 +1,46 @@ +/* + * 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_DCAMERA_SINK_HANDLER_H +#define OHOS_DCAMERA_SINK_HANDLER_H + +#include "idistributed_hardware_sink.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkHandler : public IDistributedHardwareSink { +DECLARE_SINGLE_INSTANCE_BASE(DCameraSinkHandler); +public: + int32_t InitSink(const std::string& params) override; + int32_t ReleaseSink() override; + int32_t SubscribeLocalHardware(const std::string& dhId, const std::string& parameters) override; + int32_t UnsubscribeLocalHardware(const std::string& dhId) override; + +private: + DCameraSinkHandler() = default; + ~DCameraSinkHandler(); +}; + +#ifdef __cplusplus +extern "C" { +#endif +__attribute__((visibility("default"))) IDistributedHardwareSink *GetSinkHardwareHandler(); +#ifdef __cplusplus +} +#endif +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_HANDLER_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_sink/include/dcamera_sink_handler_ipc.h b/interfaces/inner_kits/native_cpp/camera_sink/include/dcamera_sink_handler_ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..38593c516234248efd1d2d6e90459de2d6f95b35 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_sink/include/dcamera_sink_handler_ipc.h @@ -0,0 +1,53 @@ +/* + * 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_DCAMERA_SINK_HANDLER_IPC_H +#define OHOS_DCAMERA_SINK_HANDLER_IPC_H + +#include "event_handler.h" +#include "idistributed_camera_sink.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkHandlerIpc { +DECLARE_SINGLE_INSTANCE_BASE(DCameraSinkHandlerIpc); +public: + void Init(); + void UnInit(); + sptr GetSinkLocalDHMS(); + void OnSinkLocalDmsDied(const wptr& remote); + +private: + DCameraSinkHandlerIpc(); + ~DCameraSinkHandlerIpc(); + void OnSinkLocalDmsDied(const sptr& remote); + void DeleteSinkLocalDhms(); + + class SinkLocalRecipient : public IRemoteObject::DeathRecipient { + public: + void OnRemoteDied(const wptr& remote) override; + }; + sptr sinkLocalRecipient_; + sptr localSink_; + std::mutex sinkLocalDmsLock_; + + bool isInit_; + std::shared_ptr serviceHandler_; + std::mutex initDmsLock_; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_sink/include/distributed_camera_sink_proxy.h b/interfaces/inner_kits/native_cpp/camera_sink/include/distributed_camera_sink_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..c987e71b24f5e7e6055401ece9b2bd46df7a9c41 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_sink/include/distributed_camera_sink_proxy.h @@ -0,0 +1,50 @@ +/* + * 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_DISTRIBUTED_CAMERA_SINK_PROXY_H +#define OHOS_DISTRIBUTED_CAMERA_SINK_PROXY_H + +#include "idistributed_camera_sink.h" + +#include "iremote_broker.h" +#include "iremote_proxy.h" +#include "refbase.h" + +namespace OHOS { +namespace DistributedHardware { +class DistributedCameraSinkProxy : public IRemoteProxy { +public: + explicit DistributedCameraSinkProxy(const sptr& impl) + : IRemoteProxy(impl) + { + } + + ~DistributedCameraSinkProxy() {} + int32_t InitSink(const std::string& params) override; + int32_t ReleaseSink() override; + int32_t SubscribeLocalHardware(const std::string& dhId, const std::string& parameters) override; + int32_t UnsubscribeLocalHardware(const std::string& dhId) override; + int32_t StopCapture(const std::string& dhId) override; + int32_t ChannelNeg(const std::string& dhId, std::string& channelInfo) override; + int32_t GetCameraInfo(const std::string& dhId, std::string& cameraInfo) override; + int32_t OpenChannel(const std::string& dhId, std::string& openInfo) override; + int32_t CloseChannel(const std::string& dhId) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_CAMERA_SINK_PROXY_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_sink/include/idistributed_camera_sink.h b/interfaces/inner_kits/native_cpp/camera_sink/include/idistributed_camera_sink.h new file mode 100644 index 0000000000000000000000000000000000000000..c3613201cb7e4ca241b03baf0a671140ca7141e2 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_sink/include/idistributed_camera_sink.h @@ -0,0 +1,52 @@ +/* + * 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_IDISTRIBUTED_CAMERA_SINK_H +#define OHOS_IDISTRIBUTED_CAMERA_SINK_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace DistributedHardware { +class IDistributedCameraSink : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.distributedcamerasink"); + enum { + INIT_SINK = 0, + RELEASE_SINK = 1, + SUBSCRIBE_LOCAL_HARDWARE = 2, + UNSUBSCRIBE_LOCAL_HARDWARE = 3, + STOP_CAPTURE = 4, + CHANNEL_NEG = 5, + GET_CAMERA_INFO = 6, + OPEN_CHANNEL = 7, + CLOSE_CHANNEL = 8, + }; + + IDistributedCameraSink() = default; + virtual ~IDistributedCameraSink() = default; + virtual int32_t InitSink(const std::string& params) = 0; + virtual int32_t ReleaseSink() = 0; + virtual int32_t SubscribeLocalHardware(const std::string& dhId, const std::string& parameters) = 0; + virtual int32_t UnsubscribeLocalHardware(const std::string& dhId) = 0; + virtual int32_t StopCapture(const std::string& dhId) = 0; + virtual int32_t ChannelNeg(const std::string& dhId, std::string& channelInfo) = 0; + virtual int32_t GetCameraInfo(const std::string& dhId, std::string& cameraInfo) = 0; + virtual int32_t OpenChannel(const std::string& dhId, std::string& openInfo) = 0; + virtual int32_t CloseChannel(const std::string& dhId) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_IDISTRIBUTED_CAMERA_SINK_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_sink/src/dcamera_sink_handler.cpp b/interfaces/inner_kits/native_cpp/camera_sink/src/dcamera_sink_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4ddea60ad9c114a60943524ae7e497171acd681f --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_sink/src/dcamera_sink_handler.cpp @@ -0,0 +1,92 @@ +/* + * 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 "dcamera_sink_handler.h" + +#include "anonymous_string.h" +#include "dcamera_sink_handler_ipc.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DCameraSinkHandler); + +DCameraSinkHandler::~DCameraSinkHandler() +{ + DHLOGI("~DCameraSinkHandler"); +} + +int32_t DCameraSinkHandler::InitSink(const std::string& params) +{ + DHLOGI("DCameraSinkHandler::InitSink"); + DCameraSinkHandlerIpc::GetInstance().Init(); + sptr dCameraSinkSrv = DCameraSinkHandlerIpc::GetInstance().GetSinkLocalDHMS(); + if (dCameraSinkSrv == nullptr) { + DHLOGE("DCameraSinkHandler::InitSink get Service failed"); + return DCAMERA_INIT_ERR; + } + return dCameraSinkSrv->InitSink(params); +} + +int32_t DCameraSinkHandler::ReleaseSink() +{ + DHLOGI("DCameraSinkHandler::ReleaseSink"); + sptr dCameraSinkSrv = DCameraSinkHandlerIpc::GetInstance().GetSinkLocalDHMS(); + if (dCameraSinkSrv == nullptr) { + DHLOGE("DCameraSinkHandler::ReleaseSink get Service failed"); + return DCAMERA_BAD_VALUE; + } + + int32_t ret = dCameraSinkSrv->ReleaseSink(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkHandler::ReleaseSink sink service release failed, ret: %d", ret); + return ret; + } + + DCameraSinkHandlerIpc::GetInstance().UnInit(); + DHLOGI("DCameraSinkHandler::ReleaseSink success"); + return DCAMERA_OK; +} + +int32_t DCameraSinkHandler::SubscribeLocalHardware(const std::string& dhId, const std::string& parameters) +{ + DHLOGI("DCameraSinkHandler::SubscribeLocalHardware dhId: %s", GetAnonyString(dhId).c_str()); + sptr dCameraSinkSrv = DCameraSinkHandlerIpc::GetInstance().GetSinkLocalDHMS(); + if (dCameraSinkSrv == nullptr) { + DHLOGE("DCameraSinkHandler::SubscribeLocalHardware get Service failed"); + return DCAMERA_BAD_VALUE; + } + return dCameraSinkSrv->SubscribeLocalHardware(dhId, parameters); +} + +int32_t DCameraSinkHandler::UnsubscribeLocalHardware(const std::string& dhId) +{ + DHLOGI("DCameraSinkHandler::UnsubscribeLocalHardware dhId: %s", GetAnonyString(dhId).c_str()); + sptr dCameraSinkSrv = DCameraSinkHandlerIpc::GetInstance().GetSinkLocalDHMS(); + if (dCameraSinkSrv == nullptr) { + DHLOGE("DCameraSinkHandler::UnsubscribeLocalHardware get Service failed"); + return DCAMERA_BAD_VALUE; + } + return dCameraSinkSrv->UnsubscribeLocalHardware(dhId); +} + +IDistributedHardwareSink *GetSinkHardwareHandler() +{ + DHLOGI("DCameraSinkHandler::GetSinkHardwareHandler"); + return &DCameraSinkHandler::GetInstance(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_sink/src/dcamera_sink_handler_ipc.cpp b/interfaces/inner_kits/native_cpp/camera_sink/src/dcamera_sink_handler_ipc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..77a1888bb20565b1a2a270e197d929cd2be98112 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_sink/src/dcamera_sink_handler_ipc.cpp @@ -0,0 +1,159 @@ +/* + * 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 "dcamera_sink_handler_ipc.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkHandlerIpc::DCameraSinkHandlerIpc() : isInit_(false) +{ + DHLOGI("DCameraSinkHandlerIpc Create"); +} + +DCameraSinkHandlerIpc::~DCameraSinkHandlerIpc() +{ + DHLOGI("DCameraSinkHandlerIpc Delete"); + UnInit(); +} + +IMPLEMENT_SINGLE_INSTANCE(DCameraSinkHandlerIpc); + +void DCameraSinkHandlerIpc::Init() +{ + std::lock_guard autoLock(initDmsLock_); + DHLOGI("DCameraSinkHandlerIpc Init Start"); + if (isInit_) { + DHLOGI("DCameraSinkHandlerIpc has already init"); + return; + } + auto runner = AppExecFwk::EventRunner::Create("DCameraSinkHandlerIpcHandler"); + serviceHandler_ = std::make_shared(runner); + sinkLocalRecipient_ = new SinkLocalRecipient(); + isInit_ = true; + DHLOGI("DCameraSinkHandlerIpc Init End"); +} + +void DCameraSinkHandlerIpc::UnInit() +{ + std::lock_guard autoLock(initDmsLock_); + DHLOGI("DCameraSinkHandlerIpc UnInit Start"); + if (!isInit_) { + DHLOGI("DCameraSinkHandlerIpc has already UnInit"); + return; + } + DeleteSinkLocalDhms(); + DHLOGI("DCameraSinkHandlerIpc Start free serviceHandler"); + serviceHandler_ = nullptr; + DHLOGI("DCameraSinkHandlerIpc Start free recipient"); + sinkLocalRecipient_ = nullptr; + isInit_ = false; + DHLOGI("DCameraSinkHandlerIpc UnInit End"); +} + +sptr DCameraSinkHandlerIpc::GetSinkLocalDHMS() +{ + { + std::lock_guard autoLock(sinkLocalDmsLock_); + if (localSink_ != nullptr) { + DHLOGI("DCameraSinkHandlerIpc GetSinkLocalDHMS from cache"); + return localSink_; + } + } + DHLOGI("GetSinkLocalDHMS Start"); + sptr sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sm == nullptr) { + DHLOGE("GetSinkLocalDHMS GetSystemAbilityManager failed"); + return nullptr; + } + + sptr object = sm->GetSystemAbility(DISTRIBUTED_HARDWARE_CAMERA_SINK_SA_ID); + if (object == nullptr) { + DHLOGE("GetSinkLocalDHMS GetSystemAbility failed"); + return nullptr; + } + int32_t ret = object->AddDeathRecipient(sinkLocalRecipient_); + sptr localSink = iface_cast(object); + if (localSink == nullptr) { + DHLOGI("GetSinkLocalDHMS failed, localSink is null ret: %d", ret); + return nullptr; + } + { + std::lock_guard autoLock(sinkLocalDmsLock_); + if (localSink_ != nullptr) { + localSink_->AsObject()->RemoveDeathRecipient(sinkLocalRecipient_); + } + localSink_ = localSink; + } + DHLOGI("GetSinkLocalDHMS success, AddDeathRecipient ret: %d", ret); + return localSink; +} + +void DCameraSinkHandlerIpc::DeleteSinkLocalDhms() +{ + DHLOGI("DeleteSinkLocalDhms start"); + std::lock_guard autoLock(sinkLocalDmsLock_); + if (localSink_ != nullptr) { + localSink_->AsObject()->RemoveDeathRecipient(sinkLocalRecipient_); + } + localSink_ = nullptr; + DHLOGI("DeleteSinkLocalDhms end"); +} + +void DCameraSinkHandlerIpc::SinkLocalRecipient::OnRemoteDied(const wptr& remote) +{ + DHLOGI("SinkLocalRecipient OnRemoteDied received died notify!"); + DCameraSinkHandlerIpc::GetInstance().OnSinkLocalDmsDied(remote); +} + +void DCameraSinkHandlerIpc::OnSinkLocalDmsDied(const wptr& remote) +{ + sptr diedRemoted = remote.promote(); + if (diedRemoted == nullptr) { + DHLOGE("OnSinkLocalDmsDied promote failed!"); + return; + } + DHLOGI("OnSinkLocalDmsDied delete diedRemoted"); + auto remoteDmsDiedFunc = [this, diedRemoted]() { + OnSinkLocalDmsDied(diedRemoted); + }; + if (serviceHandler_ != nullptr) { + serviceHandler_->PostTask(remoteDmsDiedFunc); + } +} + +void DCameraSinkHandlerIpc::OnSinkLocalDmsDied(const sptr& remote) +{ + std::lock_guard autoLock(sinkLocalDmsLock_); + if (localSink_->AsObject() != remote) { + DHLOGI("OnSinkLocalDmsDied not found remote object"); + return; + } + + DHLOGI("OnSinkLocalDmsDied Clear"); + if (localSink_ != nullptr) { + localSink_->AsObject()->RemoveDeathRecipient(sinkLocalRecipient_); + } + localSink_ = nullptr; +} +} +} \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_sink/src/distributed_camera_sink_proxy.cpp b/interfaces/inner_kits/native_cpp/camera_sink/src/distributed_camera_sink_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28b9033aa94edf2b8fc0345a1144e9e4b945c987 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_sink/src/distributed_camera_sink_proxy.cpp @@ -0,0 +1,248 @@ +/* + * 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 "distributed_camera_sink_proxy.h" + +#include "parcel.h" + +#include "anonymous_string.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DistributedCameraSinkProxy::InitSink(const std::string& params) +{ + DHLOGI("DistributedCameraSinkProxy::InitSink"); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::InitSink remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::InitSink write token failed"); + return DCAMERA_BAD_VALUE; + } + if (!data.WriteString(params)) { + DHLOGE("DistributedCameraSinkProxy::InitSink write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(INIT_SINK, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSinkProxy::ReleaseSink() +{ + DHLOGI("DistributedCameraSinkProxy::ReleaseSink"); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::ReleaseSink remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::ReleaseSink write token failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(RELEASE_SINK, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSinkProxy::SubscribeLocalHardware(const std::string& dhId, const std::string& parameters) +{ + DHLOGI("DistributedCameraSinkProxy::SubscribeLocalHardware dhId: %s", GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::SubscribeLocalHardware remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::SubscribeLocalHardware write token failed"); + return DCAMERA_BAD_VALUE; + } + if (!data.WriteString(dhId) || !data.WriteString(parameters)) { + DHLOGE("DistributedCameraSinkProxy::SubscribeLocalHardware write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(SUBSCRIBE_LOCAL_HARDWARE, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSinkProxy::UnsubscribeLocalHardware(const std::string& dhId) +{ + DHLOGI("DistributedCameraSinkProxy::UnsubscribeLocalHardware dhId: %s", GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::UnsubscribeLocalHardware remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::UnsubscribeLocalHardware write token failed"); + return DCAMERA_BAD_VALUE; + } + if (!data.WriteString(dhId)) { + DHLOGE("DistributedCameraSinkProxy::UnsubscribeLocalHardware write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(UNSUBSCRIBE_LOCAL_HARDWARE, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSinkProxy::StopCapture(const std::string& dhId) +{ + DHLOGI("DistributedCameraSinkProxy::StopCapture dhId: %s", GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::StopCapture remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option = { MessageOption::TF_ASYNC }; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::StopCapture write token failed"); + return DCAMERA_BAD_VALUE; + } + if (!data.WriteString(dhId)) { + DHLOGE("DistributedCameraSinkProxy::StopCapture write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(STOP_CAPTURE, data, reply, option); + int32_t result = reply.ReadInt32(); + DHLOGI("DistributedCameraSinkProxy::StopCapture async dhId: %s", GetAnonyString(dhId).c_str()); + return result; +} + +int32_t DistributedCameraSinkProxy::ChannelNeg(const std::string& dhId, std::string& channelInfo) +{ + DHLOGI("DistributedCameraSinkProxy::ChannelNeg dhId: %s", GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::ChannelNeg remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::ChannelNeg write token failed"); + return DCAMERA_BAD_VALUE; + } + if (!data.WriteString(dhId) || !data.WriteString(channelInfo)) { + DHLOGE("DistributedCameraSinkProxy::ChannelNeg write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(CHANNEL_NEG, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSinkProxy::GetCameraInfo(const std::string& dhId, std::string& cameraInfo) +{ + DHLOGI("DistributedCameraSinkProxy::GetCameraInfo dhId: %s", GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::GetCameraInfo remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::GetCameraInfo write token failed"); + return DCAMERA_BAD_VALUE; + } + if (!data.WriteString(dhId) || !data.WriteString(cameraInfo)) { + DHLOGE("DistributedCameraSinkProxy::GetCameraInfo write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(GET_CAMERA_INFO, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSinkProxy::OpenChannel(const std::string& dhId, std::string& openInfo) +{ + DHLOGI("DistributedCameraSinkProxy::OpenChannel dhId: %s", GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::OpenChannel remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::OpenChannel write token failed"); + return DCAMERA_BAD_VALUE; + } + if (!data.WriteString(dhId) || !data.WriteString(openInfo)) { + DHLOGE("DistributedCameraSinkProxy::OpenChannel write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(OPEN_CHANNEL, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSinkProxy::CloseChannel(const std::string& dhId) +{ + DHLOGI("DistributedCameraSinkProxy::CloseChannel dhId: %s", GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSinkProxy::CloseChannel remote service is null"); + return DCAMERA_BAD_VALUE; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSinkProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSinkProxy::CloseChannel write token failed"); + return DCAMERA_BAD_VALUE; + } + if (!data.WriteString(dhId)) { + DHLOGE("DistributedCameraSinkProxy::CloseChannel write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(CLOSE_CHANNEL, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/BUILD.gn b/interfaces/inner_kits/native_cpp/camera_source/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d7a463a3aefe31ff59938af23187d0a4347b3b03 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/BUILD.gn @@ -0,0 +1,63 @@ +# 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. + +import("//build/ohos.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_source_sdk") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + ] + + include_dirs += [ + "include", + "include/callback", + "${common_path}/include/constants", + ] + + sources = [ + "src/dcamera_source_handler_ipc.cpp", + "src/distributed_camera_source_proxy.cpp", + "src/dcamera_source_handler.cpp", + "src/callback/dcamera_source_callback_stub.cpp", + "src/callback/dcamera_source_callback.cpp", + ] + + deps = [ + "//utils/native/base:utils", + "${fwk_utils_path}:distributedhardwareutils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dcamerasourcekits\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} + diff --git a/interfaces/inner_kits/native_cpp/camera_source/include/callback/dcamera_source_callback.h b/interfaces/inner_kits/native_cpp/camera_source/include/callback/dcamera_source_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..97288bd451774d4b51c954fa2391268a0ceec588 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/include/callback/dcamera_source_callback.h @@ -0,0 +1,46 @@ +/* + * 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_DCAMERA_SOURCE_CALLBACK_H +#define OHOS_DCAMERA_SOURCE_CALLBACK_H + +#include + +#include "dcamera_source_callback_stub.h" +#include "idistributed_hardware_source.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceCallback : public DCameraSourceCallbackStub { +public: + DCameraSourceCallback() = default; + ~DCameraSourceCallback(); + + int32_t OnNotifyRegResult(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) override; + int32_t OnNotifyUnregResult(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) override; + + void PushRegCallback(std::string& reqId, std::shared_ptr& callback); + void PopRegCallback(std::string& reqId); + void PushUnregCallback(std::string& reqId, std::shared_ptr& callback); + void PopUnregCallback(std::string& reqId); +private: + std::map> regCallbacks_; + std::map> unregCallbacks_; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/include/callback/dcamera_source_callback_stub.h b/interfaces/inner_kits/native_cpp/camera_source/include/callback/dcamera_source_callback_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..d4ed3bc486897500d66446a122495da860bfa978 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/include/callback/dcamera_source_callback_stub.h @@ -0,0 +1,41 @@ +/* + * 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_DCAMERA_SOURCE_CALLBACK_STUB_H +#define OHOS_DCAMERA_SOURCE_CALLBACK_STUB_H + +#include +#include "iremote_stub.h" + +#include "idcamera_source_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceCallbackStub : public IRemoteStub { +public: + DCameraSourceCallbackStub(); + virtual ~DCameraSourceCallbackStub(); + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t NotifyRegResultInner(MessageParcel &data, MessageParcel &reply); + int32_t NotifyUnregResultInner(MessageParcel &data, MessageParcel &reply); + + using DCameraFunc = int32_t (DCameraSourceCallbackStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/include/callback/idcamera_source_callback.h b/interfaces/inner_kits/native_cpp/camera_source/include/callback/idcamera_source_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..1c09539209657ff7e45bc020391c8bc365c494f8 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/include/callback/idcamera_source_callback.h @@ -0,0 +1,39 @@ +/* + * 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_IDCAMERA_SOURCE_CALLBACL_H +#define OHOS_IDCAMERA_SOURCE_CALLBACL_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace DistributedHardware { +class IDCameraSourceCallback : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.dcamerasourcecallback"); + enum { + NOTIFY_REG_RESULT = 0, + NOTIFY_UNREG_RESULT = 1, + }; + + virtual ~IDCameraSourceCallback() {} + virtual int32_t OnNotifyRegResult(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) = 0; + virtual int32_t OnNotifyUnregResult(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/include/dcamera_source_handler.h b/interfaces/inner_kits/native_cpp/camera_source/include/dcamera_source_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..ea9f10f1d7d43a6fc7460da9e6015402b1e4cb45 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/include/dcamera_source_handler.h @@ -0,0 +1,61 @@ +/* + * 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_DCAMERA_SOURCE_HANDLER_H +#define OHOS_DCAMERA_SOURCE_HANDLER_H + +#include + +#include "iremote_proxy.h" +#include "iremote_broker.h" +#include "refbase.h" + +#include "dcamera_source_callback.h" +#include "idistributed_hardware_source.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceHandler : public IDistributedHardwareSource { +DECLARE_SINGLE_INSTANCE_BASE(DCameraSourceHandler); +public: + int32_t InitSource(const std::string& params) override; + int32_t ReleaseSource() override; + int32_t RegisterDistributedHardware(const std::string& devId, const std::string& dhId, + const EnableParam& param, std::shared_ptr callback) override; + int32_t UnregisterDistributedHardware(const std::string& devId, const std::string& dhId, + std::shared_ptr callback) override; + int32_t ConfigDistributedHardware(const std::string& devId, const std::string& dhId, const std::string& key, + const std::string& value) override; + +private: + DCameraSourceHandler() = default; + ~DCameraSourceHandler(); + +private: + std::mutex optLock_; + sptr callback_; +}; + +#ifdef __cplusplus +extern "C" { +#endif +__attribute__((visibility("default"))) IDistributedHardwareSource *GetSourceHardwareHandler(); +#ifdef __cplusplus +} +#endif +} +} +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/include/dcamera_source_handler_ipc.h b/interfaces/inner_kits/native_cpp/camera_source/include/dcamera_source_handler_ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..cdee7ccd1285f60b25fa65a08b385a923f79939d --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/include/dcamera_source_handler_ipc.h @@ -0,0 +1,53 @@ +/* + * 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_DCAMERA_SOURCE_HANDLER_IPC_H +#define OHOS_DCAMERA_SOURCE_HANDLER_IPC_H + +#include "event_handler.h" +#include "idistributed_camera_source.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceHandlerIpc { +DECLARE_SINGLE_INSTANCE_BASE(DCameraSourceHandlerIpc); +public: + void Init(); + void UnInit(); + sptr GetSourceLocalDHMS(); + void OnSourceLocalDmsDied(const wptr& remote); + +private: + DCameraSourceHandlerIpc(); + ~DCameraSourceHandlerIpc(); + void OnSourceLocalDmsDied(const sptr& remote); + void DeleteSourceLocalDhms(); + + class SourceLocalRecipient : public IRemoteObject::DeathRecipient { + public: + void OnRemoteDied(const wptr& remote) override; + }; + sptr sourceLocalRecipient_; + sptr localSource_; + std::mutex sourceLocalDmsLock_; + + bool isInit_; + std::shared_ptr serviceHandler_; + std::mutex initDmsLock_; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/include/distributed_camera_source_proxy.h b/interfaces/inner_kits/native_cpp/camera_source/include/distributed_camera_source_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..2da596970432bb0e8283eb609f244f5f12129d74 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/include/distributed_camera_source_proxy.h @@ -0,0 +1,50 @@ +/* + * 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_DISTRIBUTED_CAMERA_SOURCE_PROXY_H +#define OHOS_DISTRIBUTED_CAMERA_SOURCE_PROXY_H + +#include + +#include "iremote_proxy.h" +#include "iremote_broker.h" +#include "refbase.h" + +#include "idistributed_camera_source.h" + +namespace OHOS { +namespace DistributedHardware { +class DistributedCameraSourceProxy : public IRemoteProxy { +public: + explicit DistributedCameraSourceProxy(const sptr& impl) + : IRemoteProxy(impl) + { + } + + ~DistributedCameraSourceProxy() {} + int32_t InitSource(const std::string& params, const sptr& callback) override; + int32_t ReleaseSource() override; + int32_t RegisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId, const EnableParam& param) override; + int32_t UnregisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId) override; + int32_t DCameraNotify(const std::string& devId, const std::string& dhId, std::string& events) override; + +private: + static inline BrokerDelegator delegator_; +}; +} +} + +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/include/idistributed_camera_source.h b/interfaces/inner_kits/native_cpp/camera_source/include/idistributed_camera_source.h new file mode 100644 index 0000000000000000000000000000000000000000..d7f98a29f6fc2422aaa1a3c1ea5ea8be003223fb --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/include/idistributed_camera_source.h @@ -0,0 +1,48 @@ +/* + * 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_IDISTRIBUTED_CAMERA_SOURCE_H +#define OHOS_IDISTRIBUTED_CAMERA_SOURCE_H + +#include "iremote_broker.h" + +#include "idcamera_source_callback.h" +#include "idistributed_hardware_source.h" + +namespace OHOS { +namespace DistributedHardware { +class IDistributedCameraSource : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.distributedcamerasource"); + enum { + INIT_SOURCE = 0, + RELEASE_SOURCE = 1, + REGISTER_DISTRIBUTED_HARDWARE = 2, + UNREGISTER_DISTRIBUTED_HARDWARE = 3, + CAMERA_NOTIFY = 4, + }; + + virtual ~IDistributedCameraSource() {} + virtual int32_t InitSource(const std::string& params, const sptr& callback) = 0; + virtual int32_t ReleaseSource() = 0; + virtual int32_t RegisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId, const EnableParam& param) = 0; + virtual int32_t UnregisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId) = 0; + virtual int32_t DCameraNotify(const std::string& devId, const std::string& dhId, std::string& events) = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/src/callback/dcamera_source_callback.cpp b/interfaces/inner_kits/native_cpp/camera_source/src/callback/dcamera_source_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9117994fce62be7cb537e37af640d9d3c2b3ba57 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/src/callback/dcamera_source_callback.cpp @@ -0,0 +1,90 @@ +/* + * 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 "dcamera_source_callback.h" + +#include "anonymous_string.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceCallback::~DCameraSourceCallback() +{ + regCallbacks_.clear(); + unregCallbacks_.clear(); +} + +int32_t DCameraSourceCallback::OnNotifyRegResult(const std::string& devId, const std::string& dhId, + const std::string& reqId, int32_t status, std::string& data) +{ + DHLOGI("DCameraSourceCallback OnNotifyRegResult devId: %s dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + auto iter = regCallbacks_.find(reqId); + if (iter == regCallbacks_.end()) { + DHLOGE("DCameraSourceCallback OnNotifyRegResult not found devId: %s dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return DCAMERA_NOT_FOUND; + } + int32_t ret = iter->second->OnRegisterResult(devId, dhId, status, data); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCallback OnNotifyRegResult failed, devId: %s dhId: %s ret: %d", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), ret); + } + regCallbacks_.erase(iter); + return ret; +} + +int32_t DCameraSourceCallback::OnNotifyUnregResult(const std::string& devId, const std::string& dhId, + const std::string& reqId, int32_t status, std::string& data) +{ + DHLOGI("DCameraSourceCallback OnNotifyUnregResult devId: %s dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + auto iter = unregCallbacks_.find(reqId); + if (iter == unregCallbacks_.end()) { + DHLOGE("DCameraSourceCallback OnNotifyUnregResult not found devId: %s dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return DCAMERA_NOT_FOUND; + } + int32_t ret = iter->second->OnUnregisterResult(devId, dhId, status, data); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCallback OnNotifyUnregResult failed, devId: %s dhId: %s ret: %d", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), ret); + } + unregCallbacks_.erase(iter); + return ret; +} + +void DCameraSourceCallback::PushRegCallback(std::string& reqId, std::shared_ptr& callback) +{ + regCallbacks_.emplace(reqId, callback); +} + +void DCameraSourceCallback::PopRegCallback(std::string& reqId) +{ + regCallbacks_.erase(reqId); +} + +void DCameraSourceCallback::PushUnregCallback(std::string& reqId, std::shared_ptr& callback) +{ + unregCallbacks_.emplace(reqId, callback); +} + +void DCameraSourceCallback::PopUnregCallback(std::string& reqId) +{ + unregCallbacks_.erase(reqId); +} +} +} \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/src/callback/dcamera_source_callback_stub.cpp b/interfaces/inner_kits/native_cpp/camera_source/src/callback/dcamera_source_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9da85fb0980be0d64937864156ea548e334a9cf9 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/src/callback/dcamera_source_callback_stub.cpp @@ -0,0 +1,82 @@ +/* + * 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 "dcamera_source_callback_stub.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceCallbackStub::DCameraSourceCallbackStub() +{ + memberFuncMap_[NOTIFY_REG_RESULT] = &DCameraSourceCallbackStub::NotifyRegResultInner; + memberFuncMap_[NOTIFY_UNREG_RESULT] = &DCameraSourceCallbackStub::NotifyUnregResultInner; +} + +DCameraSourceCallbackStub::~DCameraSourceCallbackStub() +{} + +int32_t DCameraSourceCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DCameraSourceCallbackStub OnRemoteRequest code: %d", code); + std::u16string desc = DCameraSourceCallbackStub::GetDescriptor(); + std::u16string remoteDesc = data.ReadInterfaceToken(); + if (desc != remoteDesc) { + DHLOGE("DCameraSourceCallbackStub::OnRemoteRequest remoteDesc is invalid!"); + return ERR_INVALID_DATA; + } + auto itFunc = memberFuncMap_.find(code); + if (itFunc == memberFuncMap_.end()) { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + + auto memberFunc = itFunc->second; + return (this->*memberFunc)(data, reply); +} + +int32_t DCameraSourceCallbackStub::NotifyRegResultInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DCameraSourceCallbackStub NotifyRegResultInner"); + int32_t ret = DCAMERA_OK; + do { + std::string devId = data.ReadString(); + std::string dhId = data.ReadString(); + std::string reqId = data.ReadString(); + int32_t status = data.ReadInt32(); + std::string result = data.ReadString(); + ret = OnNotifyRegResult(devId, dhId, reqId, status, result); + } while (0); + reply.WriteInt32(ret); + return ret; +} + +int32_t DCameraSourceCallbackStub::NotifyUnregResultInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DCameraSourceCallbackStub NotifyUnregResultInner"); + int32_t ret = DCAMERA_OK; + do { + std::string devId = data.ReadString(); + std::string dhId = data.ReadString(); + std::string reqId = data.ReadString(); + int32_t status = data.ReadInt32(); + std::string result = data.ReadString(); + ret = OnNotifyUnregResult(devId, dhId, reqId, status, result); + } while (0); + reply.WriteInt32(ret); + return ret; +} +} +} \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/src/dcamera_source_handler.cpp b/interfaces/inner_kits/native_cpp/camera_source/src/dcamera_source_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c22664a96bfa0aa8fca4adbd075f0cf8ed92fe8 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/src/dcamera_source_handler.cpp @@ -0,0 +1,126 @@ +/* + * 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 "dcamera_source_handler.h" +#include "dcamera_source_callback.h" + +#include "anonymous_string.h" +#include "dcamera_source_handler_ipc.h" +#include "dh_utils_tool.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DCameraSourceHandler); + +DCameraSourceHandler::~DCameraSourceHandler() +{ + DHLOGI("~DCameraSourceHandler"); +} + +int32_t DCameraSourceHandler::InitSource(const std::string& params) +{ + DHLOGI("DCameraSourceHandler InitSource Start"); + DCameraSourceHandlerIpc::GetInstance().Init(); + sptr dCameraSourceSrv = DCameraSourceHandlerIpc::GetInstance().GetSourceLocalDHMS(); + if (dCameraSourceSrv == nullptr) { + DHLOGE("DCameraSourceHandler InitSource get Service failed"); + return DCAMERA_INIT_ERR; + } + + callback_ = new DCameraSourceCallback(); + if (callback_ == nullptr) { + DHLOGE("DCameraSourceHandler InitSource init callback failed"); + return DCAMERA_INIT_ERR; + } + int32_t ret = dCameraSourceSrv->InitSource(params, callback_); + DHLOGI("DCameraSourceHandler InitSource end, ret: %d", ret); + return ret; +} + +int32_t DCameraSourceHandler::ReleaseSource() +{ + DHLOGI("DCameraSourceHandler ReleaseSource Start"); + sptr dCameraSourceSrv = DCameraSourceHandlerIpc::GetInstance().GetSourceLocalDHMS(); + if (dCameraSourceSrv == nullptr) { + DHLOGE("DCameraSourceHandler ReleaseSource get Service failed"); + return DCAMERA_INIT_ERR; + } + dCameraSourceSrv->ReleaseSource(); + DCameraSourceHandlerIpc::GetInstance().UnInit(); + DHLOGI("DCameraSourceHandler ReleaseSource end"); + return DCAMERA_OK; +} + +int32_t DCameraSourceHandler::RegisterDistributedHardware(const std::string& devId, const std::string& dhId, + const EnableParam& param, std::shared_ptr callback) +{ + DHLOGI("DCameraSourceHandler RegisterDistributedHardware devId: %s dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + sptr dCameraSourceSrv = DCameraSourceHandlerIpc::GetInstance().GetSourceLocalDHMS(); + if (dCameraSourceSrv == nullptr) { + DHLOGE("DCameraSourceHandler RegisterDistributedHardware get Service failed"); + return DCAMERA_BAD_VALUE; + } + + std::lock_guard autoLock(optLock_); + std::string reqId = GetRandomID(); + callback_->PushRegCallback(reqId, callback); + int32_t ret = dCameraSourceSrv->RegisterDistributedHardware(devId, dhId, reqId, param); + if (ret != DCAMERA_OK) { + callback_->PopRegCallback(reqId); + } + DHLOGI("DCameraSourceHandler RegisterDistributedHardware end, ret: %d devId: %s dhId: %s version: %s", + ret, GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), param.version.c_str()); + return ret; +} + +int32_t DCameraSourceHandler::UnregisterDistributedHardware(const std::string& devId, const std::string& dhId, + std::shared_ptr callback) +{ + DHLOGI("DCameraSourceHandler UnregisterDistributedHardware devId: %s dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + sptr dCameraSourceSrv = DCameraSourceHandlerIpc::GetInstance().GetSourceLocalDHMS(); + if (dCameraSourceSrv == nullptr) { + DHLOGE("DCameraSourceHandler UnregisterDistributedHardware get Service failed"); + return DCAMERA_BAD_VALUE; + } + + std::lock_guard autoLock(optLock_); + std::string reqId = GetRandomID(); + callback_->PushUnregCallback(reqId, callback); + int32_t ret = dCameraSourceSrv->UnregisterDistributedHardware(devId, dhId, reqId); + if (ret != DCAMERA_OK) { + callback_->PopUnregCallback(reqId); + } + DHLOGI("DCameraSourceHandler UnregisterDistributedHardware end, ret: %d devId: %s dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; +} + +int32_t DCameraSourceHandler::ConfigDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& key, const std::string& value) +{ + return DCAMERA_OK; +} + +IDistributedHardwareSource *GetSourceHardwareHandler() +{ + DHLOGI("DCameraSourceHandler GetSourceHardwareHandler Start"); + return &DCameraSourceHandler::GetInstance(); +} +} +} \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/src/dcamera_source_handler_ipc.cpp b/interfaces/inner_kits/native_cpp/camera_source/src/dcamera_source_handler_ipc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ccf062d2b736df37ed2263e052a78fa1fe7af1ff --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/src/dcamera_source_handler_ipc.cpp @@ -0,0 +1,159 @@ +/* + * 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 "dcamera_source_handler_ipc.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceHandlerIpc::DCameraSourceHandlerIpc() : isInit_(false) +{ + DHLOGI("DCameraSourceHandlerIpc Create"); +} + +DCameraSourceHandlerIpc::~DCameraSourceHandlerIpc() +{ + DHLOGI("DCameraSourceHandlerIpc Delete"); + UnInit(); +} + +IMPLEMENT_SINGLE_INSTANCE(DCameraSourceHandlerIpc); + +void DCameraSourceHandlerIpc::Init() +{ + std::lock_guard autoLock(initDmsLock_); + DHLOGI("DCameraSourceHandlerIpc Init Start"); + if (isInit_) { + DHLOGI("DCameraSourceHandlerIpc has already init"); + return; + } + auto runner = AppExecFwk::EventRunner::Create("DCameraSourceHandlerIpcHandler"); + serviceHandler_ = std::make_shared(runner); + sourceLocalRecipient_ = new SourceLocalRecipient(); + isInit_ = true; + DHLOGI("DCameraSourceHandlerIpc Init End"); +} + +void DCameraSourceHandlerIpc::UnInit() +{ + std::lock_guard autoLock(initDmsLock_); + DHLOGI("DCameraSourceHandlerIpc UnInit Start"); + if (!isInit_) { + DHLOGI("DCameraSourceHandlerIpc has already UnInit"); + return; + } + DeleteSourceLocalDhms(); + DHLOGI("DCameraSourceHandlerIpc Start free serviceHandler"); + serviceHandler_ = nullptr; + DHLOGI("DCameraSourceHandlerIpc Start free recipient"); + sourceLocalRecipient_ = nullptr; + isInit_ = false; + DHLOGI("DCameraSourceHandlerIpc UnInit End"); +} + +sptr DCameraSourceHandlerIpc::GetSourceLocalDHMS() +{ + { + std::lock_guard autoLock(sourceLocalDmsLock_); + if (localSource_ != nullptr) { + DHLOGI("DCameraSourceHandlerIpc GetSourceLocalDHMS from cache"); + return localSource_; + } + } + DHLOGI("GetSourceLocalDHMS Start"); + sptr sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sm == nullptr) { + DHLOGE("GetSourceLocalDHMS GetSystemAbilityManager failed"); + return nullptr; + } + + sptr object = sm->GetSystemAbility(DISTRIBUTED_HARDWARE_CAMERA_SOURCE_SA_ID); + if (object == nullptr) { + DHLOGE("GetSourceLocalDHMS GetSystemAbility failed"); + return nullptr; + } + int32_t ret = object->AddDeathRecipient(sourceLocalRecipient_); + sptr localSource = iface_cast(object); + if (localSource == nullptr) { + DHLOGI("GetSourceLocalDHMS failed, localSource is null ret: %d", ret); + return nullptr; + } + { + std::lock_guard autoLock(sourceLocalDmsLock_); + if (localSource_ != nullptr) { + localSource_->AsObject()->RemoveDeathRecipient(sourceLocalRecipient_); + } + localSource_ = localSource; + } + DHLOGI("GetSourceLocalDHMS success, AddDeathRecipient ret: %d", ret); + return localSource; +} + +void DCameraSourceHandlerIpc::DeleteSourceLocalDhms() +{ + DHLOGI("DeleteSourceLocalDhms start"); + std::lock_guard autoLock(sourceLocalDmsLock_); + if (localSource_ != nullptr) { + localSource_->AsObject()->RemoveDeathRecipient(sourceLocalRecipient_); + } + localSource_ = nullptr; + DHLOGI("DeleteSourceLocalDhms end"); +} + +void DCameraSourceHandlerIpc::SourceLocalRecipient::OnRemoteDied(const wptr& remote) +{ + DHLOGI("SourceLocalRecipient OnRemoteDied received died notify!"); + DCameraSourceHandlerIpc::GetInstance().OnSourceLocalDmsDied(remote); +} + +void DCameraSourceHandlerIpc::OnSourceLocalDmsDied(const wptr& remote) +{ + sptr diedRemoted = remote.promote(); + if (diedRemoted == nullptr) { + DHLOGE("OnSourceLocalDmsDied promote failed!"); + return; + } + DHLOGI("OnSourceLocalDmsDied delete diedRemoted"); + auto remoteDmsDiedFunc = [this, diedRemoted]() { + OnSourceLocalDmsDied(diedRemoted); + }; + if (serviceHandler_ != nullptr) { + serviceHandler_->PostTask(remoteDmsDiedFunc); + } +} + +void DCameraSourceHandlerIpc::OnSourceLocalDmsDied(const sptr& remote) +{ + std::lock_guard autoLock(sourceLocalDmsLock_); + if (localSource_->AsObject() != remote) { + DHLOGI("OnSourceLocalDmsDied not found remote object"); + return; + } + + DHLOGI("OnSourceLocalDmsDied Clear"); + if (localSource_ != nullptr) { + localSource_->AsObject()->RemoveDeathRecipient(sourceLocalRecipient_); + } + localSource_ = nullptr; +} +} +} \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/camera_source/src/distributed_camera_source_proxy.cpp b/interfaces/inner_kits/native_cpp/camera_source/src/distributed_camera_source_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07d5ddf3c47c74ddb6e548c9da9f5500300b70e2 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/camera_source/src/distributed_camera_source_proxy.cpp @@ -0,0 +1,160 @@ +/* + * 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 "distributed_camera_source_proxy.h" + +#include "parcel.h" + +#include "anonymous_string.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DistributedCameraSourceProxy::InitSource(const std::string& params, + const sptr& callback) +{ + DHLOGI("DistributedCameraSourceProxy InitSource"); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSourceProxy remote service null"); + return DCAMERA_BAD_VALUE; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSourceProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSourceProxy InitSource write token failed"); + return DCAMERA_BAD_VALUE; + } + + if (!data.WriteString(params)) { + DHLOGE("DistributedCameraSourceProxy InitSource write params failed"); + return DCAMERA_BAD_VALUE; + } + + if (!data.WriteRemoteObject(callback->AsObject())) { + DHLOGE("DistributedCameraSourceProxy InitSource write callback failed"); + return DCAMERA_BAD_VALUE; + } + + remote->SendRequest(INIT_SOURCE, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSourceProxy::ReleaseSource() +{ + DHLOGI("DistributedCameraSourceProxy ReleaseSource"); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSourceProxy remote service null"); + return DCAMERA_BAD_VALUE; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSourceProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSourceProxy InitSource write token failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(RELEASE_SOURCE, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSourceProxy::RegisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId, const EnableParam& param) +{ + DHLOGI("DistributedCameraSourceProxy RegisterDistributedHardware devId: %s dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSourceProxy remote service null"); + return DCAMERA_BAD_VALUE; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSourceProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSourceProxy RegisterDistributedHardware write token failed"); + return DCAMERA_BAD_VALUE; + } + + if (!data.WriteString(devId) || !data.WriteString(dhId) || !data.WriteString(reqId) || + !data.WriteString(param.version) || !data.WriteString(param.attrs)) { + DHLOGE("DistributedCameraSourceProxy RegisterDistributedHardware write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(REGISTER_DISTRIBUTED_HARDWARE, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSourceProxy::UnregisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId) +{ + DHLOGI("DistributedCameraSourceProxy UnregisterDistributedHardware devId: %s dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSourceProxy remote service null"); + return DCAMERA_BAD_VALUE; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSourceProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSourceProxy UnregisterDistributedHardware write token failed"); + return DCAMERA_BAD_VALUE; + } + + if (!data.WriteString(devId) || !data.WriteString(dhId) || !data.WriteString(reqId)) { + DHLOGE("DistributedCameraSourceProxy UnregisterDistributedHardware write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(UNREGISTER_DISTRIBUTED_HARDWARE, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DistributedCameraSourceProxy::DCameraNotify(const std::string& devId, const std::string& dhId, + std::string& events) +{ + DHLOGI("DCameraNotify devId: %s dhId: %s events: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), events.c_str()); + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DistributedCameraSourceProxy remote service null"); + return DCAMERA_BAD_VALUE; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DistributedCameraSourceProxy::GetDescriptor())) { + DHLOGE("DistributedCameraSourceProxy DCameraNotify write token failed"); + return DCAMERA_BAD_VALUE; + } + + if (!data.WriteString(devId) || !data.WriteString(dhId) || !data.WriteString(events)) { + DHLOGE("DistributedCameraSourceProxy DCameraNotify write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(CAMERA_NOTIFY, data, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} +} +} \ No newline at end of file diff --git a/sa_profile/4803.xml b/sa_profile/4803.xml new file mode 100644 index 0000000000000000000000000000000000000000..32f4655ed666db10b17626b22c9ed9194a30d5f4 --- /dev/null +++ b/sa_profile/4803.xml @@ -0,0 +1,27 @@ + + + + dhardware + + 4803 + libdistributed_camera_source.z.so + + + true + true + 1 + + diff --git a/sa_profile/4804.xml b/sa_profile/4804.xml new file mode 100644 index 0000000000000000000000000000000000000000..d01ba6594c8a1c63cf331fad2d651fba93d91023 --- /dev/null +++ b/sa_profile/4804.xml @@ -0,0 +1,27 @@ + + + + dhardware + + 4804 + libdistributed_camera_sink.z.so + + + true + true + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8d10ac4f7b314aec5285454fb47736feae2eb307 --- /dev/null +++ b/sa_profile/BUILD.gn @@ -0,0 +1,23 @@ +# 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. + +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("dcamera_sa_profile") { + sources = [ + "4803.xml", + "4804.xml", + ] + + part_name = "distributed_camera" +} diff --git a/services/cameraservice/base/include/dcamera_capture_info_cmd.h b/services/cameraservice/base/include/dcamera_capture_info_cmd.h new file mode 100644 index 0000000000000000000000000000000000000000..4f54f8b7072ce5c531bafcf1f90e0a99c519c480 --- /dev/null +++ b/services/cameraservice/base/include/dcamera_capture_info_cmd.h @@ -0,0 +1,54 @@ +/* + * 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_DCAMERA_CAPTURE_INFO_H +#define OHOS_DCAMERA_CAPTURE_INFO_H + +#include "distributed_camera_constants.h" +#include "json/json.h" +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraCaptureInfo { +public: + int32_t width_; + int32_t height_; + int32_t format_; + int32_t dataspace_; + bool isCapture_; + DCEncodeType encodeType_; + DCStreamType streamType_; + std::vector> captureSettings_; +}; + +class DCameraCaptureInfoCmd { +public: + std::string type_; + std::string dhId_; + std::string command_; + std::vector> value_; + +public: + int32_t Marshal(std::string& jsonStr); + int32_t Unmarshal(const std::string& jsonStr); + +private: + int32_t UmarshalValue(Json::Value& rootValue); + int32_t UmarshalSettings(Json::Value& valueJson, std::shared_ptr& captureInfo); +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/base/include/dcamera_channel_info_cmd.h b/services/cameraservice/base/include/dcamera_channel_info_cmd.h new file mode 100644 index 0000000000000000000000000000000000000000..fe6506d47768adf6e58b5f478c812f38cd3dfc02 --- /dev/null +++ b/services/cameraservice/base/include/dcamera_channel_info_cmd.h @@ -0,0 +1,57 @@ +/* + * 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_DCAMERA_CHANNEL_INFO_H +#define OHOS_DCAMERA_CHANNEL_INFO_H + +#include +#include +#include +#include + +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraChannelDetail { +public: + DCameraChannelDetail() = default; + DCameraChannelDetail(std::string dataSessionFlag, DCStreamType streamType) + : dataSessionFlag_(dataSessionFlag), streamType_(streamType) + {} + ~DCameraChannelDetail() = default; + std::string dataSessionFlag_; + DCStreamType streamType_; +}; + +class DCameraChannelInfo { +public: + std::string sourceDevId_; + std::vector detail_; +}; + +class DCameraChannelInfoCmd { +public: + std::string type_; + std::string dhId_; + std::string command_; + std::shared_ptr value_; + +public: + int32_t Marshal(std::string& jsonStr); + int32_t Unmarshal(const std::string& jsonStr); +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/base/include/dcamera_event_cmd.h b/services/cameraservice/base/include/dcamera_event_cmd.h new file mode 100644 index 0000000000000000000000000000000000000000..cf9406039e04d50dfcaa19b66df10ff13a9dd8ef --- /dev/null +++ b/services/cameraservice/base/include/dcamera_event_cmd.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_DCAMERA_EVENT_H +#define OHOS_DCAMERA_EVENT_H + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class DCameraEvent { +public: + int32_t eventType_; + int32_t eventResult_; + std::string eventContent_; +}; + +class DCameraEventCmd { +public: + std::string type_; + std::string dhId_; + std::string command_; + std::shared_ptr value_; + +public: + int32_t Marshal(std::string& jsonStr); + int32_t Unmarshal(const std::string& jsonStr); +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/base/include/dcamera_info_cmd.h b/services/cameraservice/base/include/dcamera_info_cmd.h new file mode 100644 index 0000000000000000000000000000000000000000..1519de6fec5335fa63863a17ddd560f5ecb5bd40 --- /dev/null +++ b/services/cameraservice/base/include/dcamera_info_cmd.h @@ -0,0 +1,48 @@ +/* + * 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_DCAMERA_INFO_H +#define OHOS_DCAMERA_INFO_H + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +enum { + DCAMERA_LOCAL_CLOSE = 0, + DCAMERA_LOCAL_OPEN = 1, +}; + +class DCameraInfo { +public: + int32_t state_; +}; + +class DCameraInfoCmd { +public: + std::string type_; + std::string dhId_; + std::string command_; + std::shared_ptr value_; + +public: + int32_t Marshal(std::string& jsonStr); + int32_t Unmarshal(const std::string& jsonStr); +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/base/include/dcamera_metadata_setting_cmd.h b/services/cameraservice/base/include/dcamera_metadata_setting_cmd.h new file mode 100644 index 0000000000000000000000000000000000000000..b6ea22e0ec8ffc2eff84e8ce0565a63b7dcbfd38 --- /dev/null +++ b/services/cameraservice/base/include/dcamera_metadata_setting_cmd.h @@ -0,0 +1,36 @@ +/* + * 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_DCAMERA_METADATA_SETTING_H +#define OHOS_DCAMERA_METADATA_SETTING_H + +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraMetadataSettingCmd { +public: + std::string type_; + std::string dhId_; + std::string command_; + std::vector> value_; + +public: + int32_t Marshal(std::string& jsonStr); + int32_t Unmarshal(const std::string& jsonStr); +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/base/include/dcamera_open_info_cmd.h b/services/cameraservice/base/include/dcamera_open_info_cmd.h new file mode 100644 index 0000000000000000000000000000000000000000..eeda26446ef9d0193e8979daea14b66e7ca778df --- /dev/null +++ b/services/cameraservice/base/include/dcamera_open_info_cmd.h @@ -0,0 +1,46 @@ +/* + * 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_DCAMERA_OPEN_INFO_H +#define OHOS_DCAMERA_OPEN_INFO_H + +#include +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class DCameraOpenInfo { +public: + DCameraOpenInfo() {} + DCameraOpenInfo(std::string sourceDevId) : sourceDevId_(sourceDevId) {} + ~DCameraOpenInfo() = default; + std::string sourceDevId_; +}; + +class DCameraOpenInfoCmd { +public: + std::string type_; + std::string dhId_; + std::string command_; + std::shared_ptr value_; + +public: + int32_t Marshal(std::string& jsonStr); + int32_t Unmarshal(const std::string& jsonStr); +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/base/include/dcamera_protocol.h b/services/cameraservice/base/include/dcamera_protocol.h new file mode 100644 index 0000000000000000000000000000000000000000..7cbdb4b7d267610834900a66e60634478c8e9699 --- /dev/null +++ b/services/cameraservice/base/include/dcamera_protocol.h @@ -0,0 +1,37 @@ +/* + * 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_DCAMERA_PROTOCOL_H +#define OHOS_DCAMERA_PROTOCOL_H + +#include + +namespace OHOS { +namespace DistributedHardware { +static const std::string DCAMERA_PROTOCOL_TYPE_MESSAGE = "MESSAGE"; +static const std::string DCAMERA_PROTOCOL_TYPE_OPERATION = "OPERATION"; + +static const std::string DCAMERA_PROTOCOL_CMD_GET_INFO = "GET_INFO"; +static const std::string DCAMERA_PROTOCOL_CMD_CHAN_NEG = "CHANNEL_NEG"; +static const std::string DCAMERA_PROTOCOL_CMD_UPDATE_METADATA = "UPDATE_METADATA"; +static const std::string DCAMERA_PROTOCOL_CMD_METADATA_RESULT = "METADATA_RESULT"; +static const std::string DCAMERA_PROTOCOL_CMD_STATE_NOTIFY = "STATE_NOTIFY"; +static const std::string DCAMERA_PROTOCOL_CMD_CAPTURE = "CAPTURE"; +static const std::string DCAMERA_PROTOCOL_CMD_STOP_CAPTURE = "STOP_CAPTURE"; +static const std::string DCAMERA_PROTOCOL_CMD_OPEN_CHANNEL = "OPEN_CHANNEL"; +static const std::string DCAMERA_PROTOCOL_CMD_CLOSE_CHANNEL = "CLOSE_CHANNEL"; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/base/include/icamera_controller.h b/services/cameraservice/base/include/icamera_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..47da557a03e11eed80dfca783d847ff62cef2671 --- /dev/null +++ b/services/cameraservice/base/include/icamera_controller.h @@ -0,0 +1,45 @@ +/* + * 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_ICAMERA_CONTROLLER_H +#define OHOS_ICAMERA_CONTROLLER_H +#include "dcamera_capture_info_cmd.h" +#include "dcamera_channel_info_cmd.h" +#include "dcamera_event_cmd.h" +#include "dcamera_info_cmd.h" +#include "dcamera_index.h" +#include "dcamera_open_info_cmd.h" + +namespace OHOS { +namespace DistributedHardware { +class ICameraController { +public: + ICameraController() = default; + virtual ~ICameraController() = default; + + virtual int32_t StartCapture(std::vector>& captureInfos) = 0; + virtual int32_t StopCapture() = 0; + virtual int32_t ChannelNeg(std::shared_ptr& info) = 0; + virtual int32_t DCameraNotify(std::shared_ptr& events) = 0; + virtual int32_t UpdateSettings(std::vector>& settings) = 0; + virtual int32_t GetCameraInfo(std::shared_ptr& camInfo) = 0; + virtual int32_t OpenChannel(std::shared_ptr& openInfo) = 0; + virtual int32_t CloseChannel() = 0; + virtual int32_t Init(std::vector& indexs) = 0; + virtual int32_t UnInit() = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/base/src/dcamera_capture_info_cmd.cpp b/services/cameraservice/base/src/dcamera_capture_info_cmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d5665dc8e5275355fa2252b6dae577e3740e44d --- /dev/null +++ b/services/cameraservice/base/src/dcamera_capture_info_cmd.cpp @@ -0,0 +1,170 @@ +/* + * 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 "dcamera_capture_info_cmd.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraCaptureInfoCmd::Marshal(std::string& jsonStr) +{ + Json::Value rootValue; + rootValue["Type"] = Json::Value(type_); + rootValue["dhId"] = Json::Value(dhId_); + rootValue["Command"] = Json::Value(command_); + Json::Value captureInfos; + for (auto iter = value_.begin(); iter != value_.end(); iter++) { + Json::Value captureInfo; + std::shared_ptr capture = *iter; + captureInfo["Width"] = Json::Value(capture->width_); + captureInfo["Height"] = Json::Value(capture->height_); + captureInfo["Format"] = Json::Value(capture->format_); + captureInfo["DataSpace"] = Json::Value(capture->dataspace_); + captureInfo["IsCapture"] = Json::Value(capture->isCapture_); + captureInfo["EncodeType"] = Json::Value(capture->encodeType_); + captureInfo["StreamType"] = Json::Value(capture->streamType_); + + Json::Value captureSettings; + for (auto settingIter = capture->captureSettings_.begin(); + settingIter != capture->captureSettings_.end(); settingIter++) { + Json::Value captureSetting; + captureSetting["SettingType"] = Json::Value((*settingIter)->type_); + captureSetting["SettingValue"] = Json::Value((*settingIter)->value_); + captureSettings.append(captureSetting); + } + + captureInfo["CaptureSettings"] = captureSettings; + captureInfos.append(captureInfo); + } + + rootValue["Value"] = captureInfos; + jsonStr = rootValue.toStyledString(); + return DCAMERA_OK; +} + +int32_t DCameraCaptureInfoCmd::Unmarshal(const std::string& jsonStr) +{ + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &rootValue, &errs) || + !rootValue.isObject()) { + return DCAMERA_BAD_VALUE; + } + + if (!rootValue.isMember("Type") || !rootValue["Type"].isString()) { + return DCAMERA_BAD_VALUE; + } + type_ = rootValue["Type"].asString(); + + if (!rootValue.isMember("dhId") || !rootValue["dhId"].isString()) { + return DCAMERA_BAD_VALUE; + } + dhId_ = rootValue["dhId"].asString(); + + if (!rootValue.isMember("Command") || !rootValue["Command"].isString()) { + return DCAMERA_BAD_VALUE; + } + command_ = rootValue["Command"].asString(); + + if (!rootValue.isMember("Value") || !rootValue["Value"].isArray()) { + return DCAMERA_BAD_VALUE; + } + + int32_t ret = UmarshalValue(rootValue); + if (ret != DCAMERA_OK) { + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraCaptureInfoCmd::UmarshalValue(Json::Value& rootValue) +{ + for (Json::ArrayIndex i = 0; i < rootValue["Value"].size(); i++) { + Json::Value valueJson = rootValue["Value"][i]; + std::shared_ptr captureInfo = std::make_shared(); + if (!valueJson.isMember("Width") || !valueJson["Width"].isInt()) { + return DCAMERA_BAD_VALUE; + } + captureInfo->width_ = valueJson["Width"].asInt(); + + if (!valueJson.isMember("Height") || !valueJson["Height"].isInt()) { + return DCAMERA_BAD_VALUE; + } + captureInfo->height_ = valueJson["Height"].asInt(); + + if (!valueJson.isMember("Format") || !valueJson["Format"].isInt()) { + return DCAMERA_BAD_VALUE; + } + captureInfo->format_ = valueJson["Format"].asInt(); + + if (!valueJson.isMember("DataSpace") || !valueJson["DataSpace"].isInt()) { + return DCAMERA_BAD_VALUE; + } + captureInfo->dataspace_ = valueJson["DataSpace"].asInt(); + + if (!valueJson.isMember("IsCapture") || !valueJson["IsCapture"].isBool()) { + return DCAMERA_BAD_VALUE; + } + captureInfo->isCapture_ = valueJson["IsCapture"].asBool(); + + if (!valueJson.isMember("EncodeType") || !valueJson["EncodeType"].isInt()) { + return DCAMERA_BAD_VALUE; + } + captureInfo->encodeType_ = (DCEncodeType)valueJson["EncodeType"].asInt(); + + if (!valueJson.isMember("StreamType") || !valueJson["StreamType"].isInt()) { + return DCAMERA_BAD_VALUE; + } + captureInfo->streamType_ = (DCStreamType)valueJson["StreamType"].asInt(); + + if (!valueJson.isMember("CaptureSettings") || !valueJson["CaptureSettings"].isArray()) { + return DCAMERA_BAD_VALUE; + } + + int32_t ret = UmarshalSettings(valueJson, captureInfo); + if (ret != DCAMERA_OK) { + return ret; + } + value_.push_back(captureInfo); + } + return DCAMERA_OK; +} + +int32_t DCameraCaptureInfoCmd::UmarshalSettings(Json::Value& valueJson, + std::shared_ptr& captureInfo) +{ + for (Json::ArrayIndex j = 0; j < valueJson["CaptureSettings"].size(); j++) { + Json::Value settingJson = valueJson["CaptureSettings"][j]; + if (!settingJson.isMember("SettingType") || !settingJson["SettingType"].isInt()) { + return DCAMERA_BAD_VALUE; + } + if (!settingJson.isMember("SettingValue") || !settingJson["SettingValue"].isString()) { + return DCAMERA_BAD_VALUE; + } + std::shared_ptr setting = std::make_shared(); + setting->type_ = (DCSettingsType)settingJson["SettingType"].asInt(); + setting->value_ = settingJson["SettingValue"].asString(); + captureInfo->captureSettings_.push_back(setting); + } + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/base/src/dcamera_channel_info_cmd.cpp b/services/cameraservice/base/src/dcamera_channel_info_cmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..20adf00af29debac9cb79d7e10827570974d2f62 --- /dev/null +++ b/services/cameraservice/base/src/dcamera_channel_info_cmd.cpp @@ -0,0 +1,108 @@ +/* + * 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 "dcamera_channel_info_cmd.h" + +#include "json/json.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraChannelInfoCmd::Marshal(std::string& jsonStr) +{ + Json::Value rootValue; + rootValue["Type"] = Json::Value(type_); + rootValue["dhId"] = Json::Value(dhId_); + rootValue["Command"] = Json::Value(command_); + + Json::Value channelInfo; + channelInfo["SourceDevId"] = Json::Value(value_->sourceDevId_); + Json::Value details; + for (auto iter = value_->detail_.begin(); iter != value_->detail_.end(); iter++) { + Json::Value detail; + detail["DataSessionFlag"] = Json::Value(iter->dataSessionFlag_); + detail["StreamType"] = Json::Value(iter->streamType_); + details.append(detail); + } + channelInfo["Detail"] = details; + rootValue["Value"] = channelInfo; + + jsonStr = rootValue.toStyledString(); + return DCAMERA_OK; +} + +int32_t DCameraChannelInfoCmd::Unmarshal(const std::string& jsonStr) +{ + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &rootValue, &errs) || + !rootValue.isObject()) { + return DCAMERA_BAD_VALUE; + } + + if (!rootValue.isMember("Type") || !rootValue["Type"].isString()) { + return DCAMERA_BAD_VALUE; + } + type_ = rootValue["Type"].asString(); + + if (!rootValue.isMember("dhId") || !rootValue["dhId"].isString()) { + return DCAMERA_BAD_VALUE; + } + dhId_ = rootValue["dhId"].asString(); + + if (!rootValue.isMember("Command") || !rootValue["Command"].isString()) { + return DCAMERA_BAD_VALUE; + } + command_ = rootValue["Command"].asString(); + + if (!rootValue.isMember("Value") || !rootValue["Value"].isObject()) { + return DCAMERA_BAD_VALUE; + } + Json::Value valueJson = rootValue["Value"]; + + if (!valueJson.isMember("SourceDevId") || !valueJson["SourceDevId"].isString()) { + return DCAMERA_BAD_VALUE; + } + std::shared_ptr channelInfo = std::make_shared(); + channelInfo->sourceDevId_ = valueJson["SourceDevId"].asString(); + + if (!valueJson.isMember("Detail") || !valueJson["Detail"].isArray()) { + return DCAMERA_BAD_VALUE; + } + + for (Json::ArrayIndex i = 0; i < valueJson["Detail"].size(); i++) { + Json::Value detailJson = valueJson["Detail"][i]; + DCameraChannelDetail channelDetail; + if (!detailJson.isMember("DataSessionFlag") || !detailJson["DataSessionFlag"].isString()) { + return DCAMERA_BAD_VALUE; + } + if (!detailJson.isMember("StreamType") || !detailJson["StreamType"].isInt()) { + return DCAMERA_BAD_VALUE; + } + channelDetail.dataSessionFlag_ = detailJson["DataSessionFlag"].asString(); + channelDetail.streamType_ = (DCStreamType)detailJson["StreamType"].asInt(); + channelInfo->detail_.push_back(channelDetail); + } + value_ = channelInfo; + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/base/src/dcamera_event_cmd.cpp b/services/cameraservice/base/src/dcamera_event_cmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7629fa9ab677987ce00d8e759d5351a897cd736 --- /dev/null +++ b/services/cameraservice/base/src/dcamera_event_cmd.cpp @@ -0,0 +1,95 @@ +/* + * 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 "dcamera_event_cmd.h" + +#include "json/json.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraEventCmd::Marshal(std::string& jsonStr) +{ + Json::Value rootValue; + rootValue["Type"] = Json::Value(type_); + rootValue["dhId"] = Json::Value(dhId_); + rootValue["Command"] = Json::Value(command_); + + Json::Value event; + event["EventType"] = Json::Value(value_->eventType_); + event["EventResult"] = Json::Value(value_->eventResult_); + event["EventContent"] = Json::Value(value_->eventContent_); + rootValue["Value"] = event; + + jsonStr = rootValue.toStyledString(); + return DCAMERA_OK; +} + +int32_t DCameraEventCmd::Unmarshal(const std::string& jsonStr) +{ + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &rootValue, &errs) || + !rootValue.isObject()) { + return DCAMERA_BAD_VALUE; + } + + if (!rootValue.isMember("Type") || !rootValue["Type"].isString()) { + return DCAMERA_BAD_VALUE; + } + type_ = rootValue["Type"].asString(); + + if (!rootValue.isMember("dhId") || !rootValue["dhId"].isString()) { + return DCAMERA_BAD_VALUE; + } + dhId_ = rootValue["dhId"].asString(); + + if (!rootValue.isMember("Command") || !rootValue["Command"].isString()) { + return DCAMERA_BAD_VALUE; + } + command_ = rootValue["Command"].asString(); + + if (!rootValue.isMember("Value") || !rootValue["Value"].isObject()) { + return DCAMERA_BAD_VALUE; + } + Json::Value valueJson = rootValue["Value"]; + + if (!valueJson.isMember("EventType") || !valueJson["EventType"].isInt()) { + return DCAMERA_BAD_VALUE; + } + std::shared_ptr event = std::make_shared(); + event->eventType_ = valueJson["EventType"].asInt(); + + if (!valueJson.isMember("EventResult") || !valueJson["EventResult"].isInt()) { + return DCAMERA_BAD_VALUE; + } + event->eventResult_ = valueJson["EventResult"].asInt(); + + if (!valueJson.isMember("EventContent") || !valueJson["EventContent"].isString()) { + return DCAMERA_BAD_VALUE; + } + event->eventContent_ = valueJson["EventContent"].asString(); + + value_ = event; + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/base/src/dcamera_info_cmd.cpp b/services/cameraservice/base/src/dcamera_info_cmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee34a4b3ddedf1451b2a315a8844d9d1e3dac664 --- /dev/null +++ b/services/cameraservice/base/src/dcamera_info_cmd.cpp @@ -0,0 +1,83 @@ +/* + * 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 "dcamera_info_cmd.h" + +#include "json/json.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraInfoCmd::Marshal(std::string& jsonStr) +{ + Json::Value rootValue; + rootValue["Type"] = Json::Value(type_); + rootValue["dhId"] = Json::Value(dhId_); + rootValue["Command"] = Json::Value(command_); + + Json::Value info; + info["State"] = Json::Value(value_->state_); + rootValue["Value"] = info; + + jsonStr = rootValue.toStyledString(); + return DCAMERA_OK; +} + +int32_t DCameraInfoCmd::Unmarshal(const std::string& jsonStr) +{ + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &rootValue, &errs) || + !rootValue.isObject()) { + return DCAMERA_BAD_VALUE; + } + + if (!rootValue.isMember("Type") || !rootValue["Type"].isString()) { + return DCAMERA_BAD_VALUE; + } + type_ = rootValue["Type"].asString(); + + if (!rootValue.isMember("dhId") || !rootValue["dhId"].isString()) { + return DCAMERA_BAD_VALUE; + } + dhId_ = rootValue["dhId"].asString(); + + if (!rootValue.isMember("Command") || !rootValue["Command"].isString()) { + return DCAMERA_BAD_VALUE; + } + command_ = rootValue["Command"].asString(); + + if (!rootValue.isMember("Value") || !rootValue["Value"].isObject()) { + return DCAMERA_BAD_VALUE; + } + Json::Value valueJson = rootValue["Value"]; + + if (!valueJson.isMember("State") || !valueJson["State"].isInt()) { + return DCAMERA_BAD_VALUE; + } + std::shared_ptr info = std::make_shared(); + info->state_ = valueJson["State"].asInt(); + + value_ = info; + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/base/src/dcamera_metadata_setting_cmd.cpp b/services/cameraservice/base/src/dcamera_metadata_setting_cmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c11e677e029c02cf4b81f3379262d5365fc3bb1 --- /dev/null +++ b/services/cameraservice/base/src/dcamera_metadata_setting_cmd.cpp @@ -0,0 +1,93 @@ +/* + * 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 "dcamera_metadata_setting_cmd.h" + +#include "json/json.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraMetadataSettingCmd::Marshal(std::string& jsonStr) +{ + Json::Value rootValue; + rootValue["Type"] = Json::Value(type_); + rootValue["dhId"] = Json::Value(dhId_); + rootValue["Command"] = Json::Value(command_); + + Json::Value settings; + for (auto iter = value_.begin(); iter != value_.end(); iter++) { + Json::Value setting; + setting["SettingType"] = (*iter)->type_; + setting["SettingValue"] = (*iter)->value_; + settings.append(setting); + } + + rootValue["Value"] = settings; + jsonStr = rootValue.toStyledString(); + return DCAMERA_OK; +} + +int32_t DCameraMetadataSettingCmd::Unmarshal(const std::string& jsonStr) +{ + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &rootValue, &errs) || + !rootValue.isObject()) { + return DCAMERA_BAD_VALUE; + } + + if (!rootValue.isMember("Type") || !rootValue["Type"].isString()) { + return DCAMERA_BAD_VALUE; + } + type_ = rootValue["Type"].asString(); + + if (!rootValue.isMember("dhId") || !rootValue["dhId"].isString()) { + return DCAMERA_BAD_VALUE; + } + dhId_ = rootValue["dhId"].asString(); + + if (!rootValue.isMember("Command") || !rootValue["Command"].isString()) { + return DCAMERA_BAD_VALUE; + } + command_ = rootValue["Command"].asString(); + + if (!rootValue.isMember("Value") || !rootValue["Value"].isArray()) { + return DCAMERA_BAD_VALUE; + } + + for (Json::ArrayIndex i = 0; i < rootValue["Value"].size(); i++) { + Json::Value valueJsonEle = rootValue["Value"][i]; + if (!valueJsonEle.isMember("SettingType") || !valueJsonEle["SettingType"].isInt()) { + return DCAMERA_BAD_VALUE; + } + if (!valueJsonEle.isMember("SettingValue") || !valueJsonEle["SettingValue"].isString()) { + return DCAMERA_BAD_VALUE; + } + std::shared_ptr setting = std::make_shared(); + setting->type_ = (DCSettingsType)valueJsonEle["SettingType"].asInt(); + setting->value_ = valueJsonEle["SettingValue"].asString(); + value_.push_back(setting); + } + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/base/src/dcamera_open_info_cmd.cpp b/services/cameraservice/base/src/dcamera_open_info_cmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8024026592126f844e96f3c03757930fbf0efe1 --- /dev/null +++ b/services/cameraservice/base/src/dcamera_open_info_cmd.cpp @@ -0,0 +1,82 @@ +/* + * 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 "dcamera_open_info_cmd.h" + +#include "json/json.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraOpenInfoCmd::Marshal(std::string& jsonStr) +{ + Json::Value rootValue; + rootValue["Type"] = Json::Value(type_); + rootValue["dhId"] = Json::Value(dhId_); + rootValue["Command"] = Json::Value(command_); + + Json::Value openInfo; + openInfo["SourceDevId"] = Json::Value(value_->sourceDevId_); + rootValue["Value"] = openInfo; + + jsonStr = rootValue.toStyledString(); + return DCAMERA_OK; +} + +int32_t DCameraOpenInfoCmd::Unmarshal(const std::string& jsonStr) +{ + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &rootValue, &errs) || + !rootValue.isObject()) { + return DCAMERA_BAD_VALUE; + } + + if (!rootValue.isMember("Type") || !rootValue["Type"].isString()) { + return DCAMERA_BAD_VALUE; + } + type_ = rootValue["Type"].asString(); + + if (!rootValue.isMember("dhId") || !rootValue["dhId"].isString()) { + return DCAMERA_BAD_VALUE; + } + dhId_ = rootValue["dhId"].asString(); + + if (!rootValue.isMember("Command") || !rootValue["Command"].isString()) { + return DCAMERA_BAD_VALUE; + } + command_ = rootValue["Command"].asString(); + + if (!rootValue.isMember("Value") || !rootValue["Value"].isObject()) { + return DCAMERA_BAD_VALUE; + } + Json::Value valueJson = rootValue["Value"]; + + if (!valueJson.isMember("SourceDevId") || !valueJson["SourceDevId"].isString()) { + return DCAMERA_BAD_VALUE; + } + std::shared_ptr openInfo = std::make_shared(); + openInfo->sourceDevId_ = valueJson["SourceDevId"].asString(); + value_ = openInfo; + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/base/test/unittest/BUILD.gn b/services/cameraservice/base/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a92ba40f8c67b83114b0c949024e8fdae6ccaafa --- /dev/null +++ b/services/cameraservice/base/test/unittest/BUILD.gn @@ -0,0 +1,19 @@ +# 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. + +group("services_base_test") { + testonly = true + deps = [ + "common/dcameraprotocol:dcamera_protocol_test", + ] +} \ No newline at end of file diff --git a/services/cameraservice/base/test/unittest/common/dcameraprotocol/BUILD.gn b/services/cameraservice/base/test/unittest/common/dcameraprotocol/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f6e7b2ea642fe79e3e4d63cb47c8d24ebbeec511 --- /dev/null +++ b/services/cameraservice/base/test/unittest/common/dcameraprotocol/BUILD.gn @@ -0,0 +1,75 @@ +# 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. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") +module_out_path = "distributedcamera/dcamera_protocol_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "//drivers/peripheral/base", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + ] + + include_dirs += [ + "${innerkits_path}/native_cpp/camera_source/include", + "${innerkits_path}/native_cpp/camera_sink/include", + "${innerkits_path}/native_cpp/camera_source/include/callback", + "${services_path}/cameraservice/base/include", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${distributedcamera_hdf_path}/interfaces/include", + ] +} + +ohos_unittest("DCameraProtocolTest") { + module_out_path = module_out_path + + sources = [ + "dcamera_protocol_test.cpp" + ] + + configs = [ ":module_private_config" ] + + deps = [ + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "//utils/native/base:utils", + "${services_path}/cameraservice/sourceservice:distributed_camera_source" + ] + + external_deps = [ + "dsoftbus_standard:softbus_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DCameraProtocolTest\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dcamera_protocol_test") { + testonly = true + deps = [ ":DCameraProtocolTest" ] +} \ No newline at end of file diff --git a/services/cameraservice/base/test/unittest/common/dcameraprotocol/dcamera_protocol_test.cpp b/services/cameraservice/base/test/unittest/common/dcameraprotocol/dcamera_protocol_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8527053a6086ec90e66f03a2ff03642ad222f7ef --- /dev/null +++ b/services/cameraservice/base/test/unittest/common/dcameraprotocol/dcamera_protocol_test.cpp @@ -0,0 +1,198 @@ +/* + * 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 +#include + +#include "anonymous_string.h" +#include "distributed_hardware_log.h" + +#include "dcamera_capture_info_cmd.h" +#include "dcamera_channel_info_cmd.h" +#include "dcamera_event_cmd.h" +#include "dcamera_info_cmd.h" +#include "dcamera_metadata_setting_cmd.h" +#include "dcamera_protocol.h" +#include "dcamera_utils_tools.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraProtocolTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +static std::string g_testDeviceId; +static const std::string TEST_CAPTURE_INFO_CMD_JSON = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "CAPTURE", + "Value": [ + {"Width": 1920, "Height": 1080, "Format": 1, "DataSpace": 1, + "IsCapture":true, "EncodeType": 1, "StreamType": 1, + "CaptureSettings": [{"SettingType": 1, "SettingValue": "TestSetting"}]} + ] +})"; + +static const std::string TEST_CHANNEL_INFO_CMD_JSON = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "CHANNEL_NEG", + "Value": {"SourceDevId": "TestDevId", "Detail": [{"DataSessionFlag": "TestFlag", "StreamType": 1}]} +})"; + +static const std::string TEST_EVENT_CMD_JSON = R"({ + "Type": "MESSAGE", + "dhId": "camrea_0", + "Command": "STATE_NOTIFY", + "Value": {"EventType": 1, "EventResult": 1, "EventContent": "TestContent"} +})"; + +static const std::string TEST_INFO_CMD_JSON = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "GET_INFO", + "Value": {"State": 1} +})"; + +static const std::string TEST_METADATA_SETTING_CMD_JSON = R"({ + "Type": "MESSAGE", + "dhId": "camrea_0", + "Command": "UPDATE_METADATA", + "Value": [{"SettingType": 1, "SettingValue": "TestSetting"}] +})"; + +void DCameraProtocolTest::SetUpTestCase(void) +{ + GetLocalDeviceNetworkId(g_testDeviceId); +} + +void DCameraProtocolTest::TearDownTestCase(void) +{ +} + +void DCameraProtocolTest::SetUp(void) +{ +} + +void DCameraProtocolTest::TearDown(void) +{ +} + +/** + * @tc.name: dcamera_protocol_test_001 + * @tc.desc: Verify Get ServiceAbility. + * @tc.type: FUNC + * @tc.require: AR000GK6MH + */ +HWTEST_F(DCameraProtocolTest, dcamera_protocol_test_001, TestSize.Level1) +{ + int32_t ret = DCAMERA_OK; + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_protocol_test_002 + * @tc.desc: Verify CaptureInfoCmd Json. + * @tc.type: FUNC + * @tc.require: AR000GK6MH + */ +HWTEST_F(DCameraProtocolTest, dcamera_protocol_test_002, TestSize.Level1) +{ + DCameraCaptureInfoCmd cmd; + int32_t ret = cmd.Unmarshal(TEST_CAPTURE_INFO_CMD_JSON); + EXPECT_EQ(DCAMERA_OK, ret); + + std::string jsonStr; + ret = cmd.Marshal(jsonStr); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_protocol_test_003 + * @tc.desc: Verify ChannelInfoCmd Json. + * @tc.type: FUNC + * @tc.require: AR000GK6MI + */ +HWTEST_F(DCameraProtocolTest, dcamera_protocol_test_003, TestSize.Level1) +{ + DCameraChannelInfoCmd cmd; + int32_t ret = cmd.Unmarshal(TEST_CHANNEL_INFO_CMD_JSON); + EXPECT_EQ(DCAMERA_OK, ret); + + std::string jsonStr; + ret = cmd.Marshal(jsonStr); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_protocol_test_004 + * @tc.desc: Verify EventCmd Json. + * @tc.type: FUNC + * @tc.require: AR000GK6MI + */ +HWTEST_F(DCameraProtocolTest, dcamera_protocol_test_004, TestSize.Level1) +{ + DCameraEventCmd cmd; + int32_t ret = cmd.Unmarshal(TEST_EVENT_CMD_JSON); + EXPECT_EQ(DCAMERA_OK, ret); + + std::string jsonStr; + ret = cmd.Marshal(jsonStr); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_protocol_test_005 + * @tc.desc: Verify CameraInfoCmd Json. + * @tc.type: FUNC + * @tc.require: AR000GS3AA + */ +HWTEST_F(DCameraProtocolTest, dcamera_protocol_test_005, TestSize.Level1) +{ + DCameraInfoCmd cmd; + int32_t ret = cmd.Unmarshal(TEST_INFO_CMD_JSON); + EXPECT_EQ(DCAMERA_OK, ret); + + std::string jsonStr; + ret = cmd.Marshal(jsonStr); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_protocol_test_006 + * @tc.desc: Verify MetaDataSettingCmd Json. + * @tc.type: FUNC + * @tc.require: AR000GS3AA + */ +HWTEST_F(DCameraProtocolTest, dcamera_protocol_test_006, TestSize.Level1) +{ + DCameraMetadataSettingCmd cmd; + int32_t ret = cmd.Unmarshal(TEST_METADATA_SETTING_CMD_JSON); + EXPECT_EQ(DCAMERA_OK, ret); + + std::string jsonStr; + ret = cmd.Marshal(jsonStr); + EXPECT_EQ(DCAMERA_OK, ret); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/BUILD.gn b/services/cameraservice/cameraoperator/client/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c92d304e9351c440f74a0c02dc3cb17f40e7b3b5 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/BUILD.gn @@ -0,0 +1,85 @@ +# 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. + +import("//build/ohos.gni") +import("//build/ohos_var.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_client") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${graphicstandard_path}/frameworks/surface/include", + "${camerastandard_path}/frameworks/native/metadata/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/input", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/output", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/session", + "${camerastandard_path}/services/camera_service/binder/base/include", + "${camerastandard_path}/services/camera_service/binder/client/include", + "${camerastandard_path}/services/camera_service/binder/server/include", + "${camerastandard_path}/services/camera_service/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + ] + + include_dirs += [ + "include", + "include/callback", + "include/listener", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${distributedcamera_hdf_path}/interfaces/include", + "${services_path}/cameraservice/base/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "src/dcamera_client.cpp", + "src/callback/dcamera_input_callback.cpp", + "src/callback/dcamera_manager_callback.cpp", + "src/callback/dcamera_photo_callback.cpp", + "src/callback/dcamera_preview_callback.cpp", + "src/callback/dcamera_session_callback.cpp", + "src/callback/dcamera_video_callback.cpp", + "src/listener/dcamera_photo_surface_listener.cpp", + "src/listener/dcamera_video_surface_listener.cpp", + ] + + deps = [ + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "${graphicstandard_path}:libsurface", + "${camerastandard_path}/frameworks/native/camera:camera_framework", + "${camerastandard_path}/frameworks/native/metadata:metadata", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dcameraclient\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "multimedia_media_standard:media_client", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/callback/dcamera_input_callback.h b/services/cameraservice/cameraoperator/client/include/callback/dcamera_input_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..e29fcc708aeed4f2f490c3e267ce1ed358eb78cd --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/callback/dcamera_input_callback.h @@ -0,0 +1,35 @@ +/* + * 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_DCAMERA_INPUT_CALLBACK_H +#define OHOS_DCAMERA_INPUT_CALLBACK_H + +#include "camera_input.h" + +#include "icamera_operator.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraInputCallback : public CameraStandard::ErrorCallback { +public: + explicit DCameraInputCallback(const std::shared_ptr& callback); + void OnError(const int32_t errorType, const int32_t errorMsg) const override; + +private: + std::shared_ptr callback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_INPUT_CALLBACK_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/callback/dcamera_manager_callback.h b/services/cameraservice/cameraoperator/client/include/callback/dcamera_manager_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..b6f35f3f9032c5f2916aeb5281d70c6267580e72 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/callback/dcamera_manager_callback.h @@ -0,0 +1,31 @@ +/* + * 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_DCAMERA_MANAGER_CALLBACK_H +#define OHOS_DCAMERA_MANAGER_CALLBACK_H + +#include "camera_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraManagerCallback : public CameraStandard::CameraManagerCallback { +public: + void OnCameraStatusChanged(const CameraStandard::CameraStatusInfo &cameraStatusInfo) const override; + void OnFlashlightStatusChanged(const std::string &cameraID, + const CameraStandard::FlashlightStatus flashStatus) const override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_MANAGER_CALLBACK_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/callback/dcamera_photo_callback.h b/services/cameraservice/cameraoperator/client/include/callback/dcamera_photo_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..5cc4804db18f43a51e6d74899bb9014d6078ff08 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/callback/dcamera_photo_callback.h @@ -0,0 +1,38 @@ +/* + * 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_DCAMERA_PHOTO_CALLBACK_H +#define OHOS_DCAMERA_PHOTO_CALLBACK_H + +#include "photo_output.h" + +#include "icamera_operator.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraPhotoCallback : public CameraStandard::PhotoCallback { +public: + explicit DCameraPhotoCallback(const std::shared_ptr& callback); + void OnCaptureStarted(const int32_t captureID) const override; + void OnCaptureEnded(const int32_t captureID, int32_t frameCount) const override; + void OnFrameShutter(const int32_t captureId, const uint64_t timestamp) const override; + void OnCaptureError(const int32_t captureId, const int32_t errorCode) const override; + +private: + std::shared_ptr callback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_PHOTO_CALLBACK_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/callback/dcamera_preview_callback.h b/services/cameraservice/cameraoperator/client/include/callback/dcamera_preview_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..c38caccf01ca7675d1483872b2944c4507692946 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/callback/dcamera_preview_callback.h @@ -0,0 +1,37 @@ +/* + * 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_DCAMERA_PREVIEW_CALLBACK_H +#define OHOS_DCAMERA_PREVIEW_CALLBACK_H + +#include "preview_output.h" + +#include "icamera_operator.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraPreviewCallback : public CameraStandard::PreviewCallback { +public: + explicit DCameraPreviewCallback(const std::shared_ptr& callback); + void OnFrameStarted() const override; + void OnFrameEnded(const int32_t frameCount) const override; + void OnError(const int32_t errorCode) const override; + +private: + std::shared_ptr callback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_PREVIEW_CALLBACK_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/callback/dcamera_session_callback.h b/services/cameraservice/cameraoperator/client/include/callback/dcamera_session_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..343d1c2ad5d6ceb6e1f88be3e7ac64c284d11c77 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/callback/dcamera_session_callback.h @@ -0,0 +1,35 @@ +/* + * 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_DCAMERA_SESSION_CALLBACK_H +#define OHOS_DCAMERA_SESSION_CALLBACK_H + +#include "capture_session.h" + +#include "icamera_operator.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSessionCallback : public CameraStandard::SessionCallback { +public: + explicit DCameraSessionCallback(const std::shared_ptr& callback); + void OnError(int32_t errorCode) override; + +private: + std::shared_ptr callback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SESSION_CALLBACK_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/callback/dcamera_video_callback.h b/services/cameraservice/cameraoperator/client/include/callback/dcamera_video_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..6f82f1599b8947877e39b0b2f7d59fa68680ddb3 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/callback/dcamera_video_callback.h @@ -0,0 +1,37 @@ +/* + * 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_DCAMERA_VIDEO_CALLBACK_H +#define OHOS_DCAMERA_VIDEO_CALLBACK_H + +#include "video_output.h" + +#include "icamera_operator.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraVideoCallback : public CameraStandard::VideoCallback { +public: + explicit DCameraVideoCallback(const std::shared_ptr& callback); + void OnFrameStarted() const override; + void OnFrameEnded(const int32_t frameCount) const override; + void OnError(const int32_t errorCode) const override; + +private: + std::shared_ptr callback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_VIDEO_CALLBACK_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/dcamera_client.h b/services/cameraservice/cameraoperator/client/include/dcamera_client.h new file mode 100644 index 0000000000000000000000000000000000000000..73591141e0da342f324f07299fe3d723f79fa925 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/dcamera_client.h @@ -0,0 +1,77 @@ +/* + * 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_DCAMERA_CLIENT_H +#define OHOS_DCAMERA_CLIENT_H + +#include "icamera_operator.h" + +#include "camera_info.h" +#include "camera_input.h" +#include "camera_manager.h" +#include "capture_input.h" +#include "capture_output.h" +#include "capture_session.h" +#include "photo_output.h" +#include "preview_output.h" +#include "video_output.h" + +#include "dcamera_photo_surface_listener.h" +#include "dcamera_video_surface_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraClient : public ICameraOperator { +public: + explicit DCameraClient(const std::string& dhId); + ~DCameraClient(); + + int32_t Init() override; + int32_t UnInit() override; + int32_t UpdateSettings(std::vector>& settings) override; + int32_t StartCapture(std::vector>& captureInfos) override; + int32_t StopCapture() override; + int32_t SetStateCallback(std::shared_ptr& callback) override; + int32_t SetResultCallback(std::shared_ptr& callback) override; + +private: + int32_t ConfigCaptureSession(std::vector>& captureInfos); + int32_t ConfigCaptureSessionInner(); + int32_t CreateCaptureOutput(std::vector>& captureInfos); + int32_t CreatePhotoOutput(std::shared_ptr& info); + int32_t CreateVideoOutput(std::shared_ptr& info); + int32_t StartCaptureInner(std::shared_ptr& info); + int32_t StartPhotoOutput(std::shared_ptr& info); + int32_t StartVideoOutput(); + + bool isInit_; + std::string cameraId_; + sptr photoSurface_; + sptr videoSurface_; + sptr cameraInfo_; + sptr cameraManager_; + sptr captureSession_; + sptr cameraInput_; + sptr photoOutput_; + sptr previewOutput_; + sptr videoOutput_; + std::shared_ptr stateCallback_; + std::shared_ptr resultCallback_; + std::shared_ptr photoListener_; + std::shared_ptr videoListener_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_CLIENT_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/icamera_operator.h b/services/cameraservice/cameraoperator/client/include/icamera_operator.h new file mode 100644 index 0000000000000000000000000000000000000000..6f787d36bcba80d93580a8c0ed10ec71a737997b --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/icamera_operator.h @@ -0,0 +1,64 @@ +/* + * 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_ICAMERA_OPERATOR_H +#define OHOS_ICAMERA_OPERATOR_H + +#include +#include +#include +#include + +#include "data_buffer.h" +#include "dcamera_capture_info_cmd.h" +#include "dcamera_event_cmd.h" +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class StateCallback { +public: + StateCallback() = default; + virtual ~StateCallback() = default; + + virtual void OnStateChanged(std::shared_ptr& event) = 0; + virtual void OnMetadataResult() = 0; +}; + +class ResultCallback { +public: + ResultCallback() = default; + virtual ~ResultCallback() = default; + + virtual void OnPhotoResult(std::shared_ptr& buffer) = 0; + virtual void OnVideoResult(std::shared_ptr& buffer) = 0; +}; + +class ICameraOperator { +public: + ICameraOperator() = default; + virtual ~ICameraOperator() = default; + + virtual int32_t Init() = 0; + virtual int32_t UnInit() = 0; + virtual int32_t UpdateSettings(std::vector>& settings) = 0; + virtual int32_t StartCapture(std::vector>& captureInfos) = 0; + virtual int32_t StopCapture() = 0; + virtual int32_t SetStateCallback(std::shared_ptr& callback) = 0; + virtual int32_t SetResultCallback(std::shared_ptr& callback) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_ICAMERA_OPERATOR_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/listener/dcamera_photo_surface_listener.h b/services/cameraservice/cameraoperator/client/include/listener/dcamera_photo_surface_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..54a9e50cb690340cb1d279a4919df5a4baf3a480 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/listener/dcamera_photo_surface_listener.h @@ -0,0 +1,36 @@ +/* + * 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_DCAMERA_PHOTO_SURFACE_LISTENER_H +#define OHOS_DCAMERA_PHOTO_SURFACE_LISTENER_H + +#include "surface.h" +#include "icamera_operator.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraPhotoSurfaceListener : public IBufferConsumerListener { +public: + DCameraPhotoSurfaceListener(const sptr& surface, + const std::shared_ptr& callback); + void OnBufferAvailable() override; + +private: + sptr surface_; + std::shared_ptr callback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_PHOTO_SURFACE_LISTENER_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/include/listener/dcamera_video_surface_listener.h b/services/cameraservice/cameraoperator/client/include/listener/dcamera_video_surface_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..c1bae897605c0f43e6594d4359f56b06cfec8e43 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/include/listener/dcamera_video_surface_listener.h @@ -0,0 +1,36 @@ +/* + * 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_DCAMERA_VIDEO_SURFACE_LISTENER_H +#define OHOS_DCAMERA_VIDEO_SURFACE_LISTENER_H + +#include "surface.h" +#include "icamera_operator.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraVideoSurfaceListener : public IBufferConsumerListener { +public: + DCameraVideoSurfaceListener(const sptr& surface, + const std::shared_ptr& callback); + void OnBufferAvailable() override; + +private: + sptr surface_; + std::shared_ptr callback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_VIDEO_SURFACE_LISTENER_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/src/callback/dcamera_input_callback.cpp b/services/cameraservice/cameraoperator/client/src/callback/dcamera_input_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e915aac55ee7b61f32aa0a088c3730570b8bece4 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/callback/dcamera_input_callback.cpp @@ -0,0 +1,41 @@ +/* + * 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 "dcamera_input_callback.h" + +#include "distributed_camera_constants.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraInputCallback::DCameraInputCallback(const std::shared_ptr& callback) : callback_(callback) +{ +} + +void DCameraInputCallback::OnError(const int32_t errorType, const int32_t errorMsg) const +{ + DHLOGE("DCameraInputCallback::OnError, errorType: %d, errorMsg: %d", errorType, errorMsg); + if (callback_ == nullptr) { + DHLOGE("DCameraInputCallback::OnError StateCallback is null"); + return; + } + + std::shared_ptr event = std::make_shared(); + event->eventType_ = DCAMERA_MESSAGE; + event->eventResult_ = DCAMERA_EVENT_CAMERA_ERROR; + callback_->OnStateChanged(event); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/src/callback/dcamera_manager_callback.cpp b/services/cameraservice/cameraoperator/client/src/callback/dcamera_manager_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f3865d72d16cbec413c609890bd2eae5341987c --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/callback/dcamera_manager_callback.cpp @@ -0,0 +1,36 @@ +/* + * 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 "dcamera_manager_callback.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +void DCameraManagerCallback::OnCameraStatusChanged(const CameraStandard::CameraStatusInfo &cameraStatusInfo) const +{ + DHLOGI("DCameraManagerCallback::OnCameraStatusChanged, cameraStatus: %d", cameraStatusInfo.cameraStatus); +} + +void DCameraManagerCallback::OnFlashlightStatusChanged(const std::string &cameraID, + const CameraStandard::FlashlightStatus flashStatus) const +{ + DHLOGI("DCameraManagerCallback::OnFlashlightStatusChanged, cameraID: %s, flashStatus: %d", + GetAnonyString(cameraID).c_str(), flashStatus); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/src/callback/dcamera_photo_callback.cpp b/services/cameraservice/cameraoperator/client/src/callback/dcamera_photo_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62f283ef5082f459a6cd5ae741f1ffef0a13d853 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/callback/dcamera_photo_callback.cpp @@ -0,0 +1,56 @@ +/* + * 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 "dcamera_photo_callback.h" + +#include "distributed_camera_constants.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraPhotoCallback::DCameraPhotoCallback(const std::shared_ptr& callback) : callback_(callback) +{ +} + +void DCameraPhotoCallback::OnCaptureStarted(const int32_t captureID) const +{ + DHLOGI("DCameraPhotoCallback::OnCaptureStarted, captureID: %d", captureID); +} + +void DCameraPhotoCallback::OnCaptureEnded(const int32_t captureID, const int32_t frameCount) const +{ + DHLOGI("DCameraPhotoCallback::OnCaptureEnded, captureID: %d, frameCount: %d", captureID, frameCount); +} + +void DCameraPhotoCallback::OnFrameShutter(const int32_t captureId, const uint64_t timestamp) const +{ + DHLOGI("DCameraPhotoCallback::OnFrameShutter, captureId: %d, timestamp: %llu", captureId, timestamp); +} + +void DCameraPhotoCallback::OnCaptureError(const int32_t captureId, const int32_t errorCode) const +{ + DHLOGE("DCameraPhotoCallback::OnCaptureError, captureId: %d, errorCode: %d", captureId, errorCode); + if (callback_ == nullptr) { + DHLOGE("DCameraPhotoCallback::OnCaptureError StateCallback is null"); + return; + } + + std::shared_ptr event = std::make_shared(); + event->eventType_ = DCAMERA_MESSAGE; + event->eventResult_ = DCAMERA_EVENT_CAMERA_ERROR; + callback_->OnStateChanged(event); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/src/callback/dcamera_preview_callback.cpp b/services/cameraservice/cameraoperator/client/src/callback/dcamera_preview_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1eb36092b0fb089038972ffb14b6b7b65eb5fd08 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/callback/dcamera_preview_callback.cpp @@ -0,0 +1,51 @@ +/* + * 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 "dcamera_preview_callback.h" + +#include "distributed_camera_constants.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraPreviewCallback::DCameraPreviewCallback(const std::shared_ptr& callback) : callback_(callback) +{ +} + +void DCameraPreviewCallback::OnFrameStarted() const +{ + DHLOGI("DCameraPreviewCallback::OnFrameStarted"); +} + +void DCameraPreviewCallback::OnFrameEnded(const int32_t frameCount) const +{ + DHLOGI("DCameraPreviewCallback::OnFrameEnded, frameCount: %d", frameCount); +} + +void DCameraPreviewCallback::OnError(const int32_t errorCode) const +{ + DHLOGE("DCameraPreviewCallback::OnError, errorCode: %d", errorCode); + if (callback_ == nullptr) { + DHLOGE("DCameraPreviewCallback::OnError StateCallback is null"); + return; + } + + std::shared_ptr event = std::make_shared(); + event->eventType_ = DCAMERA_MESSAGE; + event->eventResult_ = DCAMERA_EVENT_CAMERA_ERROR; + callback_->OnStateChanged(event); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/cameraservice/cameraoperator/client/src/callback/dcamera_session_callback.cpp b/services/cameraservice/cameraoperator/client/src/callback/dcamera_session_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d26fb922f89084c6464041c83f9a87429c705e6d --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/callback/dcamera_session_callback.cpp @@ -0,0 +1,41 @@ +/* + * 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 "dcamera_session_callback.h" + +#include "distributed_camera_constants.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSessionCallback::DCameraSessionCallback(const std::shared_ptr& callback) : callback_(callback) +{ +} + +void DCameraSessionCallback::OnError(int32_t errorCode) +{ + DHLOGE("DCameraSessionCallback::OnError, errorCode: %d", errorCode); + if (callback_ == nullptr) { + DHLOGE("DCameraSessionCallback::OnError StateCallback is null"); + return; + } + + std::shared_ptr event = std::make_shared(); + event->eventType_ = DCAMERA_MESSAGE; + event->eventResult_ = DCAMERA_EVENT_CAMERA_ERROR; + callback_->OnStateChanged(event); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/src/callback/dcamera_video_callback.cpp b/services/cameraservice/cameraoperator/client/src/callback/dcamera_video_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8adb9731a28fd2a4103e85a3d612dc05c60ebd79 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/callback/dcamera_video_callback.cpp @@ -0,0 +1,51 @@ +/* + * 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 "dcamera_video_callback.h" + +#include "distributed_camera_constants.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraVideoCallback::DCameraVideoCallback(const std::shared_ptr& callback) : callback_(callback) +{ +} + +void DCameraVideoCallback::OnFrameStarted() const +{ + DHLOGI("DCameraVideoCallback::OnFrameStarted"); +} + +void DCameraVideoCallback::OnFrameEnded(const int32_t frameCount) const +{ + DHLOGI("DCameraVideoCallback::OnFrameEnded, frameCount: %d", frameCount); +} + +void DCameraVideoCallback::OnError(const int32_t errorCode) const +{ + DHLOGE("DCameraVideoCallback::OnError, errorCode: %d", errorCode); + if (callback_ == nullptr) { + DHLOGE("DCameraVideoCallback StateCallback is null"); + return; + } + + std::shared_ptr event = std::make_shared(); + event->eventType_ = DCAMERA_MESSAGE; + event->eventResult_ = DCAMERA_EVENT_CAMERA_ERROR; + callback_->OnStateChanged(event); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/src/dcamera_client.cpp b/services/cameraservice/cameraoperator/client/src/dcamera_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e52b396661f3f4f80819086408c7166fe3accf3e --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/dcamera_client.cpp @@ -0,0 +1,437 @@ +/* + * 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 "dcamera_client.h" + +#include "anonymous_string.h" +#include "dcamera_input_callback.h" +#include "dcamera_manager_callback.h" +#include "dcamera_photo_callback.h" +#include "dcamera_session_callback.h" +#include "dcamera_utils_tools.h" +#include "dcamera_video_callback.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraClient::DCameraClient(const std::string& dhId) +{ + DHLOGI("DCameraClient Constructor dhId: %s", GetAnonyString(dhId).c_str()); + cameraId_ = dhId.substr(CAMERA_ID_PREFIX.size()); + isInit_ = false; +} + +DCameraClient::~DCameraClient() +{ + if (isInit_) { + UnInit(); + } +} + +int32_t DCameraClient::Init() +{ + DHLOGI("DCameraClient::Init cameraId: %s", GetAnonyString(cameraId_).c_str()); + cameraManager_ = CameraStandard::CameraManager::GetInstance(); + if (cameraManager_ == nullptr) { + DHLOGE("DCameraClient::Init cameraManager getInstance failed"); + return DCAMERA_BAD_VALUE; + } + cameraManager_->SetCallback(std::make_shared()); + + std::vector> cameraList = cameraManager_->GetCameras(); + DHLOGI("DCameraClient::Init camera size: %d", cameraList.size()); + for (auto& info : cameraList) { + if (info->GetID() == cameraId_) { + DHLOGI("DCameraClient::Init cameraInfo get id: %s", GetAnonyString(info->GetID()).c_str()); + cameraInfo_ = info; + break; + } + } + if (cameraInfo_ == nullptr) { + DHLOGE("DCameraClient::Init cameraInfo is null"); + return DCAMERA_BAD_VALUE; + } + + isInit_ = true; + DHLOGI("DCameraClient::Init %s success", GetAnonyString(cameraId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraClient::UnInit() +{ + DHLOGI("DCameraClient::UnInit cameraId: %s", GetAnonyString(cameraId_).c_str()); + if (cameraManager_ != nullptr) { + DHLOGI("DCameraClient::UnInit unregister cameraManager callback"); + cameraManager_->SetCallback(nullptr); + } + + isInit_ = false; + cameraInfo_ = nullptr; + cameraManager_ = nullptr; + DHLOGI("DCameraClient::UnInit %s success", GetAnonyString(cameraId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraClient::UpdateSettings(std::vector>& settings) +{ + DHLOGI("DCameraClient::UpdateCameraSettings cameraId: %s", GetAnonyString(cameraId_).c_str()); + for (auto& setting : settings) { + switch (setting->type_) { + case UPDATE_METADATA: { + DHLOGI("DCameraClient::UpdateCameraSettings %s update metadata settings", + GetAnonyString(cameraId_).c_str()); + std::string metadataStr = Base64Decode(setting->value_); + int32_t ret = ((sptr &)cameraInput_)->SetCameraSettings(metadataStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::UpdateSettings %s update metadata settings failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + break; + } + default: { + DHLOGE("DCameraClient::UpdateSettings unknown setting type"); + break; + } + } + } + DHLOGI("DCameraClient::UpdateCameraSettings %s success", GetAnonyString(cameraId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraClient::StartCapture(std::vector>& captureInfos) +{ + DHLOGI("DCameraClient::StartCapture cameraId: %s", GetAnonyString(cameraId_).c_str()); + if ((photoOutput_ == nullptr) && (videoOutput_ == nullptr)) { + DHLOGI("DCameraClient::StartCapture %s config capture session", GetAnonyString(cameraId_).c_str()); + int32_t ret = ConfigCaptureSession(captureInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::StartCapture config capture session failed, cameraId: %s, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + } + + for (auto& info : captureInfos) { + if (!(info->isCapture_)) { + continue; + } + int32_t ret = StartCaptureInner(info); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::StartCapture failed, cameraId: %s, ret: %d", GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + } + DHLOGI("DCameraClient::StartCapture %s success", GetAnonyString(cameraId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraClient::StopCapture() +{ + DHLOGI("DCameraClient::StopCapture cameraId: %s", GetAnonyString(cameraId_).c_str()); + if (videoOutput_ != nullptr) { + DHLOGI("DCameraClient::StopCapture %s stop videoOutput", GetAnonyString(cameraId_).c_str()); + int32_t ret = ((sptr &)videoOutput_)->Stop(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::StopCapture videoOutput stop failed, cameraId: %s, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + } + } + + if (captureSession_ != nullptr) { + DHLOGI("DCameraClient::StopCapture %s stop captureSession", GetAnonyString(cameraId_).c_str()); + int32_t ret = captureSession_->Stop(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::StopCapture captureSession stop failed, cameraId: %s, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + } + DHLOGI("DCameraClient::StopCapture %s release captureSession", GetAnonyString(cameraId_).c_str()); + captureSession_->Release(); + } + + if (cameraInput_ != nullptr) { + DHLOGI("DCameraClient::StopCapture %s release cameraInput", GetAnonyString(cameraId_).c_str()); + cameraInput_->Release(); + } + + photoOutput_ = nullptr; + videoOutput_ = nullptr; + cameraInput_ = nullptr; + captureSession_ = nullptr; + DHLOGI("DCameraClient::StopCapture %s success", GetAnonyString(cameraId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraClient::SetStateCallback(std::shared_ptr& callback) +{ + DHLOGI("DCameraClient::SetStateCallback cameraId: %s", GetAnonyString(cameraId_).c_str()); + if (callback == nullptr) { + DHLOGE("DCameraClient::SetStateCallback %s unregistering state callback", GetAnonyString(cameraId_).c_str()); + } + stateCallback_ = callback; + return DCAMERA_OK; +} + +int32_t DCameraClient::SetResultCallback(std::shared_ptr& callback) +{ + DHLOGI("DCameraClient::SetResultCallback cameraId: %s", GetAnonyString(cameraId_).c_str()); + if (callback == nullptr) { + DHLOGE("DCameraClient::SetResultCallback %s unregistering result callback", GetAnonyString(cameraId_).c_str()); + } + resultCallback_ = callback; + return DCAMERA_OK; +} + +int32_t DCameraClient::ConfigCaptureSession(std::vector>& captureInfos) +{ + DHLOGI("DCameraClient::ConfigCaptureSession cameraId: %s", GetAnonyString(cameraId_).c_str()); + cameraInput_ = cameraManager_->CreateCameraInput(cameraInfo_); + if (cameraInput_ == nullptr) { + DHLOGE("DCameraClient::ConfigCaptureSession %s create cameraInput failed", GetAnonyString(cameraId_).c_str()); + return DCAMERA_BAD_VALUE; + } + std::shared_ptr inputCallback = std::make_shared(stateCallback_); + ((sptr &)cameraInput_)->SetErrorCallback(inputCallback); + + captureSession_ = cameraManager_->CreateCaptureSession(); + if (captureSession_ == nullptr) { + DHLOGE("DCameraClient::ConfigCaptureSession %s create captureSession failed", + GetAnonyString(cameraId_).c_str()); + return DCAMERA_BAD_VALUE; + } + captureSession_->SetCallback(std::make_shared(stateCallback_)); + + int32_t ret = CreateCaptureOutput(captureInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::ConfigCaptureSession create capture output failed, cameraId: %s, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + + return ConfigCaptureSessionInner(); +} + +int32_t DCameraClient::ConfigCaptureSessionInner() +{ + int32_t ret = captureSession_->BeginConfig(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::ConfigCaptureSession %s config captureSession failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + + ret = captureSession_->AddInput(cameraInput_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::ConfigCaptureSession %s add cameraInput to captureSession failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + + if (photoOutput_ != nullptr) { + ret = captureSession_->AddOutput(photoOutput_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::ConfigCaptureSession %s add photoOutput to captureSession failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + } + + if (videoOutput_ != nullptr) { + ret = captureSession_->AddOutput(videoOutput_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::ConfigCaptureSession %s add videoOutput to captureSession failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + } + + ret = captureSession_->CommitConfig(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::ConfigCaptureSession %s commit captureSession failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + + ret = captureSession_->Start(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::ConfigCaptureSession %s start captureSession failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + } + + DHLOGI("DCameraClient::ConfigCaptureSession %s success", GetAnonyString(cameraId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraClient::CreateCaptureOutput(std::vector>& captureInfos) +{ + if (captureInfos.empty()) { + DHLOGE("DCameraClient::CreateCaptureOutput no capture info, cameraId: %s", GetAnonyString(cameraId_).c_str()); + return DCAMERA_BAD_VALUE; + } + + for (auto& info : captureInfos) { + if (info->streamType_ == SNAPSHOT_FRAME) { + int32_t ret = CreatePhotoOutput(info); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::CreateCaptureOutput %s create photo output failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + } else if (info->streamType_ == CONTINUOUS_FRAME) { + int32_t ret = CreateVideoOutput(info); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::CreateCaptureOutput %s create video output failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + } else { + DHLOGE("DCameraClient::CreateCaptureOutput unknown stream type"); + return DCAMERA_BAD_VALUE; + } + } + return DCAMERA_OK; +} + +int32_t DCameraClient::CreatePhotoOutput(std::shared_ptr& info) +{ + DHLOGI("DCameraClient::CreatePhotoOutput camId: %s, width: %d, height: %d, format: %d, stream: %d, isCapture: %d", + GetAnonyString(cameraId_).c_str(), info->width_, info->height_, info->format_, + info->streamType_, info->isCapture_); + photoSurface_ = Surface::CreateSurfaceAsConsumer(); + photoSurface_->SetDefaultWidthAndHeight(info->width_, info->height_); + photoSurface_->SetUserData(CAMERA_SURFACE_FORMAT, std::to_string(info->format_)); + photoListener_ = std::make_shared(photoSurface_, resultCallback_); + photoSurface_->RegisterConsumerListener((sptr &)photoListener_); + photoOutput_ = cameraManager_->CreatePhotoOutput(photoSurface_); + if (photoOutput_ == nullptr) { + DHLOGE("DCameraClient::CreatePhotoOutput %s create photo output failed", GetAnonyString(cameraId_).c_str()); + return DCAMERA_BAD_VALUE; + } + std::shared_ptr photoCallback = std::make_shared(stateCallback_); + ((sptr &)photoOutput_)->SetCallback(photoCallback); + DHLOGI("DCameraClient::CreatePhotoOutput %s success", GetAnonyString(cameraId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraClient::CreateVideoOutput(std::shared_ptr& info) +{ + DHLOGI("DCameraClient::CreateVideoOutput camId: %s, width: %d, height: %d, format: %d, stream: %d, isCapture: %d", + GetAnonyString(cameraId_).c_str(), info->width_, info->height_, info->format_, + info->streamType_, info->isCapture_); + videoSurface_ = Surface::CreateSurfaceAsConsumer(); + videoSurface_->SetDefaultWidthAndHeight(info->width_, info->height_); + videoSurface_->SetUserData(CAMERA_SURFACE_FORMAT, std::to_string(info->format_)); + videoListener_ = std::make_shared(videoSurface_, resultCallback_); + videoSurface_->RegisterConsumerListener((sptr &)videoListener_); + videoOutput_ = cameraManager_->CreateVideoOutput(videoSurface_); + if (videoOutput_ == nullptr) { + DHLOGE("DCameraClient::CreateVideoOutput %s create video output failed", GetAnonyString(cameraId_).c_str()); + return DCAMERA_BAD_VALUE; + } + std::shared_ptr videoCallback = std::make_shared(stateCallback_); + ((sptr &)videoOutput_)->SetCallback(videoCallback); + DHLOGI("DCameraClient::CreateVideoOutput %s success", GetAnonyString(cameraId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraClient::StartCaptureInner(std::shared_ptr& info) +{ + switch (info->streamType_) { + case CONTINUOUS_FRAME: { + return StartVideoOutput(); + } + case SNAPSHOT_FRAME: { + return StartPhotoOutput(info); + } + default: { + DHLOGE("DCameraClient::StartCaptureInner unknown stream type"); + return DCAMERA_BAD_VALUE; + } + } +} + +int32_t DCameraClient::StartPhotoOutput(std::shared_ptr& info) +{ + DHLOGI("DCameraClient::StartPhotoOutput cameraId: %s", GetAnonyString(cameraId_).c_str()); + if (photoOutput_ == nullptr) { + DHLOGE("DCameraClient::StartPhotoOutput photoOutput is null"); + return DCAMERA_BAD_VALUE; + } + + std::vector> captureSettings = info->captureSettings_; + std::string metadataSetting; + for (auto& setting : captureSettings) { + if (setting->type_ == UPDATE_METADATA) { + DHLOGI("DCameraClient::StartPhotoOutput %s update metadata settings", GetAnonyString(cameraId_).c_str()); + metadataSetting = setting->value_; + } + } + + if (metadataSetting.empty()) { + DHLOGE("DCameraClient::StartPhotoOutput no metadata settings to update"); + int32_t ret = ((sptr &)photoOutput_)->Capture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::StartPhotoOutput %s photoOutput capture failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + return DCAMERA_OK; + } + + camera_metadata_item_t item; + CameraStandard::PhotoCaptureSetting::RotationConfig rotation = + CameraStandard::PhotoCaptureSetting::RotationConfig::Rotation_0; + std::shared_ptr cameraMetadata = + CameraStandard::MetadataUtils::DecodeFromString(Base64Decode(metadataSetting)); + int32_t ret = CameraStandard::FindCameraMetadataItem(cameraMetadata->get(), OHOS_JPEG_ORIENTATION, &item); + if (ret == DCAMERA_OK) { + DHLOGI("DCameraClient::StartPhotoOutput %s find camera metadata item", GetAnonyString(cameraId_).c_str()); + rotation = static_cast(item.data.i32[0]); + } + + DHLOGI("DCameraClient::StartPhotoOutput %s photo capture settings set rotation: %d", + GetAnonyString(cameraId_).c_str(), rotation); + std::shared_ptr photoCaptureSettings = + std::make_shared(); + photoCaptureSettings->SetRotation(rotation); + ret = ((sptr &)photoOutput_)->Capture(photoCaptureSettings); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::StartPhotoOutput %s photoOutput capture failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraClient::StartVideoOutput() +{ + DHLOGI("DCameraClient::StartVideoOutput cameraId: %s", GetAnonyString(cameraId_).c_str()); + if (videoOutput_ == nullptr) { + DHLOGE("DCameraClient::StartVideoOutput videoOutput is null"); + return DCAMERA_BAD_VALUE; + } + int32_t ret = ((sptr &)videoOutput_)->Start(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraClient::StartVideoOutput %s videoOutput start failed, ret: %d", + GetAnonyString(cameraId_).c_str(), ret); + return ret; + } + return DCAMERA_OK; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/src/listener/dcamera_photo_surface_listener.cpp b/services/cameraservice/cameraoperator/client/src/listener/dcamera_photo_surface_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a2ea6c400de0e27180efca9ad6c2c9fb71bdfb2 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/listener/dcamera_photo_surface_listener.cpp @@ -0,0 +1,70 @@ +/* + * 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 "dcamera_photo_surface_listener.h" + +#include + +#include "data_buffer.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraPhotoSurfaceListener::DCameraPhotoSurfaceListener(const sptr& surface, + const std::shared_ptr& callback) : surface_(surface), callback_(callback) +{ +} + +void DCameraPhotoSurfaceListener::OnBufferAvailable() +{ + DHLOGI("DCameraPhotoSurfaceListener::OnBufferAvailable"); + OHOS::sptr buffer = nullptr; + int32_t flushFence = 0; + int64_t timestamp = 0; + OHOS::Rect damage; + + do { + surface_->AcquireBuffer(buffer, flushFence, timestamp, damage); + if (buffer == nullptr) { + DHLOGE("DCameraPhotoSurfaceListener AcquireBuffer failed"); + break; + } + + char *address = static_cast(buffer->GetVirAddr()); + int32_t size = static_cast(buffer->GetSize()); + if ((address == nullptr) || (size <= 0)) { + DHLOGE("DCameraPhotoSurfaceListener invalid params, size: %d", size); + break; + } + + DHLOGI("DCameraPhotoSurfaceListener size: %d", size); + std::shared_ptr dataBuffer = std::make_shared(size); + int32_t ret = memcpy_s(dataBuffer->Data(), dataBuffer->Capacity(), address, size); + if (ret != EOK) { + DHLOGE("DCameraPhotoSurfaceListener Memory Copy failed, ret: %d", ret); + break; + } + + if (callback_ == nullptr) { + DHLOGE("DCameraPhotoSurfaceListener ResultCallback is null"); + break; + } + callback_->OnPhotoResult(dataBuffer); + } while (0); + surface_->ReleaseBuffer(buffer, -1); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/src/listener/dcamera_video_surface_listener.cpp b/services/cameraservice/cameraoperator/client/src/listener/dcamera_video_surface_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d7865e396fd48a6c4983d55bde45d8b69127364 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/src/listener/dcamera_video_surface_listener.cpp @@ -0,0 +1,75 @@ +/* + * 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 "dcamera_video_surface_listener.h" + +#include + +#include "data_buffer.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraVideoSurfaceListener::DCameraVideoSurfaceListener(const sptr& surface, + const std::shared_ptr& callback) : surface_(surface), callback_(callback) +{ +} + +void DCameraVideoSurfaceListener::OnBufferAvailable() +{ + DHLOGI("DCameraVideoSurfaceListener::OnBufferAvailable"); + OHOS::sptr buffer = nullptr; + int32_t flushFence = 0; + int64_t timestamp = 0; + OHOS::Rect damage; + + do { + surface_->AcquireBuffer(buffer, flushFence, timestamp, damage); + if (buffer == nullptr) { + DHLOGE("DCameraVideoSurfaceListener AcquireBuffer failed"); + break; + } + + char *address = static_cast(buffer->GetVirAddr()); + int32_t size = buffer->GetSize(); + int32_t width = buffer->GetWidth(); + int32_t height = buffer->GetHeight(); + if ((address == nullptr) || (size <= 0) || (width <= 0) || (height <= 0)) { + DHLOGE("DCameraVideoSurfaceListener invalid params, width: %d, height: %d, size: %d", width, height, size); + break; + } + + DHLOGI("DCameraVideoSurfaceListener width: %d, height: %d, size: %d", width, height, size); + int32_t y2UvRatio = 2; + int32_t bytesPerPixel = 3; + size_t validImgSize = static_cast(width * height * bytesPerPixel / y2UvRatio); + std::shared_ptr dataBuffer = std::make_shared(validImgSize); + int32_t ret = memcpy_s(dataBuffer->Data(), dataBuffer->Capacity(), address, validImgSize); + if (ret != EOK) { + DHLOGE("DCameraVideoSurfaceListener Memory Copy failed, ret: %d", ret); + break; + } + + if (callback_ == nullptr) { + DHLOGE("DCameraVideoSurfaceListener ResultCallback is null"); + break; + } + callback_->OnVideoResult(dataBuffer); + } while (0); + surface_->ReleaseBuffer(buffer, -1); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/test/unittest/BUILD.gn b/services/cameraservice/cameraoperator/client/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..11aa5aca7267a8946674ebba9c5cc49cd3478b25 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/test/unittest/BUILD.gn @@ -0,0 +1,19 @@ +# 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. + +group("camera_client_test") { + testonly = true + deps = [ + "common/cameraoperator:dcamera_client_test", + ] +} \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/client/test/unittest/common/cameraoperator/BUILD.gn b/services/cameraservice/cameraoperator/client/test/unittest/common/cameraoperator/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..46082450f4b37f93f55ed69635e144ee6ce788c1 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/test/unittest/common/cameraoperator/BUILD.gn @@ -0,0 +1,90 @@ +# 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. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") +module_out_path = "distributed_camera/dcamera_client_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//third_party/jsoncpp/include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${graphicstandard_path}/frameworks/surface/include", + "${camerastandard_path}/frameworks/native/metadata/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/input", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/output", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/session", + "${camerastandard_path}/services/camera_service/binder/base/include", + "${camerastandard_path}/services/camera_service/binder/client/include", + "${camerastandard_path}/services/camera_service/binder/server/include", + "${camerastandard_path}/services/camera_service/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + ] + + include_dirs += [ + "${distributedcamera_hdf_path}/interfaces/include", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${services_path}/cameraservice/base/include", + "${services_path}/cameraservice/cameraoperator/client/include", + "${services_path}/cameraservice/cameraoperator/client/include/callback", + "${services_path}/cameraservice/cameraoperator/client/include/listener", + ] +} + +ohos_unittest("DCameraClientTest") { + module_out_path = module_out_path + + sources = [ + "dcamera_client_test.cpp" + ] + + configs = [ ":module_private_config" ] + + deps = [ + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "${graphicstandard_path}:libsurface", + "${camerastandard_path}/frameworks/native/camera:camera_framework", + "${camerastandard_path}/frameworks/native/metadata:metadata", + "${services_path}/cameraservice/cameraoperator/client:distributed_camera_client", + "${services_path}/cameraservice/sinkservice:distributed_camera_sink" + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "eventhandler:libeventhandler", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DCameraClientTest\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dcamera_client_test") { + testonly = true + deps = [ ":DCameraClientTest" ] +} diff --git a/services/cameraservice/cameraoperator/client/test/unittest/common/cameraoperator/dcamera_client_test.cpp b/services/cameraservice/cameraoperator/client/test/unittest/common/cameraoperator/dcamera_client_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95a787a2d353557fdfbf0c8065fdc3453c142168 --- /dev/null +++ b/services/cameraservice/cameraoperator/client/test/unittest/common/cameraoperator/dcamera_client_test.cpp @@ -0,0 +1,269 @@ +/* + * 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 + +#include "anonymous_string.h" +#include "dcamera_client.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraClientTestStateCallback : public StateCallback { +public: + void OnStateChanged(std::shared_ptr& event) + { + DHLOGI("DCameraClientTestStateCallback::OnStateChanged type: %d, result: %d", + event->eventType_, event->eventResult_); + } + + void OnMetadataResult() + { + DHLOGI("DCameraClientTestStateCallback::OnMetadataResult"); + } +}; + +class DCameraClientTestResultCallback : public ResultCallback { +public: + void OnPhotoResult(std::shared_ptr& buffer) + { + DHLOGI("DCameraClientTestResultCallback::OnPhotoResult"); + } + + void OnVideoResult(std::shared_ptr& buffer) + { + DHLOGI("DCameraClientTestResultCallback::OnVideoResult"); + } +}; + +const int32_t TEST_WIDTH = 1920; +const int32_t TEST_HEIGHT = 1080; +const int32_t TEST_FORMAT_3 = 3; +const int32_t TEST_FORMAT_4 = 4; +const int32_t TEST_SLEEP_SEC = 2; +const std::string TEST_CAMERA_ID = "Camera_device@3.5/legacy/1"; + +class DCameraClientTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr client_; + std::shared_ptr photoInfo_false_; + std::shared_ptr videoInfo_false_; + std::shared_ptr photoInfo_true_; + std::shared_ptr videoInfo_true_; +}; + +void DCameraClientTest::SetUpTestCase(void) +{ + DHLOGI("DCameraClientTest::SetUpTestCase"); +} + +void DCameraClientTest::TearDownTestCase(void) +{ + DHLOGI("DCameraClientTest::TearDownTestCase"); +} + +void DCameraClientTest::SetUp(void) +{ + DHLOGI("DCameraClientTest::SetUp"); + client_ = std::make_shared(TEST_CAMERA_ID); + + photoInfo_false_ = std::make_shared(); + photoInfo_false_->width_ = TEST_WIDTH; + photoInfo_false_->height_ = TEST_HEIGHT; + photoInfo_false_->format_ = TEST_FORMAT_4; + photoInfo_false_->isCapture_ = false; + photoInfo_false_->streamType_ = SNAPSHOT_FRAME; + + videoInfo_false_ = std::make_shared(); + videoInfo_false_->width_ = TEST_WIDTH; + videoInfo_false_->height_ = TEST_HEIGHT; + videoInfo_false_->format_ = TEST_FORMAT_3; + videoInfo_false_->isCapture_ = false; + videoInfo_false_->streamType_ = CONTINUOUS_FRAME; + + photoInfo_true_ = std::make_shared(); + photoInfo_true_->width_ = TEST_WIDTH; + photoInfo_true_->height_ = TEST_HEIGHT; + photoInfo_true_->format_ = TEST_FORMAT_4; + photoInfo_true_->isCapture_ = true; + photoInfo_true_->streamType_ = SNAPSHOT_FRAME; + + videoInfo_true_ = std::make_shared(); + videoInfo_true_->width_ = TEST_WIDTH; + videoInfo_true_->height_ = TEST_HEIGHT; + videoInfo_true_->format_ = TEST_FORMAT_3; + videoInfo_true_->isCapture_ = true; + videoInfo_true_->streamType_ = CONTINUOUS_FRAME; +} + +void DCameraClientTest::TearDown(void) +{ + DHLOGI("DCameraClientTest::TearDown"); + client_ = nullptr; + photoInfo_false_ = nullptr; + videoInfo_false_ = nullptr; + photoInfo_true_ = nullptr; + videoInfo_true_ = nullptr; +} + +/** + * @tc.name: dcamera_client_test_001 + * @tc.desc: Verify SetStateCallback + * @tc.type: FUNC + * @tc.require: AR000GK6MN + */ +HWTEST_F(DCameraClientTest, dcamera_client_test_001, TestSize.Level1) +{ + DHLOGI("DCameraClientTest dcamera_client_test_001: test set state callback"); + std::shared_ptr stateCallback = std::make_shared(); + int32_t ret = client_->SetStateCallback(stateCallback); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_client_test_002 + * @tc.desc: Verify SetResultCallback + * @tc.type: FUNC + * @tc.require: AR000GK6MN + */ +HWTEST_F(DCameraClientTest, dcamera_client_test_002, TestSize.Level1) +{ + DHLOGI("DCameraClientTest dcamera_client_test_002: test set result callback"); + std::shared_ptr resultCallback = std::make_shared(); + int32_t ret = client_->SetResultCallback(resultCallback); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_client_test_003 + * @tc.desc: Verify Init and UnInit + * @tc.type: FUNC + * @tc.require: AR000GK6ML + */ +HWTEST_F(DCameraClientTest, dcamera_client_test_003, TestSize.Level1) +{ + DHLOGI("DCameraClientTest dcamera_client_test_003: test init and release client"); + std::shared_ptr stateCallback = std::make_shared(); + int32_t ret = client_->SetStateCallback(stateCallback); + EXPECT_EQ(DCAMERA_OK, ret); + + std::shared_ptr resultCallback = std::make_shared(); + ret = client_->SetResultCallback(resultCallback); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = client_->Init(); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = client_->UnInit(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_client_test_004 + * @tc.desc: Verify StartCapture and StopCapture + * @tc.type: FUNC + * @tc.require: AR000GK6ML + */ +HWTEST_F(DCameraClientTest, dcamera_client_test_004, TestSize.Level1) +{ + DHLOGI("DCameraClientTest dcamera_client_test_004: test startCapture and stopCapture"); + std::shared_ptr stateCallback = std::make_shared(); + int32_t ret = client_->SetStateCallback(stateCallback); + EXPECT_EQ(DCAMERA_OK, ret); + + std::shared_ptr resultCallback = std::make_shared(); + ret = client_->SetResultCallback(resultCallback); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = client_->Init(); + EXPECT_EQ(DCAMERA_OK, ret); + + DHLOGI("DCameraClientTest dcamera_client_test_004: video width: %d, height: %d, format: %d, isCapture: %d", + videoInfo_true_->width_, videoInfo_true_->height_, videoInfo_true_->format_, videoInfo_true_->isCapture_); + std::vector> captureInfos; + captureInfos.push_back(videoInfo_true_); + ret = client_->StartCapture(captureInfos); + EXPECT_EQ(DCAMERA_OK, ret); + + sleep(TEST_SLEEP_SEC); + + ret = client_->StopCapture(); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = client_->UnInit(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_client_test_005 + * @tc.desc: Verify StartCapture and StopCapture + * @tc.type: FUNC + * @tc.require: AR000GK6ML + */ +HWTEST_F(DCameraClientTest, dcamera_client_test_005, TestSize.Level1) +{ + DHLOGI("DCameraClientTest dcamera_client_test_005: test startCapture and stopCapture"); + std::shared_ptr stateCallback = std::make_shared(); + int32_t ret = client_->SetStateCallback(stateCallback); + EXPECT_EQ(DCAMERA_OK, ret); + + std::shared_ptr resultCallback = std::make_shared(); + ret = client_->SetResultCallback(resultCallback); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = client_->Init(); + EXPECT_EQ(DCAMERA_OK, ret); + + DHLOGI("DCameraClientTest dcamera_client_test_005: video width: %d, height: %d, format: %d, isCapture: %d", + videoInfo_true_->width_, videoInfo_true_->height_, videoInfo_true_->format_, videoInfo_true_->isCapture_); + DHLOGI("DCameraClientTest dcamera_client_test_005: photo width: %d, height: %d, format: %d, isCapture: %d", + photoInfo_false_->width_, photoInfo_false_->height_, photoInfo_false_->format_, photoInfo_false_->isCapture_); + std::vector> captureInfos; + captureInfos.push_back(videoInfo_true_); + captureInfos.push_back(photoInfo_false_); + ret = client_->StartCapture(captureInfos); + EXPECT_EQ(DCAMERA_OK, ret); + + sleep(TEST_SLEEP_SEC); + + DHLOGI("DCameraClientTest dcamera_client_test_005: video width: %d, height: %d, format: %d, isCapture: %d", + videoInfo_false_->width_, videoInfo_false_->height_, videoInfo_false_->format_, videoInfo_false_->isCapture_); + DHLOGI("DCameraClientTest dcamera_client_test_005: photo width: %d, height: %d, format: %d, isCapture: %d", + photoInfo_true_->width_, photoInfo_true_->height_, photoInfo_true_->format_, photoInfo_true_->isCapture_); + captureInfos.clear(); + captureInfos.push_back(videoInfo_false_); + captureInfos.push_back(photoInfo_true_); + ret = client_->StartCapture(captureInfos); + EXPECT_EQ(DCAMERA_OK, ret); + + sleep(TEST_SLEEP_SEC); + + ret = client_->StopCapture(); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = client_->UnInit(); + EXPECT_EQ(DCAMERA_OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/handler/BUILD.gn b/services/cameraservice/cameraoperator/handler/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..39c468a28fcab989bb3d2c26bedbed28f1a36899 --- /dev/null +++ b/services/cameraservice/cameraoperator/handler/BUILD.gn @@ -0,0 +1,77 @@ +# 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. + +import("//build/ohos.gni") +import("//build/ohos_var.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_handler") { + include_dirs = [ + "//third_party/jsoncpp/include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${graphicstandard_path}/frameworks/surface/include", + "${camerastandard_path}/frameworks/native/metadata/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/input", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/output", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/session", + "${camerastandard_path}/services/camera_service/binder/base/include", + "${camerastandard_path}/services/camera_service/binder/client/include", + "${camerastandard_path}/services/camera_service/binder/server/include", + "${camerastandard_path}/services/camera_service/include", + "${mediastandard_path}/interfaces/innerkits/native/media/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + ] + + include_dirs += [ + "include", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${distributedcamera_hdf_path}/interfaces/include", + "${services_path}/cameraservice/cameraoperator/client/include/callback", + ] + + sources = [ + "src/dcamera_handler.cpp", + "${services_path}/cameraservice/cameraoperator/client/src/callback/dcamera_manager_callback.cpp", + ] + + deps = [ + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "${graphicstandard_path}:libsurface", + "${camerastandard_path}/frameworks/native/camera:camera_framework", + "${camerastandard_path}/frameworks/native/metadata:metadata", + "//utils/native/base:utils", + "//third_party/jsoncpp:jsoncpp", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dcamerahandler\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "multimedia_media_standard:media_client", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/handler/include/dcamera_handler.h b/services/cameraservice/cameraoperator/handler/include/dcamera_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..4167d4f3693a2015c4db1da4c3924b9274073435 --- /dev/null +++ b/services/cameraservice/cameraoperator/handler/include/dcamera_handler.h @@ -0,0 +1,73 @@ +/* + * 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_DCAMERA_HANDLER_H +#define OHOS_DCAMERA_HANDLER_H + +#include "ihardware_handler.h" + +#include + +#include "camera_info.h" +#include "camera_input.h" +#include "camera_manager.h" +#include "json/json.h" +#include "single_instance.h" +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +struct ConfigInfo { + DCStreamType type; + std::string formatKey; + sptr cameraInput; +}; + +class DCameraHandler : public IHardwareHandler { +DECLARE_SINGLE_INSTANCE_BASE(DCameraHandler); +public: + int32_t Initialize() override; + std::vector Query() override; + std::map QueryExtraInfo() override; + bool IsSupportPlugin() override; + void RegisterPluginListener(std::shared_ptr listener) override; + + std::vector GetCameras(); + +private: + DCameraHandler() = default; + ~DCameraHandler(); + +private: + DHItem CreateDHItem(sptr& info); + std::string GetCameraPosition(camera_position_enum_t position); + void ConfigFormatAndResolution(ConfigInfo& info, Json::Value& outputFormat, Json::Value& resolution, + std::vector& formatList, std::set& formatSet); + bool IsValid(DCStreamType type, CameraStandard::CameraPicSize& size); + + sptr cameraManager_; + std::shared_ptr pluginListener_; +}; + +#ifdef __cplusplus +extern "C" { +#endif +__attribute__((visibility("default"))) IHardwareHandler* GetHardwareHandler(); +#ifdef __cplusplus +} +#endif +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_HANDLER_H \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/handler/src/dcamera_handler.cpp b/services/cameraservice/cameraoperator/handler/src/dcamera_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..116029dbb10a7c4a55ae80f3660d389aa4788232 --- /dev/null +++ b/services/cameraservice/cameraoperator/handler/src/dcamera_handler.cpp @@ -0,0 +1,256 @@ +/* + * 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 "dcamera_handler.h" + +#include "anonymous_string.h" +#include "avcodec_info.h" +#include "avcodec_list.h" +#include "dcamera_manager_callback.h" +#include "dcamera_utils_tools.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" +#include "metadata_utils.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DCameraHandler); + +DCameraHandler::~DCameraHandler() +{ + DHLOGI("~DCameraHandler"); +} + +int32_t DCameraHandler::Initialize() +{ + DHLOGI("DCameraHandler::Initialize"); + cameraManager_ = CameraStandard::CameraManager::GetInstance(); + if (cameraManager_ == nullptr) { + DHLOGE("DCameraHandler::Initialize cameraManager getInstance failed"); + return DCAMERA_INIT_ERR; + } + std::shared_ptr cameraMgrCallback = std::make_shared(); + cameraManager_->SetCallback(cameraMgrCallback); + DHLOGI("DCameraHandler::Initialize success"); + return DCAMERA_OK; +} + +std::vector DCameraHandler::Query() +{ + std::vector itemList; + std::vector> cameraList = cameraManager_->GetCameras(); + DHLOGI("DCameraHandler::Query get %d cameras", cameraList.size()); + if (cameraList.empty()) { + DHLOGE("DCameraHandler::Query no camera device"); + return itemList; + } + for (auto& info : cameraList) { + if (info->GetConnectionType() != OHOS_CAMERA_CONNECTION_TYPE_BUILTIN) { + DHLOGI("DCameraHandler::Query connection type: %d", info->GetConnectionType()); + continue; + } + if ((info->GetPosition() == OHOS_CAMERA_POSITION_FRONT) || + (info->GetPosition() == OHOS_CAMERA_POSITION_BACK && info->GetCameraType() == OHOS_CAMERA_TYPE_LOGICAL)) { + DHItem item = CreateDHItem(info); + itemList.push_back(item); + } + } + DHLOGI("DCameraHandler::Query success, get %d items", itemList.size()); + return itemList; +} + +std::map DCameraHandler::QueryExtraInfo() +{ + DHLOGI("DCameraHandler::QueryExtraInfo"); + std::map extraInfo; + return extraInfo; +} + +bool DCameraHandler::IsSupportPlugin() +{ + DHLOGI("DCameraHandler::IsSupportPlugin"); + return false; +} + +void DCameraHandler::RegisterPluginListener(std::shared_ptr listener) +{ + DHLOGI("DCameraHandler::RegisterPluginListener"); + if (listener == nullptr) { + DHLOGE("DCameraHandler unregistering plugin listener"); + } + pluginListener_ = listener; +} + +std::vector DCameraHandler::GetCameras() +{ + std::vector cameras; + std::vector> cameraList = cameraManager_->GetCameras(); + DHLOGI("DCameraHandler::GetCameras get %d cameras", cameraList.size()); + if (cameraList.empty()) { + DHLOGE("DCameraHandler::GetCameras no camera device"); + return cameras; + } + for (auto& info : cameraList) { + if (info->GetConnectionType() != OHOS_CAMERA_CONNECTION_TYPE_BUILTIN) { + DHLOGI("DCameraHandler::GetCameras connection type: %d", info->GetConnectionType()); + continue; + } + if ((info->GetPosition() == OHOS_CAMERA_POSITION_FRONT) || + (info->GetPosition() == OHOS_CAMERA_POSITION_BACK && info->GetCameraType() == OHOS_CAMERA_TYPE_LOGICAL)) { + std::string dhId = CAMERA_ID_PREFIX + info->GetID(); + cameras.push_back(dhId); + } + } + DHLOGI("DCameraHandler::GetCameras success, get %d items", cameras.size()); + return cameras; +} + +DHItem DCameraHandler::CreateDHItem(sptr& info) +{ + DHItem item; + std::string id = info->GetID(); + item.dhId = CAMERA_ID_PREFIX + id; + DHLOGI("DCameraHandler::CreateDHItem camera id: %s", GetAnonyString(id).c_str()); + + Json::Value root; + root[CAMERA_PROTOCOL_VERSION_KEY] = Json::Value(CAMERA_PROTOCOL_VERSION_VALUE); + root[CAMERA_POSITION_KEY] = Json::Value(GetCameraPosition(info->GetPosition())); + + std::shared_ptr avCodecList = Media::AVCodecListFactory::CreateAVCodecList(); + std::vector> videoCapsList = avCodecList->GetVideoEncoderCaps(); + for (auto& videoCaps : videoCapsList) { + std::shared_ptr codecInfo = videoCaps->GetCodecInfo(); + std::string name = codecInfo->GetName(); + root[CAMERA_CODEC_TYPE_KEY].append(name); + DHLOGI("DCameraHandler::CreateDHItem codec type: %s", name.c_str()); + } + + sptr cameraInput = cameraManager_->CreateCameraInput(info); + if (cameraInput == nullptr) { + DHLOGE("DCameraHandler::CreateDHItem create cameraInput failed"); + return item; + } + + Json::Value outputFormat; + Json::Value resolution; + std::set formatSet; + + std::vector videoFormats = cameraInput->GetSupportedVideoFormats(); + ConfigInfo videoConfig = {CONTINUOUS_FRAME, CAMERA_FORMAT_VIDEO, cameraInput}; + ConfigFormatAndResolution(videoConfig, outputFormat, resolution, videoFormats, formatSet); + + std::vector previewFormats = cameraInput->GetSupportedPreviewFormats(); + ConfigInfo previewInfo = {CONTINUOUS_FRAME, CAMERA_FORMAT_PREVIEW, cameraInput}; + ConfigFormatAndResolution(previewInfo, outputFormat, resolution, previewFormats, formatSet); + + std::vector photoFormats = cameraInput->GetSupportedPhotoFormats(); + ConfigInfo photoConfig = {SNAPSHOT_FRAME, CAMERA_FORMAT_PHOTO, cameraInput}; + ConfigFormatAndResolution(photoConfig, outputFormat, resolution, photoFormats, formatSet); + + root[CAMERA_FORMAT_KEY] = outputFormat; + root[CAMERA_RESOLUTION_KEY] = resolution; + + std::string abilityString = cameraInput->GetCameraSettings(); + std::string encodeString = Base64Encode(reinterpret_cast(abilityString.c_str()), + abilityString.length()); + root[CAMERA_METADATA_KEY] = Json::Value(encodeString); + + item.attrs = root.toStyledString(); + cameraInput->Release(); + return item; +} + +std::string DCameraHandler::GetCameraPosition(camera_position_enum_t position) +{ + DHLOGI("DCameraHandler::GetCameraPosition position: %d", position); + std::string ret = ""; + switch (position) { + case OHOS_CAMERA_POSITION_BACK: { + ret = CAMERA_POSITION_BACK; + break; + } + case OHOS_CAMERA_POSITION_FRONT: { + ret = CAMERA_POSITION_FRONT; + break; + } + case OHOS_CAMERA_POSITION_OTHER: { + ret = CAMERA_POSITION_UNSPECIFIED; + break; + } + default: { + DHLOGE("DCameraHandler::GetCameraPosition unknown camera position"); + break; + } + } + DHLOGI("DCameraHandler::GetCameraPosition success ret: %s", ret.c_str()); + return ret; +} + +void DCameraHandler::ConfigFormatAndResolution(ConfigInfo& info, Json::Value& outputFormat, Json::Value& resolution, + std::vector& formatList, std::set& formatSet) +{ + DHLOGI("DCameraHandler::ConfigFormatAndResolution camera format size: %d", formatList.size()); + for (auto& format : formatList) { + DHLOGI("DCameraHandler::ConfigFormatAndResolution %s format: %d", info.formatKey.c_str(), format); + outputFormat[info.formatKey].append(format); + if (formatSet.insert(format).second) { + std::vector picSizes = info.cameraInput->getSupportedSizes(format); + std::string keyName = std::to_string(format); + DHLOGI("DCameraHandler::ConfigFormatAndResolution get %d supported camera pic size", picSizes.size()); + for (auto& size : picSizes) { + if (IsValid(info.type, size)) { + std::string value = std::to_string(size.width) + "*" + std::to_string(size.height); + resolution[keyName].append(value); + DHLOGI("DCameraHandler::ConfigFormatAndResolution format %d resolution %s", format, value.c_str()); + } + } + } + } +} + +bool DCameraHandler::IsValid(DCStreamType type, CameraStandard::CameraPicSize& size) +{ + bool ret = false; + switch (type) { + case CONTINUOUS_FRAME: { + ret = (size.width >= RESOLUTION_MIN_WIDTH) && + (size.height >= RESOLUTION_MIN_HEIGHT) && + (size.width <= RESOLUTION_MAX_WIDTH_CONTINUOUS) && + (size.height <= RESOLUTION_MAX_HEIGHT_CONTINUOUS); + break; + } + case SNAPSHOT_FRAME: { + ret = (size.width >= RESOLUTION_MIN_WIDTH) && + (size.height >= RESOLUTION_MIN_HEIGHT) && + (size.width <= RESOLUTION_MAX_WIDTH_SNAPSHOT) && + (size.height <= RESOLUTION_MAX_HEIGHT_SNAPSHOT); + break; + } + default: { + DHLOGE("DCameraHandler::isValid unknown stream type"); + break; + } + } + return ret; +} + +IHardwareHandler* GetHardwareHandler() +{ + DHLOGI("DCameraHandler::GetHardwareHandler"); + return &DCameraHandler::GetInstance(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/handler/test/unittest/BUILD.gn b/services/cameraservice/cameraoperator/handler/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0cdc5b0726aee6ff519dd873caddb3620bbc20dc --- /dev/null +++ b/services/cameraservice/cameraoperator/handler/test/unittest/BUILD.gn @@ -0,0 +1,19 @@ +# 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. + +group("camera_handler_test") { + testonly = true + deps = [ + "common/dcamerahandler:dcamera_handler_test", + ] +} \ No newline at end of file diff --git a/services/cameraservice/cameraoperator/handler/test/unittest/common/dcamerahandler/BUILD.gn b/services/cameraservice/cameraoperator/handler/test/unittest/common/dcamerahandler/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..17312387712b5374119920f2b848de3028011b4e --- /dev/null +++ b/services/cameraservice/cameraoperator/handler/test/unittest/common/dcamerahandler/BUILD.gn @@ -0,0 +1,87 @@ +# 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. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") +module_out_path = "distributed_camera/dcamera_handler_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${graphicstandard_path}/frameworks/surface/include", + "${camerastandard_path}/frameworks/native/metadata/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/input", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/output", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/session", + "${camerastandard_path}/services/camera_service/binder/base/include", + "${camerastandard_path}/services/camera_service/binder/client/include", + "${camerastandard_path}/services/camera_service/binder/server/include", + "${camerastandard_path}/services/camera_service/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + ] + + include_dirs += [ + "${distributedcamera_hdf_path}/interfaces/include", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${services_path}/cameraservice/base/include", + "${services_path}/cameraservice/cameraoperator/client/include/callback", + "${services_path}/cameraservice/cameraoperator/handler/include", + ] +} + +ohos_unittest("DCameraHandlerTest") { + module_out_path = module_out_path + + sources = [ + "dcamera_handler_test.cpp" + ] + + configs = [ ":module_private_config" ] + + deps = [ + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "${graphicstandard_path}:libsurface", + "${camerastandard_path}/frameworks/native/camera:camera_framework", + "${camerastandard_path}/frameworks/native/metadata:metadata", + "${services_path}/cameraservice/cameraoperator/handler:distributed_camera_handler", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "eventhandler:libeventhandler", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DCameraHandlerTest\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dcamera_handler_test") { + testonly = true + deps = [ ":DCameraHandlerTest" ] +} diff --git a/services/cameraservice/cameraoperator/handler/test/unittest/common/dcamerahandler/dcamera_handler_test.cpp b/services/cameraservice/cameraoperator/handler/test/unittest/common/dcamerahandler/dcamera_handler_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4607fee3145aa9d59b037aea40d71fc5215f7d3 --- /dev/null +++ b/services/cameraservice/cameraoperator/handler/test/unittest/common/dcamerahandler/dcamera_handler_test.cpp @@ -0,0 +1,90 @@ +/* + * 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 + +#include "dcamera_handler.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraHandlerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DCameraHandlerTest::SetUpTestCase(void) +{ + DHLOGI("DCameraHandlerTest::SetUpTestCase"); +} + +void DCameraHandlerTest::TearDownTestCase(void) +{ + DHLOGI("DCameraHandlerTest::TearDownTestCase"); +} + +void DCameraHandlerTest::SetUp(void) +{ + DHLOGI("DCameraHandlerTest::SetUp"); +} + +void DCameraHandlerTest::TearDown(void) +{ + DHLOGI("DCameraHandlerTest::TearDown"); +} + +/** + * @tc.name: dcamera_handler_test_001 + * @tc.desc: Verify Initialize + * @tc.type: FUNC + * @tc.require: AR000GK6MF + */ +HWTEST_F(DCameraHandlerTest, dcamera_handler_test_001, TestSize.Level1) +{ + int32_t ret = DCameraHandler::GetInstance().Initialize(); + EXPECT_EQ(ret, DCAMERA_OK); +} + +/** + * @tc.name: dcamera_handler_test_002 + * @tc.desc: Verify GetCameras + * @tc.type: FUNC + * @tc.require: AR000GK6MF + */ +HWTEST_F(DCameraHandlerTest, dcamera_handler_test_002, TestSize.Level1) +{ + int32_t ret = DCameraHandler::GetInstance().GetCameras().size(); + EXPECT_GT(ret, DCAMERA_OK); +} + +/** + * @tc.name: dcamera_handler_test_003 + * @tc.desc: Verify Query + * @tc.type: FUNC + * @tc.require: AR000GK6MF + */ +HWTEST_F(DCameraHandlerTest, dcamera_handler_test_003, TestSize.Level1) +{ + int32_t ret = DCameraHandler::GetInstance().Query().size(); + EXPECT_GT(ret, DCAMERA_OK); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/BUILD.gn b/services/cameraservice/sinkservice/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8f442aed5edd400ad90232d98e62eac8b5888340 --- /dev/null +++ b/services/cameraservice/sinkservice/BUILD.gn @@ -0,0 +1,128 @@ +# 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. + +import("//build/ohos.gni") +import("//build/ohos_var.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_sink") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${graphicstandard_path}/frameworks/surface/include", + "${camerastandard_path}/frameworks/native/metadata/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/input", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/output", + "${camerastandard_path}/interfaces/inner_api/native/camera/include/session", + "${camerastandard_path}/services/camera_service/binder/base/include", + "${camerastandard_path}/services/camera_service/binder/client/include", + "${camerastandard_path}/services/camera_service/binder/server/include", + "${camerastandard_path}/services/camera_service/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/eventbus", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + "//third_party/jsoncpp/include", + ] + + include_dirs += [ + "include/distributedcamera", + "include/distributedcameramgr", + "include/distributedcameramgr/callback", + "include/distributedcameramgr/eventbus", + "include/distributedcameramgr/interface", + "include/distributedcameramgr/listener", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${innerkits_path}/native_cpp/camera_sink/include", + "${innerkits_path}/native_cpp/camera_source/include", + "${innerkits_path}/native_cpp/camera_source/include/callback", + "${distributedcamera_hdf_path}/interfaces/include", + "${services_path}/cameraservice/base/include", + "${services_path}/cameraservice/cameraoperator/client/include", + "${services_path}/cameraservice/cameraoperator/client/include/callback", + "${services_path}/cameraservice/cameraoperator/client/include/listener", + "${services_path}/cameraservice/cameraoperator/handler/include", + "${services_path}/channel/include", + "${services_path}/data_process/include/eventbus", + "${services_path}/data_process/include/interfaces", + "${services_path}/data_process/include/pipeline", + "${services_path}/data_process/include/utils", + ] + + sources = [ + "src/distributedcamera/distributed_camera_sink_service.cpp", + "src/distributedcamera/distributed_camera_sink_stub.cpp", + "${innerkits_path}/native_cpp/camera_source/src/distributed_camera_source_proxy.cpp", + + "src/distributedcameramgr/callback/dcamera_sink_controller_state_callback.cpp", + "src/distributedcameramgr/callback/dcamera_sink_output_result_callback.cpp", + + "src/distributedcameramgr/eventbus/dcamera_frame_trigger_event.cpp", + "src/distributedcameramgr/eventbus/dcamera_photo_output_event.cpp", + "src/distributedcameramgr/eventbus/dcamera_post_authorization_event.cpp", + "src/distributedcameramgr/eventbus/dcamera_video_output_event.cpp", + + "src/distributedcameramgr/listener/dcamera_sink_controller_channel_listener.cpp", + "src/distributedcameramgr/listener/dcamera_sink_data_process_listener.cpp", + "src/distributedcameramgr/listener/dcamera_sink_output_channel_listener.cpp", + + "src/distributedcameramgr/dcamera_sink_access_control.cpp", + "src/distributedcameramgr/dcamera_sink_controller.cpp", + "src/distributedcameramgr/dcamera_sink_data_process.cpp", + "src/distributedcameramgr/dcamera_sink_dev.cpp", + "src/distributedcameramgr/dcamera_sink_output.cpp", + "src/distributedcameramgr/dcamera_sink_service_ipc.cpp", + + "${services_path}/cameraservice/base/src/dcamera_capture_info_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_channel_info_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_event_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_info_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_metadata_setting_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_open_info_cmd.cpp", + ] + + deps = [ + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "${graphicstandard_path}:libsurface", + "${camerastandard_path}/frameworks/native/camera:camera_framework", + "${camerastandard_path}/frameworks/native/metadata:metadata", + "${services_path}/cameraservice/cameraoperator/client:distributed_camera_client", + "${services_path}/cameraservice/cameraoperator/handler:distributed_camera_handler", + "${services_path}/channel:distributed_camera_channel", + "${services_path}/data_process:distributed_camera_data_process", + "//utils/native/base:utils", + "//third_party/jsoncpp:jsoncpp", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dcamerasinksvr\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcamera/distributed_camera_sink_service.h b/services/cameraservice/sinkservice/include/distributedcamera/distributed_camera_sink_service.h new file mode 100644 index 0000000000000000000000000000000000000000..b356ffa3fa2e7506c8b47751a67849884d6603f9 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcamera/distributed_camera_sink_service.h @@ -0,0 +1,59 @@ +/* + * 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_DISTRIBUTED_CAMERA_SINK_SERVICE_H +#define OHOS_DISTRIBUTED_CAMERA_SINK_SERVICE_H + +#include "system_ability.h" +#include "ipc_object_stub.h" + +#include "dcamera_sink_dev.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_sink_stub.h" + +namespace OHOS { +namespace DistributedHardware { +class DistributedCameraSinkService : public SystemAbility, public DistributedCameraSinkStub { +DECLARE_SYSTEM_ABILITY(DistributedCameraSinkService); +public: + DistributedCameraSinkService(int32_t saId, bool runOnCreate); + ~DistributedCameraSinkService() = default; + + int32_t InitSink(const std::string& params) override; + int32_t ReleaseSink() override; + int32_t SubscribeLocalHardware(const std::string& dhId, const std::string& parameters) override; + int32_t UnsubscribeLocalHardware(const std::string& dhId) override; + int32_t StopCapture(const std::string& dhId) override; + int32_t ChannelNeg(const std::string& dhId, std::string& channelInfo) override; + int32_t GetCameraInfo(const std::string& dhId, std::string& cameraInfo) override; + int32_t OpenChannel(const std::string& dhId, std::string& openInfo) override; + int32_t CloseChannel(const std::string& dhId) override; + +protected: + void OnStart() override; + void OnStop() override; + DISALLOW_COPY_AND_MOVE(DistributedCameraSinkService); + +private: + bool Init(); + bool registerToService_ = false; + DCameraServiceState state_ = DCameraServiceState::DCAMERA_SRV_STATE_NOT_START; + + std::string sinkVer_; + std::map> camerasMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_CAMERA_SINK_SERVICE_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcamera/distributed_camera_sink_stub.h b/services/cameraservice/sinkservice/include/distributedcamera/distributed_camera_sink_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..3f31c97c519822d2ac030c709a8c566b2ee0193f --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcamera/distributed_camera_sink_stub.h @@ -0,0 +1,48 @@ +/* + * 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_DISTRIBUTED_CAMERA_SINK_STUB_H +#define OHOS_DISTRIBUTED_CAMERA_SINK_STUB_H + +#include +#include "iremote_stub.h" + +#include "idistributed_camera_sink.h" + +namespace OHOS { +namespace DistributedHardware { +class DistributedCameraSinkStub : public IRemoteStub { +public: + DistributedCameraSinkStub(); + virtual ~DistributedCameraSinkStub(); + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t InitSinkInner(MessageParcel &data, MessageParcel &reply); + int32_t ReleaseSinkInner(MessageParcel &data, MessageParcel &reply); + int32_t SubscribeLocalHardwareInner(MessageParcel &data, MessageParcel &reply); + int32_t UnsubscribeLocalHardwareInner(MessageParcel &data, MessageParcel &reply); + int32_t StopCaptureInner(MessageParcel &data, MessageParcel &reply); + int32_t ChannelNegInner(MessageParcel &data, MessageParcel &reply); + int32_t GetCameraInfoInner(MessageParcel &data, MessageParcel &reply); + int32_t OpenChannelInner(MessageParcel &data, MessageParcel &reply); + int32_t CloseChannelInner(MessageParcel &data, MessageParcel &reply); + + using DCameraFunc = int32_t (DistributedCameraSinkStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_CAMERA_SINK_STUB_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/callback/dcamera_sink_controller_state_callback.h b/services/cameraservice/sinkservice/include/distributedcameramgr/callback/dcamera_sink_controller_state_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..70110ccee8ac899483724764a3fd5f6975c59ff3 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/callback/dcamera_sink_controller_state_callback.h @@ -0,0 +1,38 @@ +/* + * 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_DCAMERA_SINK_CONTROLLER_STATE_CALLBACK_H +#define OHOS_DCAMERA_SINK_CONTROLLER_STATE_CALLBACK_H + +#include "icamera_operator.h" + +#include "dcamera_sink_controller.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkControllerStateCallback : public StateCallback { +public: + explicit DCameraSinkControllerStateCallback(std::shared_ptr& controller); + ~DCameraSinkControllerStateCallback() = default; + + void OnStateChanged(std::shared_ptr& event) override; + void OnMetadataResult() override; + +private: + std::weak_ptr controller_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_CONTROLLER_STATE_CALLBACK_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/callback/dcamera_sink_output_result_callback.h b/services/cameraservice/sinkservice/include/distributedcameramgr/callback/dcamera_sink_output_result_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..d2c6290625a7a3140345443ae10ae6cd72f0d078 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/callback/dcamera_sink_output_result_callback.h @@ -0,0 +1,38 @@ +/* + * 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_DCAMERA_SINK_OUTPUT_RESULT_CALLBACK_H +#define OHOS_DCAMERA_SINK_OUTPUT_RESULT_CALLBACK_H + +#include "icamera_operator.h" + +#include "dcamera_sink_output.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkOutputResultCallback : public ResultCallback { +public: + explicit DCameraSinkOutputResultCallback(std::shared_ptr& output); + ~DCameraSinkOutputResultCallback() = default; + + void OnPhotoResult(std::shared_ptr& buffer) override; + void OnVideoResult(std::shared_ptr& buffer) override; + +private: + std::weak_ptr output_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_OUTPUT_RESULT_CALLBACK_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_access_control.h b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_access_control.h new file mode 100644 index 0000000000000000000000000000000000000000..7fac01cd625c85b897cb5244afd00a758d28264a --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_access_control.h @@ -0,0 +1,35 @@ +/* + * 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_DCAMERA_SINK_ACCESS_CONTROL_H +#define OHOS_DCAMERA_SINK_ACCESS_CONTROL_H + +#include "icamera_sink_access_control.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkAccessControl : public ICameraSinkAccessControl { +public: + DCameraSinkAccessControl() = default; + ~DCameraSinkAccessControl() = default; + + bool IsSensitiveSrcAccess(const std::string& srcType) override; + bool NotifySensitiveSrc(const std::string& srcType) override; + int32_t TriggerFrame(const std::string& deviceName) override; + int32_t GetAccessControlType(const std::string& accessType) override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_ACCESS_CONTROL_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_controller.h b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..1de1b4f2881eaac6026cef1cc97842cc165ee112 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_controller.h @@ -0,0 +1,84 @@ +/* + * 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_DCAMERA_SINK_CONTROLLER_H +#define OHOS_DCAMERA_SINK_CONTROLLER_H + +#include "event_bus.h" +#include "dcamera_frame_trigger_event.h" +#include "dcamera_post_authorization_event.h" +#include "icamera_controller.h" + +#include "icamera_channel.h" +#include "icamera_operator.h" +#include "icamera_sink_access_control.h" +#include "icamera_sink_output.h" +#include + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkController : public ICameraController, public EventSender, + public DistributedHardware::EventBusHandler, + public DistributedHardware::EventBusHandler, + public std::enable_shared_from_this { +public: + explicit DCameraSinkController(std::shared_ptr& accessControl); + ~DCameraSinkController(); + + int32_t StartCapture(std::vector>& captureInfos) override; + int32_t StopCapture() override; + int32_t ChannelNeg(std::shared_ptr& info) override; + int32_t DCameraNotify(std::shared_ptr& events) override; + int32_t UpdateSettings(std::vector>& settings) override; + int32_t GetCameraInfo(std::shared_ptr& camInfo) override; + int32_t OpenChannel(std::shared_ptr& openInfo) override; + int32_t CloseChannel() override; + int32_t Init(std::vector& indexs) override; + int32_t UnInit() override; + + void OnEvent(DCameraFrameTriggerEvent& event) override; + void OnEvent(DCameraPostAuthorizationEvent& event) override; + + void OnStateChanged(std::shared_ptr& event); + void OnMetadataResult(); + + void OnSessionState(int32_t state); + void OnSessionError(int32_t eventType, int32_t eventReason, std::string detail); + void OnDataReceived(std::vector>& buffers); + +private: + int32_t StartCaptureInner(std::vector>& captureInfos); + int32_t DCameraNotifyInner(int32_t type, int32_t result, std::string content); + int32_t HandleReceivedData(std::shared_ptr& dataBuffer); + void PostAuthorization(std::vector>& captureInfos); + + bool isInit_; + int32_t sessionState_; + std::mutex captureLock_; + std::mutex channelLock_; + std::string dhId_; + std::string srcDevId_; + std::shared_ptr eventBus_; + std::shared_ptr channel_; + std::shared_ptr operator_; + std::shared_ptr accessControl_; + std::shared_ptr output_; + + const std::string SESSION_FLAG = "control"; + const std::string SRC_TYPE = "camera"; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_CONTROLLER_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_data_process.h b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..01c108d3fe3eebbe4d80e1a677409df293cf3116 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_data_process.h @@ -0,0 +1,61 @@ +/* + * 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_DCAMERA_SINK_DATA_PROCESS_H +#define OHOS_DCAMERA_SINK_DATA_PROCESS_H + +#include "event_bus.h" +#include "dcamera_photo_output_event.h" +#include "dcamera_video_output_event.h" +#include "icamera_sink_data_process.h" + +#include "icamera_channel.h" +#include "idata_process_pipeline.h" +#include "image_common_type.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkDataProcess : public ICameraSinkDataProcess, public EventSender, + public DistributedHardware::EventBusHandler, + public DistributedHardware::EventBusHandler, + public std::enable_shared_from_this { +public: + DCameraSinkDataProcess(const std::string& dhId, std::shared_ptr& channel); + ~DCameraSinkDataProcess() = default; + + int32_t StartCapture(std::shared_ptr& captureInfo) override; + int32_t StopCapture() override; + int32_t FeedStream(std::shared_ptr& dataBuffer) override; + + void OnEvent(DCameraPhotoOutputEvent& event) override; + void OnEvent(DCameraVideoOutputEvent& event) override; + + void OnProcessedVideoBuffer(const std::shared_ptr& videoResult); + void OnError(DataProcessErrorType errorType); + +private: + int32_t FeedStreamInner(std::shared_ptr& dataBuffer); + VideoCodecType GetPipelineCodecType(DCEncodeType encodeType); + Videoformat GetPipelineFormat(int32_t format); + + std::string dhId_; + std::shared_ptr captureInfo_; + std::shared_ptr eventBus_; + std::shared_ptr channel_; + std::shared_ptr pipeline_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_DATA_PROCESS_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_dev.h b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_dev.h new file mode 100644 index 0000000000000000000000000000000000000000..295e562e8e8318c6141e02033dd2a9fc327fd9d2 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_dev.h @@ -0,0 +1,51 @@ +/* + * 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_DCAMERA_SINK_DEV_H +#define OHOS_DCAMERA_SINK_DEV_H + +#include +#include +#include + +#include "icamera_controller.h" +#include "icamera_sink_access_control.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkDev { +public: + explicit DCameraSinkDev(const std::string& dhId); + ~DCameraSinkDev(); + + int32_t Init(); + int32_t UnInit(); + int32_t SubscribeLocalHardware(const std::string& parameters); + int32_t UnsubscribeLocalHardware(); + int32_t StopCapture(); + int32_t ChannelNeg(std::string& channelInfo); + int32_t GetCameraInfo(std::string& cameraInfo); + int32_t OpenChannel(std::string& openInfo); + int32_t CloseChannel(); + +private: + bool isInit_; + std::string dhId_; + std::shared_ptr controller_; + std::shared_ptr accessControl_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_DEV_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_output.h b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_output.h new file mode 100644 index 0000000000000000000000000000000000000000..839a8c1489026ea99e0ebb92ed81f48ec92e1b7b --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_output.h @@ -0,0 +1,60 @@ +/* + * 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_DCAMERA_SINK_OUTPUT_H +#define OHOS_DCAMERA_SINK_OUTPUT_H + +#include "icamera_sink_output.h" + +#include + +#include "icamera_channel.h" +#include "icamera_operator.h" +#include "icamera_sink_data_process.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkOutput : public ICameraSinkOutput, public std::enable_shared_from_this { +public: + DCameraSinkOutput(const std::string& dhId, std::shared_ptr& cameraOperator); + ~DCameraSinkOutput(); + + int32_t Init() override; + int32_t UnInit() override; + int32_t StartCapture(std::vector>& captureInfos) override; + int32_t StopCapture() override; + int32_t OpenChannel(std::shared_ptr& info) override; + int32_t CloseChannel() override; + + void OnPhotoResult(std::shared_ptr& buffer); + void OnVideoResult(std::shared_ptr& buffer); + + void OnSessionState(DCStreamType type, int32_t state); + void OnSessionError(DCStreamType type, int32_t eventType, int32_t eventReason, std::string detail); + void OnDataReceived(DCStreamType type, std::vector>& dataBuffers); + +private: + void InitInner(DCStreamType type); + + bool isInit_; + std::string dhId_; + std::map sessionState_; + std::map> channels_; + std::map> dataProcesses_; + std::shared_ptr operator_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_OUTPUT_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_service_ipc.h b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_service_ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..ee19ae09336bf3ba0b6f9748c4a9bf9c9c53516f --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/dcamera_sink_service_ipc.h @@ -0,0 +1,54 @@ +/* + * 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_DCAMERA_SINK_SERVICE_IPC_H +#define OHOS_DCAMERA_SINK_SERVICE_IPC_H + +#include "event_handler.h" +#include "idistributed_camera_source.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkServiceIpc { +DECLARE_SINGLE_INSTANCE_BASE(DCameraSinkServiceIpc); +public: + void Init(); + void UnInit(); + sptr GetSourceRemoteDHMS(const std::string& deviceId); + void OnSourceRemoteDmsDied(const wptr& remote); + void DeleteSourceRemoteDhms(const std::string& deviceId); + +private: + DCameraSinkServiceIpc(); + ~DCameraSinkServiceIpc(); + void OnSourceRemoteDmsDied(const sptr& remote); + void ClearSourceRemoteDhms(); + + class SourceRemoteRecipient : public IRemoteObject::DeathRecipient { + public: + void OnRemoteDied(const wptr& remote) override; + }; + sptr sourceRemoteRecipient_; + std::map> remoteSources_; + std::mutex sourceRemoteDmsLock_; + + bool isInit_; + std::shared_ptr serviceHandler_; + std::mutex initDmsLock_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_frame_trigger_event.h b/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_frame_trigger_event.h new file mode 100644 index 0000000000000000000000000000000000000000..7024a9dd65e1dba5f9843175f9847fd0107687c5 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_frame_trigger_event.h @@ -0,0 +1,36 @@ +/* + * 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_DCAMERA_FRAME_TRIGER_EVENT_H +#define OHOS_DCAMERA_FRAME_TRIGER_EVENT_H + +#include "event.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraFrameTriggerEvent : public Event { +TYPEINDENT(DCameraFrameTriggerEvent); +public: + explicit DCameraFrameTriggerEvent(EventSender& sender); + DCameraFrameTriggerEvent(EventSender& sender, std::string& param); + ~DCameraFrameTriggerEvent() = default; + std::string GetParam(); + +private: + std::string param_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_FRAME_TRIGER_EVENT_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_photo_output_event.h b/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_photo_output_event.h new file mode 100644 index 0000000000000000000000000000000000000000..d42e84fadf18487c9f8e4825b067bb45df594f52 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_photo_output_event.h @@ -0,0 +1,38 @@ +/* + * 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_DCAMERA_PHOTO_OUTPUT_EVENT_H +#define OHOS_DCAMERA_PHOTO_OUTPUT_EVENT_H + +#include "event.h" + +#include "data_buffer.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraPhotoOutputEvent : public Event { +TYPEINDENT(DCameraPhotoOutputEvent); +public: + explicit DCameraPhotoOutputEvent(EventSender& sender); + DCameraPhotoOutputEvent(EventSender& sender, const std::shared_ptr& param); + ~DCameraPhotoOutputEvent() = default; + std::shared_ptr GetParam(); + +private: + std::shared_ptr param_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_PHOTO_OUTPUT_EVENT_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_post_authorization_event.h b/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_post_authorization_event.h new file mode 100644 index 0000000000000000000000000000000000000000..5c23084c07f2e7a4a585aa2f86925eafb5197fdd --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_post_authorization_event.h @@ -0,0 +1,38 @@ +/* + * 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_DCAMERA_POST_AUTHORIZATION_EVENT_H +#define OHOS_DCAMERA_POST_AUTHORIZATION_EVENT_H + +#include "event.h" + +#include "dcamera_capture_info_cmd.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraPostAuthorizationEvent : public Event { +TYPEINDENT(DCameraPostAuthorizationEvent); +public: + explicit DCameraPostAuthorizationEvent(EventSender& sender); + DCameraPostAuthorizationEvent(EventSender& sender, std::vector>& param); + ~DCameraPostAuthorizationEvent() = default; + std::vector> GetParam(); + +private: + std::vector> param_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_POST_AUTHORIZATION_EVENT_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_video_output_event.h b/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_video_output_event.h new file mode 100644 index 0000000000000000000000000000000000000000..f0cb638243fb60171852626fdeb8ccb4b6c43c04 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/eventbus/dcamera_video_output_event.h @@ -0,0 +1,38 @@ +/* + * 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_DCAMERA_VIDEO_OUTPUT_EVENT_H +#define OHOS_DCAMERA_VIDEO_OUTPUT_EVENT_H + +#include "event.h" + +#include "data_buffer.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraVideoOutputEvent : public Event { +TYPEINDENT(DCameraVideoOutputEvent); +public: + explicit DCameraVideoOutputEvent(EventSender& sender); + DCameraVideoOutputEvent(EventSender& sender, const std::shared_ptr& param); + ~DCameraVideoOutputEvent() = default; + std::shared_ptr GetParam(); + +private: + std::shared_ptr param_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_VIDEO_OUTPUT_EVENT_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_access_control.h b/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_access_control.h new file mode 100644 index 0000000000000000000000000000000000000000..06e264ff591be124fc91b9d286ee1b982fc4ed36 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_access_control.h @@ -0,0 +1,36 @@ +/* + * 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_ICAMERA_SINK_ACCESS_CONTROL_H +#define OHOS_ICAMERA_SINK_ACCESS_CONTROL_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class ICameraSinkAccessControl { +public: + ICameraSinkAccessControl() = default; + virtual ~ICameraSinkAccessControl() = default; + + virtual bool IsSensitiveSrcAccess(const std::string& srcType) = 0; + virtual bool NotifySensitiveSrc(const std::string& srcType) = 0; + virtual int32_t TriggerFrame(const std::string& deviceName) = 0; + virtual int32_t GetAccessControlType(const std::string& accessType) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_ICAMERA_SINK_ACCESS_CONTROL_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_data_process.h b/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..035cec5e3ce28ac423ba86516fb45cb973e391fd --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_data_process.h @@ -0,0 +1,38 @@ +/* + * 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_ICAMERA_SINK_DATA_PROCESS_H +#define OHOS_ICAMERA_SINK_DATA_PROCESS_H + +#include +#include + +#include "data_buffer.h" +#include "dcamera_capture_info_cmd.h" + +namespace OHOS { +namespace DistributedHardware { +class ICameraSinkDataProcess { +public: + ICameraSinkDataProcess() = default; + virtual ~ICameraSinkDataProcess() = default; + + virtual int32_t StartCapture(std::shared_ptr& captureInfo) = 0; + virtual int32_t StopCapture() = 0; + virtual int32_t FeedStream(std::shared_ptr& dataBuffer) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_ICAMERA_SINK_DATA_PROCESS_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_output.h b/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_output.h new file mode 100644 index 0000000000000000000000000000000000000000..2355b70bc05b59862bdc7c2fa39168d792e5de2d --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/interface/icamera_sink_output.h @@ -0,0 +1,42 @@ +/* + * 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_ICAMERA_SINK_OUTPUT_H +#define OHOS_ICAMERA_SINK_OUTPUT_H + +#include +#include +#include + +#include "dcamera_capture_info_cmd.h" +#include "dcamera_channel_info_cmd.h" + +namespace OHOS { +namespace DistributedHardware { +class ICameraSinkOutput { +public: + ICameraSinkOutput() = default; + virtual ~ICameraSinkOutput() = default; + + virtual int32_t Init() = 0; + virtual int32_t UnInit() = 0; + virtual int32_t StartCapture(std::vector>& captureInfos) = 0; + virtual int32_t StopCapture() = 0; + virtual int32_t OpenChannel(std::shared_ptr& info) = 0; + virtual int32_t CloseChannel() = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_ICAMERA_SINK_OUTPUT_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_controller_channel_listener.h b/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_controller_channel_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..1c7d88fa354a5a1fe16154aa07fa0c64e55b637d --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_controller_channel_listener.h @@ -0,0 +1,39 @@ +/* + * 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_DCAMERA_SINK_CONTROLLER_CHANNEL_LISTENER_H +#define OHOS_DCAMERA_SINK_CONTROLLER_CHANNEL_LISTENER_H + +#include "icamera_channel_listener.h" + +#include "dcamera_sink_controller.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkControllerChannelListener : public ICameraChannelListener { +public: + explicit DCameraSinkControllerChannelListener(std::shared_ptr& controller); + ~DCameraSinkControllerChannelListener() = default; + + void OnSessionState(int32_t state) override; + void OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) override; + void OnDataReceived(std::vector>& buffers) override; + +private: + std::weak_ptr controller_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_CONTROLLER_CHANNEL_LISTENER_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_data_process_listener.h b/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_data_process_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..ec6376d38a976fb5a9023d290c3938ac0c269e0f --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_data_process_listener.h @@ -0,0 +1,38 @@ +/* + * 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_DCAMERA_SINK_DATA_PROCESS_LISTENER_H +#define OHOS_DCAMERA_SINK_DATA_PROCESS_LISTENER_H + +#include "data_process_listener.h" + +#include "dcamera_sink_data_process.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkDataProcessListener : public DataProcessListener { +public: + explicit DCameraSinkDataProcessListener(std::shared_ptr& dataProcess); + ~DCameraSinkDataProcessListener() = default; + + void OnProcessedVideoBuffer(const std::shared_ptr& videoResult) override; + void OnError(DataProcessErrorType errorType) override; + +private: + std::weak_ptr dataProcess_; +}; +} // namespace OHOS +} // namespace DistributedHardware +#endif // OHOS_DCAMERA_SINK_DATA_PROCESS_LISTENER_H diff --git a/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_output_channel_listener.h b/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_output_channel_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..65e72912e294c9a4368c83463be0952f92d2b903 --- /dev/null +++ b/services/cameraservice/sinkservice/include/distributedcameramgr/listener/dcamera_sink_output_channel_listener.h @@ -0,0 +1,40 @@ +/* + * 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_DCAMERA_SINK_OUTPUT_CHANNEL_LISTENER_H +#define OHOS_DCAMERA_SINK_OUTPUT_CHANNEL_LISTENER_H + +#include "icamera_channel_listener.h" + +#include "dcamera_sink_output.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkOutputChannelListener : public ICameraChannelListener { +public: + DCameraSinkOutputChannelListener(DCStreamType type, std::shared_ptr& output); + ~DCameraSinkOutputChannelListener() = default; + + void OnSessionState(int32_t state) override; + void OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) override; + void OnDataReceived(std::vector>& buffers) override; + +private: + DCStreamType streamType_; + std::weak_ptr output_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DCAMERA_SINK_OUTPUT_CHANNEL_LISTENER_H \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcamera/distributed_camera_sink_service.cpp b/services/cameraservice/sinkservice/src/distributedcamera/distributed_camera_sink_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..888708d87df08381cd3d3325d610c84e85ac4e06 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcamera/distributed_camera_sink_service.cpp @@ -0,0 +1,256 @@ +/* + * 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 "distributed_camera_sink_service.h" + +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +#include "anonymous_string.h" +#include "dcamera_handler.h" +#include "dcamera_sink_service_ipc.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +REGISTER_SYSTEM_ABILITY_BY_ID(DistributedCameraSinkService, DISTRIBUTED_HARDWARE_CAMERA_SINK_SA_ID, true); + +DistributedCameraSinkService::DistributedCameraSinkService(int32_t saId, bool runOnCreate) + : SystemAbility(saId, runOnCreate) +{ +} + +void DistributedCameraSinkService::OnStart() +{ + DHLOGI("DistributedCameraSinkService::OnStart"); + if (state_ == DCameraServiceState::DCAMERA_SRV_STATE_RUNNING) { + DHLOGI("DistributedCameraSinkService has already started."); + return; + } + + if (!Init()) { + DHLOGE("DistributedCameraSinkService init failed"); + return; + } + state_ = DCameraServiceState::DCAMERA_SRV_STATE_RUNNING; + DHLOGI("DCameraServiceState OnStart service success."); +} + +bool DistributedCameraSinkService::Init() +{ + DHLOGI("DistributedCameraSinkService start init"); + DCameraSinkServiceIpc::GetInstance().Init(); + if (!registerToService_) { + bool ret = Publish(this); + if (!ret) { + DHLOGE("DistributedCameraSinkService Publish service failed"); + return false; + } + registerToService_ = true; + } + DHLOGI("DistributedCameraSinkService init success"); + return true; +} + +void DistributedCameraSinkService::OnStop() +{ + DHLOGI("DistributedCameraSinkService OnStop service"); + state_ = DCameraServiceState::DCAMERA_SRV_STATE_NOT_START; + registerToService_ = false; + DCameraSinkServiceIpc::GetInstance().UnInit(); +} + +int32_t DistributedCameraSinkService::InitSink(const std::string& params) +{ + DHLOGI("DistributedCameraSinkService::InitSink"); + sinkVer_ = params; + int32_t ret = DCameraHandler::GetInstance().Initialize(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::InitSink handler initialize failed, ret: %d", ret); + return ret; + } + + std::vector cameras = DCameraHandler::GetInstance().GetCameras(); + if (cameras.empty()) { + DHLOGE("DistributedCameraSinkService::InitSink no camera device"); + return DCAMERA_BAD_VALUE; + } + for (auto& dhId : cameras) { + std::shared_ptr sinkDevice = std::make_shared(dhId); + ret = sinkDevice->Init(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::InitSink sink device init failed, ret: %d", ret); + return ret; + } + camerasMap_.emplace(dhId, sinkDevice); + } + DHLOGI("DistributedCameraSinkService::InitSink success"); + return DCAMERA_OK; +} + +int32_t DistributedCameraSinkService::ReleaseSink() +{ + DHLOGI("DistributedCameraSinkService::ReleaseSink"); + for (auto iter = camerasMap_.begin(); iter != camerasMap_.end(); iter++) { + std::shared_ptr sinkDevice = iter->second; + int32_t ret = sinkDevice->UnInit(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::ReleaseSink release sink device failed, ret: %d", ret); + } + } + camerasMap_.clear(); + DHLOGI("DistributedCameraSinkService::ReleaseSink success"); + return DCAMERA_OK; +} + +int32_t DistributedCameraSinkService::SubscribeLocalHardware(const std::string& dhId, const std::string& parameters) +{ + DHLOGI("DistributedCameraSinkService::SubscribeLocalHardware dhId: %s", GetAnonyString(dhId).c_str()); + auto iter = camerasMap_.find(dhId); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSinkService::SubscribeLocalHardware device not found"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr sinkDevice = iter->second; + int32_t ret = sinkDevice->SubscribeLocalHardware(parameters); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::SubscribeLocalHardware failed, ret: %d", ret); + return ret; + } + DHLOGI("DistributedCameraSinkService::SubscribeLocalHardware success"); + return DCAMERA_OK; +} + +int32_t DistributedCameraSinkService::UnsubscribeLocalHardware(const std::string& dhId) +{ + DHLOGI("DistributedCameraSinkService::UnsubscribeLocalHardware dhId: %s", GetAnonyString(dhId).c_str()); + auto iter = camerasMap_.find(dhId); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSinkService::UnsubscribeLocalHardware device not found"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr sinkDevice = iter->second; + int32_t ret = sinkDevice->UnsubscribeLocalHardware(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::UnsubscribeLocalHardware failed, ret: %d", ret); + return ret; + } + DHLOGI("DistributedCameraSinkService::UnsubscribeLocalHardware success"); + return DCAMERA_OK; +} + +int32_t DistributedCameraSinkService::StopCapture(const std::string& dhId) +{ + DHLOGI("DistributedCameraSinkService::StopCapture dhId: %s", GetAnonyString(dhId).c_str()); + auto iter = camerasMap_.find(dhId); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSinkService::StopCapture device not found"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr sinkDevice = iter->second; + int32_t ret = sinkDevice->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::StopCapture failed, ret: %d", ret); + return ret; + } + DHLOGI("DistributedCameraSinkService::StopCapture success"); + return DCAMERA_OK; +} + +int32_t DistributedCameraSinkService::ChannelNeg(const std::string& dhId, std::string& channelInfo) +{ + DHLOGI("DistributedCameraSinkService::ChannelNeg dhId: %s", GetAnonyString(dhId).c_str()); + auto iter = camerasMap_.find(dhId); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSinkService::ChannelNeg device not found"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr sinkDevice = iter->second; + int32_t ret = sinkDevice->ChannelNeg(channelInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::ChannelNeg failed, ret: %d", ret); + return ret; + } + DHLOGI("DistributedCameraSinkService::ChannelNeg success"); + return DCAMERA_OK; +} + +int32_t DistributedCameraSinkService::GetCameraInfo(const std::string& dhId, std::string& cameraInfo) +{ + DHLOGI("DistributedCameraSinkService::GetCameraInfo dhId: %s", GetAnonyString(dhId).c_str()); + auto iter = camerasMap_.find(dhId); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSinkService::GetCameraInfo device not found"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr sinkDevice = iter->second; + int32_t ret = sinkDevice->GetCameraInfo(cameraInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::GetCameraInfo failed, ret: %d", ret); + return ret; + } + DHLOGI("DistributedCameraSinkService::GetCameraInfo success"); + return DCAMERA_OK; +} + +int32_t DistributedCameraSinkService::OpenChannel(const std::string& dhId, std::string& openInfo) +{ + DHLOGI("DistributedCameraSinkService::OpenChannel dhId: %s", GetAnonyString(dhId).c_str()); + auto iter = camerasMap_.find(dhId); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSinkService::OpenChannel device not found"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr sinkDevice = iter->second; + int32_t ret = sinkDevice->OpenChannel(openInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::OpenChannel failed, ret: %d", ret); + return ret; + } + DHLOGI("DistributedCameraSinkService::OpenChannel success"); + return DCAMERA_OK; +} + +int32_t DistributedCameraSinkService::CloseChannel(const std::string& dhId) +{ + DHLOGI("DistributedCameraSinkService::CloseChannel dhId: %s", GetAnonyString(dhId).c_str()); + auto iter = camerasMap_.find(dhId); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSinkService::CloseChannel device not found"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr sinkDevice = iter->second; + int32_t ret = sinkDevice->CloseChannel(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSinkService::CloseChannel failed, ret: %d", ret); + return ret; + } + DHLOGI("DistributedCameraSinkService::CloseChannel success"); + return DCAMERA_OK; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcamera/distributed_camera_sink_stub.cpp b/services/cameraservice/sinkservice/src/distributedcamera/distributed_camera_sink_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ebb31524dff4a77b7548c32664dbe536f2bdf67 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcamera/distributed_camera_sink_stub.cpp @@ -0,0 +1,141 @@ +/* + * 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 "distributed_camera_sink_stub.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DistributedCameraSinkStub::DistributedCameraSinkStub() +{ + memberFuncMap_[INIT_SINK] = &DistributedCameraSinkStub::InitSinkInner; + memberFuncMap_[RELEASE_SINK] = &DistributedCameraSinkStub::ReleaseSinkInner; + memberFuncMap_[SUBSCRIBE_LOCAL_HARDWARE] = &DistributedCameraSinkStub::SubscribeLocalHardwareInner; + memberFuncMap_[UNSUBSCRIBE_LOCAL_HARDWARE] = &DistributedCameraSinkStub::UnsubscribeLocalHardwareInner; + memberFuncMap_[STOP_CAPTURE] = &DistributedCameraSinkStub::StopCaptureInner; + memberFuncMap_[CHANNEL_NEG] = &DistributedCameraSinkStub::ChannelNegInner; + memberFuncMap_[GET_CAMERA_INFO] = &DistributedCameraSinkStub::GetCameraInfoInner; + memberFuncMap_[OPEN_CHANNEL] = &DistributedCameraSinkStub::OpenChannelInner; + memberFuncMap_[CLOSE_CHANNEL] = &DistributedCameraSinkStub::CloseChannelInner; +} + +DistributedCameraSinkStub::~DistributedCameraSinkStub() +{} + +int32_t DistributedCameraSinkStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DistributedCameraSinkStub::OnRemoteRequest code: %d", code); + std::u16string desc = DistributedCameraSinkStub::GetDescriptor(); + std::u16string remoteDesc = data.ReadInterfaceToken(); + if (desc != remoteDesc) { + DHLOGE("DistributedCameraSinkStub::OnRemoteRequest remoteDesc is invalid!"); + return ERR_INVALID_DATA; + } + auto itFunc = memberFuncMap_.find(code); + if (itFunc == memberFuncMap_.end()) { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + + auto memberFunc = itFunc->second; + return (this->*memberFunc)(data, reply); +} + +int32_t DistributedCameraSinkStub::InitSinkInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::InitSinkInner"); + std::string params = data.ReadString(); + int32_t ret = InitSink(params); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSinkStub::ReleaseSinkInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::ReleaseSinkInner"); + int32_t ret = ReleaseSink(); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSinkStub::SubscribeLocalHardwareInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::SubscribeLocalHardwareInner"); + std::string dhId = data.ReadString(); + std::string parameters = data.ReadString(); + int32_t ret = SubscribeLocalHardware(dhId, parameters); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSinkStub::UnsubscribeLocalHardwareInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::UnsubscribeLocalHardwareInner"); + std::string dhId = data.ReadString(); + int32_t ret = UnsubscribeLocalHardware(dhId); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSinkStub::StopCaptureInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::StopCaptureInner"); + std::string dhId = data.ReadString(); + int32_t ret = StopCapture(dhId); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSinkStub::ChannelNegInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::ChannelNegInner"); + std::string dhId = data.ReadString(); + std::string channelInfo = data.ReadString(); + int32_t ret = ChannelNeg(dhId, channelInfo); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSinkStub::GetCameraInfoInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::GetCameraInfoInner"); + std::string dhId = data.ReadString(); + std::string cameraInfo = data.ReadString(); + int32_t ret = GetCameraInfo(dhId, cameraInfo); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSinkStub::OpenChannelInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::OpenChannelInner"); + std::string dhId = data.ReadString(); + std::string openInfo = data.ReadString(); + int32_t ret = OpenChannel(dhId, openInfo); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSinkStub::CloseChannelInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSinkStub::CloseChannelInner"); + std::string dhId = data.ReadString(); + int32_t ret = CloseChannel(dhId); + reply.WriteInt32(ret); + return ret; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/callback/dcamera_sink_controller_state_callback.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/callback/dcamera_sink_controller_state_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed6f925590d7ab72378ec0f3e3f0d964cb3c633b --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/callback/dcamera_sink_controller_state_callback.cpp @@ -0,0 +1,47 @@ +/* + * 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 "dcamera_sink_controller_state_callback.h" + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkControllerStateCallback::DCameraSinkControllerStateCallback( + std::shared_ptr& controller) : controller_(controller) +{ +} + +void DCameraSinkControllerStateCallback::OnStateChanged(std::shared_ptr& event) +{ + std::shared_ptr controller = controller_.lock(); + if (controller == nullptr) { + DHLOGE("DCameraSinkControllerStateCallback::OnStateChanged controller is null"); + return; + } + controller->OnStateChanged(event); +} + +void DCameraSinkControllerStateCallback::OnMetadataResult() +{ + std::shared_ptr controller = controller_.lock(); + if (controller == nullptr) { + DHLOGE("DCameraSinkControllerStateCallback::OnMetadataResult controller is null"); + return; + } + controller->OnMetadataResult(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/callback/dcamera_sink_output_result_callback.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/callback/dcamera_sink_output_result_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab2f3cca9a4003bc3d61e47307f77e72265a5fbe --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/callback/dcamera_sink_output_result_callback.cpp @@ -0,0 +1,47 @@ +/* + * 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 "dcamera_sink_output_result_callback.h" + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkOutputResultCallback::DCameraSinkOutputResultCallback( + std::shared_ptr& output) : output_(output) +{ +} + +void DCameraSinkOutputResultCallback::OnPhotoResult(std::shared_ptr& buffer) +{ + std::shared_ptr output = output_.lock(); + if (output == nullptr) { + DHLOGE("DCameraSinkOutputResultCallback::OnPhotoResult output is null"); + return; + } + output->OnPhotoResult(buffer); +} + +void DCameraSinkOutputResultCallback::OnVideoResult(std::shared_ptr& buffer) +{ + std::shared_ptr output = output_.lock(); + if (output == nullptr) { + DHLOGE("DCameraSinkOutputResultCallback::OnVideoResult output is null"); + return; + } + output->OnVideoResult(buffer); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_access_control.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_access_control.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b03992af46f9ba78af9350b5f974381864cae5ba --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_access_control.cpp @@ -0,0 +1,48 @@ +/* + * 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 "dcamera_sink_access_control.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +bool DCameraSinkAccessControl::IsSensitiveSrcAccess(const std::string& srcType) +{ + DHLOGI("DCameraSinkAccessControl::IsSensitiveSrcAccess srcType: %s", srcType.c_str()); + return true; +} + +bool DCameraSinkAccessControl::NotifySensitiveSrc(const std::string& srcType) +{ + DHLOGI("DCameraSinkAccessControl::NotifySensitiveSrc srcType: %s", srcType.c_str()); + return true; +} + +int32_t DCameraSinkAccessControl::TriggerFrame(const std::string& deviceName) +{ + DHLOGI("DCameraSinkAccessControl::TriggerFrame deviceName: %s", deviceName.c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkAccessControl::GetAccessControlType(const std::string& accessType) +{ + DHLOGI("DCameraSinkAccessControl::GetAccessControlType accessType: %s", accessType.c_str()); + return DCAMERA_SAME_ACCOUNT; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_controller.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_controller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40e3388a8f41f30fe54fc856cbc839877ed7a134 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_controller.cpp @@ -0,0 +1,442 @@ +/* + * 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 "dcamera_sink_controller.h" + +#include "anonymous_string.h" +#include "dcamera_channel_sink_impl.h" +#include "dcamera_client.h" +#include "dcamera_metadata_setting_cmd.h" +#include "dcamera_protocol.h" +#include "dcamera_utils_tools.h" + +#include "dcamera_sink_access_control.h" +#include "dcamera_sink_controller_channel_listener.h" +#include "dcamera_sink_controller_state_callback.h" +#include "dcamera_sink_output.h" +#include "dcamera_sink_service_ipc.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" +#include "idistributed_camera_source.h" +#include "json/json.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkController::DCameraSinkController(std::shared_ptr& accessControl) + : isInit_(false), sessionState_(DCAMERA_CHANNEL_STATE_DISCONNECTED), accessControl_(accessControl) +{ +} + +DCameraSinkController::~DCameraSinkController() +{ + if (isInit_) { + UnInit(); + } +} + +int32_t DCameraSinkController::StartCapture(std::vector>& captureInfos) +{ + DHLOGI("DCameraSinkController::StartCapture dhId: %s", GetAnonyString(dhId_).c_str()); + std::string accessType = ""; + if ((accessControl_->IsSensitiveSrcAccess(SRC_TYPE)) && + (accessControl_->GetAccessControlType(accessType) == DCAMERA_SAME_ACCOUNT)) { + int32_t ret = StartCaptureInner(captureInfos); + if (ret == DCAMERA_OK) { + accessControl_->NotifySensitiveSrc(SRC_TYPE); + } + return ret; + } else { + std::string param = ""; + DCameraFrameTriggerEvent triggerEvent(*this, param); + DCameraPostAuthorizationEvent authEvent(*this, captureInfos); + eventBus_->PostEvent(triggerEvent, POSTMODE::POST_ASYNC); + eventBus_->PostEvent(authEvent, POSTMODE::POST_ASYNC); + } + return DCAMERA_OK; +} + +int32_t DCameraSinkController::StopCapture() +{ + std::lock_guard autoLock(captureLock_); + DHLOGI("DCameraSinkController::StopCapture dhId: %s", GetAnonyString(dhId_).c_str()); + int32_t ret = operator_->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::StopCapture client stop capture failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_CAMERA_ERROR, std::string("operator stop capture failed")); + return ret; + } + + ret = output_->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::StopCapture output stop capture failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_CAMERA_ERROR, std::string("output stop capture failed")); + return ret; + } + + DHLOGI("DCameraSinkController::StopCapture %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkController::ChannelNeg(std::shared_ptr& info) +{ + DHLOGI("DCameraSinkController::ChannelNeg dhId: %s", GetAnonyString(dhId_).c_str()); + int32_t ret = output_->OpenChannel(info); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::ChannelNeg channel negotiate failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + DHLOGI("DCameraSinkController::ChannelNeg %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkController::DCameraNotify(std::shared_ptr& events) +{ + DHLOGI("DCameraSinkController::DCameraNotify dhId: %s", GetAnonyString(dhId_).c_str()); + if (srcDevId_.empty()) { + DHLOGE("DCameraSinkController::DCameraNotify source deviceId is empty"); + return DCAMERA_BAD_VALUE; + } + + sptr sourceSA = DCameraSinkServiceIpc::GetInstance().GetSourceRemoteDHMS(srcDevId_); + if (sourceSA == nullptr) { + DHLOGE("DCameraSinkController::DCameraNotify sourceSA is null"); + return DCAMERA_BAD_VALUE; + } + + DCameraEventCmd eventCmd; + std::string jsonStr = ""; + eventCmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE; + eventCmd.dhId_ = dhId_; + eventCmd.command_ = DCAMERA_PROTOCOL_CMD_STATE_NOTIFY; + eventCmd.value_ = events; + int32_t ret = eventCmd.Marshal(jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::DCameraNotify DCameraEventCmd marshal failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + std::string sinkDevId; + ret = GetLocalDeviceNetworkId(sinkDevId); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::DCameraNotify GetLocalDeviceNetworkId failed, devId: %s, dhId: %s, ret: %d", + GetAnonyString(sinkDevId).c_str(), GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + ret = sourceSA->DCameraNotify(sinkDevId, dhId_, jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::DCameraNotify SourceSA notify failed, srcId: %s, sinkId: %s, dhId: %s, ret: %d", + GetAnonyString(srcDevId_).c_str(), GetAnonyString(sinkDevId).c_str(), + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + DHLOGI("DCameraSinkController::DCameraNotify %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkController::UpdateSettings(std::vector>& settings) +{ + DHLOGI("DCameraSinkController::UpdateSettings dhId: %s", GetAnonyString(dhId_).c_str()); + int32_t ret = operator_->UpdateSettings(settings); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::UpdateSettings failed, dhId: %s, ret: %d", GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + DHLOGI("DCameraSinkController::UpdateSettings %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkController::GetCameraInfo(std::shared_ptr& camInfo) +{ + DHLOGI("DCameraSinkController::GetCameraInfo dhId: %s, session state: %d", + GetAnonyString(dhId_).c_str(), sessionState_); + camInfo->state_ = sessionState_; + return DCAMERA_OK; +} + +int32_t DCameraSinkController::OpenChannel(std::shared_ptr& openInfo) +{ + DHLOGI("DCameraSinkController::OpenChannel dhId: %s", GetAnonyString(dhId_).c_str()); + if (sessionState_ != DCAMERA_CHANNEL_STATE_DISCONNECTED) { + DHLOGE("DCameraSinkController::OpenChannel wrong state, dhId: %s, sessionState: %d", + GetAnonyString(dhId_).c_str(), sessionState_); + return DCAMERA_WRONG_STATE; + } + srcDevId_ = openInfo->sourceDevId_; + std::vector indexs; + indexs.push_back(DCameraIndex(srcDevId_, dhId_)); + auto controller = std::shared_ptr(shared_from_this()); + std::shared_ptr listener = + std::make_shared(controller); + int32_t ret = channel_->CreateSession(indexs, SESSION_FLAG, DCAMERA_SESSION_MODE_CTRL, listener); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::Init channel create session failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + DHLOGI("DCameraSinkController::OpenChannel %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkController::CloseChannel() +{ + std::lock_guard autoLock(channelLock_); + DHLOGI("DCameraSinkController::CloseChannel dhId: %s", GetAnonyString(dhId_).c_str()); + DCameraSinkServiceIpc::GetInstance().DeleteSourceRemoteDhms(srcDevId_); + srcDevId_.clear(); + int32_t ret = channel_->ReleaseSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController release channel failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + } + + ret = output_->CloseChannel(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController CloseChannel failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + } + sessionState_ = DCAMERA_CHANNEL_STATE_DISCONNECTED; + DHLOGI("DCameraSinkController::CloseChannel %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkController::Init(std::vector& indexs) +{ + DHLOGI("DCameraSinkController::Init"); + dhId_ = indexs[0].dhId_; + operator_ = std::make_shared(dhId_); + output_ = std::make_shared(dhId_, operator_); + int32_t ret = output_->Init(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::Init output init failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + auto controller = std::shared_ptr(shared_from_this()); + std::shared_ptr stateCallback = std::make_shared(controller); + operator_->SetStateCallback(stateCallback); + ret = operator_->Init(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::Init operator init failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + channel_ = std::make_shared(); + eventBus_ = std::make_shared(); + DCameraFrameTriggerEvent triggerEvent(*this); + DCameraPostAuthorizationEvent authEvent(*this); + eventBus_->AddHandler(triggerEvent.GetType(), *this); + eventBus_->AddHandler(authEvent.GetType(), *this); + + isInit_ = true; + DHLOGI("DCameraSinkController::Init %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkController::UnInit() +{ + DHLOGI("DCameraSinkController::UnInit dhId: %s", GetAnonyString(dhId_).c_str()); + if (output_ != nullptr) { + int32_t ret = output_->UnInit(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController release output failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + } + } + + if (operator_ != nullptr) { + int32_t ret = operator_->UnInit(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController release operator failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + } + } + + isInit_ = false; + DHLOGI("DCameraSinkController::UnInit %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +void DCameraSinkController::OnEvent(DCameraFrameTriggerEvent& event) +{ + std::string param = event.GetParam(); + accessControl_->TriggerFrame(param); +} + +void DCameraSinkController::OnEvent(DCameraPostAuthorizationEvent& event) +{ + std::vector> captureInfos = event.GetParam(); + PostAuthorization(captureInfos); +} + +void DCameraSinkController::OnStateChanged(std::shared_ptr& event) +{ + DHLOGI("DCameraSinkController::OnStateChanged dhId: %s, result: %d", + GetAnonyString(dhId_).c_str(), event->eventResult_); + DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_CAMERA_ERROR, std::string("camera error")); +} + +void DCameraSinkController::OnMetadataResult() +{ + DHLOGI("DCameraSinkController::OnMetadataResult dhId: %s", GetAnonyString(dhId_).c_str()); +} + +void DCameraSinkController::OnSessionState(int32_t state) +{ + DHLOGI("DCameraSinkController::OnSessionState dhId: %s, state: %d", GetAnonyString(dhId_).c_str(), state); + sessionState_ = state; + switch (state) { + case DCAMERA_CHANNEL_STATE_CONNECTING: { + DHLOGI("DCameraSinkController::OnSessionState channel is connecting"); + break; + } + case DCAMERA_CHANNEL_STATE_CONNECTED: { + DHLOGI("DCameraSinkController::OnSessionState channel is connected"); + break; + } + case DCAMERA_CHANNEL_STATE_DISCONNECTED: { + DHLOGI("DCameraSinkController::OnSessionState channel is disconnected"); + int32_t ret = StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::OnSessionState session state: %d, %s stop capture failed, ret: %d", + sessionState_, GetAnonyString(dhId_).c_str(), ret); + } + ret = CloseChannel(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::OnSessionState session state: %d, %s close channel failed, ret: %d", + sessionState_, GetAnonyString(dhId_).c_str(), ret); + } + break; + } + default: { + DHLOGE("DCameraSinkController::OnSessionState unknown session state"); + break; + } + } +} + +void DCameraSinkController::OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) +{ + DHLOGI("DCameraSinkController::OnSessionError dhId: %s, eventType: %d, eventReason: %d, detail: %s", + GetAnonyString(dhId_).c_str(), eventType, eventReason, detail.c_str()); +} + +void DCameraSinkController::OnDataReceived(std::vector>& buffers) +{ + DHLOGI("DCameraSinkController::OnReceivedData %s control channel receive data", GetAnonyString(dhId_).c_str()); + for (auto& buffer : buffers) { + HandleReceivedData(buffer); + } +} + +void DCameraSinkController::PostAuthorization(std::vector>& captureInfos) +{ + DHLOGI("DCameraSinkController::PostAuthorization dhId: %s", GetAnonyString(dhId_).c_str()); + int32_t ret = StartCaptureInner(captureInfos); + if (ret == DCAMERA_OK) { + accessControl_->NotifySensitiveSrc(SRC_TYPE); + } +} + +int32_t DCameraSinkController::StartCaptureInner(std::vector>& captureInfos) +{ + std::lock_guard autoLock(captureLock_); + DHLOGI("DCameraSinkController::StartCaptureInner dhId: %s", GetAnonyString(dhId_).c_str()); + int32_t ret = output_->StartCapture(captureInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::StartCaptureInner output start capture failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_CAMERA_ERROR, std::string("output start capture failed")); + return ret; + } + + ret = operator_->StartCapture(captureInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::StartCaptureInner camera client start capture failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_CAMERA_ERROR, std::string("operator start capture failed")); + return ret; + } + + DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_CAMERA_SUCCESS, std::string("operator start capture success")); + DHLOGI("DCameraSinkController::StartCaptureInner %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkController::DCameraNotifyInner(int32_t type, int32_t result, std::string reason) +{ + std::shared_ptr event = std::make_shared(); + event->eventType_ = type; + event->eventResult_ = result; + event->eventContent_ = reason; + return DCameraNotify(event); +} + +int32_t DCameraSinkController::HandleReceivedData(std::shared_ptr& dataBuffer) +{ + DHLOGI("DCameraSinkController::HandleReceivedData dhId: %s", GetAnonyString(dhId_).c_str()); + uint8_t *data = dataBuffer->Data(); + std::string jsonStr((const char *)data, dataBuffer->Capacity()); + + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value root; + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if ((!jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &root, &errs)) || + (!root.isObject())) { + DHLOGE("DCameraSinkController::HandleReceivedData parse json string failed"); + return DCAMERA_BAD_VALUE; + } + + if ((!root.isMember("Command")) || (!root["Command"].isString())) { + DHLOGE("DCameraSinkController::HandleReceivedData parse command failed"); + return DCAMERA_BAD_VALUE; + } + + std::string command = root["Command"].asString(); + if ((!command.empty()) && (command.compare(DCAMERA_PROTOCOL_CMD_CAPTURE) == 0)) { + DCameraCaptureInfoCmd captureInfoCmd; + int ret = captureInfoCmd.Unmarshal(jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::HandleReceivedData Capture Info Unmarshal failed, dhId: %s ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + return StartCapture(captureInfoCmd.value_); + } else if ((!command.empty()) && (command.compare(DCAMERA_PROTOCOL_CMD_UPDATE_METADATA) == 0)) { + DCameraMetadataSettingCmd metadataSettingCmd; + int ret = metadataSettingCmd.Unmarshal(jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkController::HandleReceivedData Metadata Setting Unmarshal failed, dhId: %s ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + return UpdateSettings(metadataSettingCmd.value_); + } + return DCAMERA_BAD_VALUE; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_data_process.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_data_process.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d870b710ef4fbe0b16b1ff1c5a691851d21c0188 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_data_process.cpp @@ -0,0 +1,185 @@ +/* + * 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 "dcamera_sink_data_process.h" + +#include "anonymous_string.h" +#include "dcamera_channel_sink_impl.h" +#include "dcamera_pipeline_sink.h" +#include "dcamera_sink_data_process_listener.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkDataProcess::DCameraSinkDataProcess(const std::string& dhId, std::shared_ptr& channel) + : dhId_(dhId), channel_(channel) +{ + DHLOGI("DCameraSinkDataProcess Constructor dhId: %s", GetAnonyString(dhId_).c_str()); + eventBus_ = std::make_shared(); + DCameraPhotoOutputEvent photoEvent(*this); + DCameraVideoOutputEvent videoEvent(*this); + eventBus_->AddHandler(photoEvent.GetType(), *this); + eventBus_->AddHandler(videoEvent.GetType(), *this); +} + +int32_t DCameraSinkDataProcess::StartCapture(std::shared_ptr& captureInfo) +{ + DHLOGI("DCameraSinkDataProcess::StartCapture dhId: %s, width: %d, height: %d, format: %d, stream: %d, encode: %d", + GetAnonyString(dhId_).c_str(), captureInfo->width_, captureInfo->height_, captureInfo->format_, + captureInfo->streamType_, captureInfo->encodeType_); + captureInfo_ = captureInfo; + if (pipeline_ != nullptr) { + DHLOGI("DCameraSinkDataProcess::StartCapture %s pipeline already exits", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; + } + + if ((captureInfo->streamType_ == CONTINUOUS_FRAME) && (captureInfo->format_ != captureInfo->encodeType_)) { + DHLOGI("DCameraSinkDataProcess::StartCapture %s create data process pipeline", GetAnonyString(dhId_).c_str()); + pipeline_ = std::make_shared(); + auto dataProcess = std::shared_ptr(shared_from_this()); + std::shared_ptr listener = std::make_shared(dataProcess); + VideoConfigParams srcParams(VideoCodecType::NO_CODEC, + GetPipelineFormat(captureInfo->format_), + DCAMERA_PRODUCER_FPS_DEFAULT, + captureInfo->width_, + captureInfo->height_); + VideoConfigParams destParams(GetPipelineCodecType(captureInfo->encodeType_), + GetPipelineFormat(captureInfo->format_), + DCAMERA_PRODUCER_FPS_DEFAULT, + captureInfo->width_, + captureInfo->height_); + int32_t ret = pipeline_->CreateDataProcessPipeline(PipelineType::VIDEO, srcParams, destParams, listener); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDataProcess::StartCapture create data process pipeline failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + } + DHLOGI("DCameraSinkDataProcess::StartCapture %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkDataProcess::StopCapture() +{ + DHLOGI("DCameraSinkDataProcess::StopCapture dhId: %s", GetAnonyString(dhId_).c_str()); + if (pipeline_ != nullptr) { + pipeline_->DestroyDataProcessPipeline(); + pipeline_ = nullptr; + } + return DCAMERA_OK; +} + +int32_t DCameraSinkDataProcess::FeedStream(std::shared_ptr& dataBuffer) +{ + DCStreamType type = captureInfo_->streamType_; + DHLOGI("DCameraSinkDataProcess::FeedStream dhId: %s, stream type: %d", GetAnonyString(dhId_).c_str(), type); + switch (type) { + case CONTINUOUS_FRAME: { + int32_t ret = FeedStreamInner(dataBuffer); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDataProcess::FeedStream continuous frame failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + break; + } + case SNAPSHOT_FRAME: { + DCameraPhotoOutputEvent photoEvent(*this, dataBuffer); + eventBus_->PostEvent(photoEvent, POSTMODE::POST_ASYNC); + break; + } + default: { + DHLOGE("DCameraSinkDataProcess::FeedStream %s unknown stream type: %d", + GetAnonyString(dhId_).c_str(), type); + break; + } + } + DHLOGI("DCameraSinkDataProcess::FeedStream %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +void DCameraSinkDataProcess::OnEvent(DCameraPhotoOutputEvent& event) +{ + std::shared_ptr buffer = event.GetParam(); + int32_t ret = channel_->SendData(buffer); + DHLOGI("DCameraSinkDataProcess::OnEvent %s send photo output data ret: %d", GetAnonyString(dhId_).c_str(), ret); +} + +void DCameraSinkDataProcess::OnEvent(DCameraVideoOutputEvent& event) +{ + std::shared_ptr buffer = event.GetParam(); + int32_t ret = channel_->SendData(buffer); + DHLOGI("DCameraSinkDataProcess::OnEvent %s send video output data ret: %d", GetAnonyString(dhId_).c_str(), ret); +} + +void DCameraSinkDataProcess::OnProcessedVideoBuffer(const std::shared_ptr& videoResult) +{ + DCameraVideoOutputEvent videoEvent(*this, videoResult); + eventBus_->PostEvent(videoEvent, POSTMODE::POST_ASYNC); +} + +void DCameraSinkDataProcess::OnError(DataProcessErrorType errorType) +{ + DHLOGE("DCameraSinkDataProcess::OnError %s data process pipeline error, errorType: %d", + GetAnonyString(dhId_).c_str(), errorType); +} + +int32_t DCameraSinkDataProcess::FeedStreamInner(std::shared_ptr& dataBuffer) +{ + DHLOGI("DCameraSinkDataProcess::FeedStreamInner dhId: %s", GetAnonyString(dhId_).c_str()); + if (captureInfo_->format_ == captureInfo_->encodeType_) { + DHLOGI("DCameraSinkDataProcess::FeedStreamInner %s send video buffer", GetAnonyString(dhId_).c_str()); + DCameraVideoOutputEvent videoEvent(*this, dataBuffer); + eventBus_->PostEvent(videoEvent, POSTMODE::POST_ASYNC); + return DCAMERA_OK; + } + + std::vector> buffers; + buffers.push_back(dataBuffer); + int32_t ret = pipeline_->ProcessData(buffers); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDataProcess::FeedStreamInner process data failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + DHLOGI("DCameraSinkDataProcess::FeedStreamInner %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +VideoCodecType DCameraSinkDataProcess::GetPipelineCodecType(DCEncodeType encodeType) +{ + VideoCodecType codecType; + switch (encodeType) { + case ENCODE_TYPE_H264: + codecType = VideoCodecType::CODEC_H264; + break; + case ENCODE_TYPE_H265: + codecType = VideoCodecType::CODEC_H265; + break; + default: + codecType = VideoCodecType::NO_CODEC; + break; + } + return codecType; +} + +Videoformat DCameraSinkDataProcess::GetPipelineFormat(int32_t format) +{ + return Videoformat::NV21; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_dev.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_dev.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9db8f9f5fd53956896c5f528b30921796c055ef --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_dev.cpp @@ -0,0 +1,160 @@ +/* + * 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 "dcamera_sink_dev.h" + +#include "anonymous_string.h" +#include "dcamera_channel_info_cmd.h" +#include "dcamera_info_cmd.h" +#include "dcamera_protocol.h" +#include "dcamera_sink_access_control.h" +#include "dcamera_sink_controller.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkDev::DCameraSinkDev(const std::string& dhId) : dhId_(dhId) +{ + DHLOGI("DCameraSinkDev Constructor dhId: %s", GetAnonyString(dhId_).c_str()); + isInit_ = false; +} + +DCameraSinkDev::~DCameraSinkDev() +{ + if (isInit_) { + UnInit(); + } +} + +int32_t DCameraSinkDev::Init() +{ + DHLOGI("DCameraSinkDev::Init dhId: %s", GetAnonyString(dhId_).c_str()); + accessControl_ = std::make_shared(); + controller_ = std::make_shared(accessControl_); + DCameraIndex index("", dhId_); + std::vector indexs; + indexs.push_back(index); + int32_t ret = controller_->Init(indexs); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDev::Init init controller failed, dhId: %s, ret: %d", GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + isInit_ = true; + DHLOGI("DCameraSinkDev::Init %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkDev::UnInit() +{ + if (controller_ != nullptr) { + int32_t ret = controller_->UnInit(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDev::UnInit release controller failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + } + } + isInit_ = false; + return DCAMERA_OK; +} + +int32_t DCameraSinkDev::SubscribeLocalHardware(const std::string& parameters) +{ + DHLOGI("DCameraSinkDev::SubscribeLocalHardware"); + return DCAMERA_OK; +} + +int32_t DCameraSinkDev::UnsubscribeLocalHardware() +{ + DHLOGI("DCameraSinkDev::UnsubscribeLocalHardware"); + return DCAMERA_OK; +} + +int32_t DCameraSinkDev::StopCapture() +{ + DHLOGI("DCameraSinkDev::StopCapture dhId: %s", GetAnonyString(dhId_).c_str()); + return controller_->StopCapture(); +} + +int32_t DCameraSinkDev::ChannelNeg(std::string& channelInfo) +{ + DHLOGI("DCameraSinkDev::ChannelNeg dhId: %s", GetAnonyString(dhId_).c_str()); + if (channelInfo.empty()) { + DHLOGE("DCameraSinkDev::ChannelNeg channelInfo is empty"); + return DCAMERA_BAD_VALUE; + } + + DCameraChannelInfoCmd channelInfoCmd; + int32_t ret = channelInfoCmd.Unmarshal(channelInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDev::ChannelNeg channelInfo unmarshal failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + return controller_->ChannelNeg(channelInfoCmd.value_); +} + +int32_t DCameraSinkDev::GetCameraInfo(std::string& cameraInfo) +{ + DHLOGI("DCameraSinkDev::GetCameraInfo dhId: %s", GetAnonyString(dhId_).c_str()); + std::shared_ptr info = std::make_shared(); + int32_t ret = controller_->GetCameraInfo(info); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDev::GetCameraInfo get state failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + DCameraInfoCmd cameraInfoCmd; + cameraInfoCmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE; + cameraInfoCmd.dhId_ = dhId_; + cameraInfoCmd.command_ = DCAMERA_PROTOCOL_CMD_GET_INFO; + cameraInfoCmd.value_ = info; + ret = cameraInfoCmd.Marshal(cameraInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDev::GetCameraInfo cameraInfoCmd marshal failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + DHLOGI("DCameraSinkDev::GetCameraInfo %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkDev::OpenChannel(std::string& openInfo) +{ + DHLOGI("DCameraSinkDev::OpenChannel dhId: %s", GetAnonyString(dhId_).c_str()); + if (openInfo.empty()) { + DHLOGE("DCameraSinkDev::OpenChannel openInfo is empty"); + return DCAMERA_BAD_VALUE; + } + + DCameraOpenInfoCmd cmd; + int32_t ret = cmd.Unmarshal(openInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkDev::OpenChannel openInfo unmarshal failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + return controller_->OpenChannel(cmd.value_); +} + +int32_t DCameraSinkDev::CloseChannel() +{ + DHLOGI("DCameraSinkDev::CloseChannel dhId: %s", GetAnonyString(dhId_).c_str()); + return controller_->CloseChannel(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_output.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_output.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7397bb8d54e7b8f528a7421ea7af1293c9d382a4 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_output.cpp @@ -0,0 +1,234 @@ +/* + * 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 "dcamera_sink_output.h" + +#include "anonymous_string.h" +#include "dcamera_channel_sink_impl.h" +#include "dcamera_client.h" +#include "dcamera_sink_data_process.h" +#include "dcamera_sink_output_channel_listener.h" +#include "dcamera_sink_output_result_callback.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkOutput::DCameraSinkOutput(const std::string& dhId, std::shared_ptr& cameraOperator) + : dhId_(dhId), operator_(cameraOperator) +{ + DHLOGI("DCameraSinkOutput Constructor dhId: %s", GetAnonyString(dhId_).c_str()); + isInit_ = false; +} + +DCameraSinkOutput::~DCameraSinkOutput() +{ + if (isInit_) { + UnInit(); + } +} + +int32_t DCameraSinkOutput::Init() +{ + DHLOGI("DCameraSinkOutput::Init dhId: %s", GetAnonyString(dhId_).c_str()); + auto output = std::shared_ptr(shared_from_this()); + std::shared_ptr resultCallback = std::make_shared(output); + operator_->SetResultCallback(resultCallback); + + InitInner(CONTINUOUS_FRAME); + InitInner(SNAPSHOT_FRAME); + isInit_ = true; + DHLOGI("DCameraSinkOutput::Init %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +void DCameraSinkOutput::InitInner(DCStreamType type) +{ + std::shared_ptr channel = std::make_shared(); + std::shared_ptr dataProcess = std::make_shared(dhId_, channel); + dataProcesses_.emplace(type, dataProcess); + channels_.emplace(type, channel); + sessionState_.emplace(type, DCAMERA_CHANNEL_STATE_DISCONNECTED); +} + +int32_t DCameraSinkOutput::UnInit() +{ + DHLOGI("DCameraSinkOutput::UnInit dhId: %s", GetAnonyString(dhId_).c_str()); + channels_.clear(); + dataProcesses_.clear(); + sessionState_.clear(); + isInit_ = false; + DHLOGI("DCameraSinkOutput::UnInit %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSinkOutput::OpenChannel(std::shared_ptr& info) +{ + DHLOGI("DCameraSinkOutput::OpenChannel dhId: %s", GetAnonyString(dhId_).c_str()); + std::map modeMaps; + modeMaps.emplace(CONTINUOUS_FRAME, DCAMERA_SESSION_MODE_VIDEO); + modeMaps.emplace(SNAPSHOT_FRAME, DCAMERA_SESSION_MODE_JPEG); + std::vector indexs; + indexs.push_back(DCameraIndex(info->sourceDevId_, dhId_)); + for (auto iter = info->detail_.begin(); iter != info->detail_.end(); iter++) { + if (sessionState_[iter->streamType_] != DCAMERA_CHANNEL_STATE_DISCONNECTED) { + DHLOGE("DCameraSinkOutput::OpenChannel wrong state, sessionState: %d", sessionState_[iter->streamType_]); + return DCAMERA_WRONG_STATE; + } + auto iterCh = channels_.find(iter->streamType_); + if (iterCh == channels_.end()) { + continue; + } + auto output = std::shared_ptr(shared_from_this()); + std::shared_ptr channelListener = + std::make_shared(iter->streamType_, output); + int32_t ret = iterCh->second->CreateSession(indexs, iter->dataSessionFlag_, modeMaps[iter->streamType_], + channelListener); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkOutput::Init channel create session failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + } + return DCAMERA_OK; +} + +int32_t DCameraSinkOutput::CloseChannel() +{ + DHLOGI("DCameraSinkOutput::CloseChannel dhId: %s", GetAnonyString(dhId_).c_str()); + int32_t ret = DCAMERA_OK; + auto iterCon = channels_.find(CONTINUOUS_FRAME); + if (iterCon != channels_.end()) { + ret = iterCon->second->ReleaseSession(); + if (ret != DCAMERA_OK) { + DHLOGI("DCameraSinkOutput UnInit release continue session failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + } + sessionState_[CONTINUOUS_FRAME] = DCAMERA_CHANNEL_STATE_DISCONNECTED; + } + + auto iterSnap = channels_.find(SNAPSHOT_FRAME); + if (iterSnap != channels_.end()) { + ret = iterSnap->second->ReleaseSession(); + if (ret != DCAMERA_OK) { + DHLOGI("DCameraSinkOutput UnInit release snapshot session failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + } + sessionState_[SNAPSHOT_FRAME] = DCAMERA_CHANNEL_STATE_DISCONNECTED; + } + return DCAMERA_OK; +} + +int32_t DCameraSinkOutput::StartCapture(std::vector>& captureInfos) +{ + DHLOGI("DCameraSinkOutput::StartCapture dhId: %s", GetAnonyString(dhId_).c_str()); + for (auto& info : captureInfos) { + if (dataProcesses_.find(info->streamType_) == dataProcesses_.end()) { + DHLOGE("DCameraSinkOutput::StartCapture has no data process, streamType: %d", info->streamType_); + break; + } + int32_t ret = dataProcesses_[info->streamType_]->StartCapture(info); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkOutput::StartCapture failed, dhId: %s, ret: %d", GetAnonyString(dhId_).c_str(), ret); + return ret; + } + } + return DCAMERA_OK; +} + +int32_t DCameraSinkOutput::StopCapture() +{ + DHLOGI("DCameraSinkOutput::StopCapture dhId: %s", GetAnonyString(dhId_).c_str()); + int32_t ret = dataProcesses_[CONTINUOUS_FRAME]->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkOutput::StopCapture continuous data process stop capture failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + ret = dataProcesses_[SNAPSHOT_FRAME]->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSinkOutput::StopCapture snapshot data process stop capture failed, dhId: %s, ret: %d", + GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + DHLOGI("DCameraSinkOutput::StopCapture %s success", GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +void DCameraSinkOutput::OnVideoResult(std::shared_ptr& buffer) +{ + if (sessionState_[CONTINUOUS_FRAME] != DCAMERA_CHANNEL_STATE_CONNECTED) { + DHLOGE("DCameraSinkOutput::OnVideoResult dhId: %s, channel state: %d", + GetAnonyString(dhId_).c_str(), sessionState_[CONTINUOUS_FRAME]); + return; + } + if (dataProcesses_.find(CONTINUOUS_FRAME) == dataProcesses_.end()) { + DHLOGE("DCameraSinkOutput::OnVideoResult %s has no continuous data process", GetAnonyString(dhId_).c_str()); + return; + } + dataProcesses_[CONTINUOUS_FRAME]->FeedStream(buffer); +} + +void DCameraSinkOutput::OnPhotoResult(std::shared_ptr& buffer) +{ + if (dataProcesses_.find(SNAPSHOT_FRAME) == dataProcesses_.end()) { + DHLOGE("DCameraSinkOutput::OnPhotoResult %s has no snapshot data process", GetAnonyString(dhId_).c_str()); + return; + } + dataProcesses_[SNAPSHOT_FRAME]->FeedStream(buffer); +} + +void DCameraSinkOutput::OnSessionState(DCStreamType type, int32_t state) +{ + DHLOGI("DCameraSinkOutput::OnSessionState dhId: %s, stream type: %d, state: %d", + GetAnonyString(dhId_).c_str(), type, state); + sessionState_[type] = state; + switch (state) { + case DCAMERA_CHANNEL_STATE_CONNECTING: { + DHLOGI("DCameraSinkOutput::OnSessionState channel is connecting, dhId: %s, stream type: %d", + GetAnonyString(dhId_).c_str(), type); + break; + } + case DCAMERA_CHANNEL_STATE_CONNECTED: { + DHLOGI("DCameraSinkOutput::OnSessionState channel is connected, dhId: %s, stream type: %d", + GetAnonyString(dhId_).c_str(), type); + break; + } + case DCAMERA_CHANNEL_STATE_DISCONNECTED: { + DHLOGI("DCameraSinkOutput::OnSessionState channel is disconnected, dhId: %s, stream type: %d", + GetAnonyString(dhId_).c_str(), type); + break; + } + default: { + DHLOGE("DCameraSinkOutput::OnSessionState %s unknown session state", GetAnonyString(dhId_).c_str()); + break; + } + } +} + +void DCameraSinkOutput::OnSessionError(DCStreamType type, int32_t eventType, int32_t eventReason, std::string detail) +{ + DHLOGI("DCameraSinkOutput::OnSessionError dhId: %s, stream type: %d, eventType: %d, eventReason: %d, detail: %s", + GetAnonyString(dhId_).c_str(), type, eventType, eventReason, detail.c_str()); +} + +void DCameraSinkOutput::OnDataReceived(DCStreamType type, std::vector>& dataBuffers) +{ +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_service_ipc.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_service_ipc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7cc2b1dd45927dcc13a04ecabf921ec25fb14261 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/dcamera_sink_service_ipc.cpp @@ -0,0 +1,191 @@ +/* + * 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 "dcamera_sink_service_ipc.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkServiceIpc::DCameraSinkServiceIpc() : isInit_(false) +{ + DHLOGI("DCameraSinkServiceIpc Create"); +} + +DCameraSinkServiceIpc::~DCameraSinkServiceIpc() +{ + DHLOGI("DCameraSinkServiceIpc Delete"); + UnInit(); +} + +IMPLEMENT_SINGLE_INSTANCE(DCameraSinkServiceIpc); + +void DCameraSinkServiceIpc::Init() +{ + std::lock_guard autoLock(initDmsLock_); + DHLOGI("DCameraSinkServiceIpc Init Start"); + if (isInit_) { + DHLOGI("DCameraSinkServiceIpc has already init"); + return; + } + auto runner = AppExecFwk::EventRunner::Create("DCameraSinkServiceIpcHandler"); + serviceHandler_ = std::make_shared(runner); + sourceRemoteRecipient_ = new SourceRemoteRecipient(); + isInit_ = true; + DHLOGI("DCameraSinkServiceIpc Init End"); +} + +void DCameraSinkServiceIpc::UnInit() +{ + std::lock_guard autoLock(initDmsLock_); + DHLOGI("DCameraSinkServiceIpc UnInit Start"); + if (!isInit_) { + DHLOGI("DCameraSinkServiceIpc has already UnInit"); + return; + } + ClearSourceRemoteDhms(); + DHLOGI("DCameraSinkServiceIpc Start free serviceHandler"); + serviceHandler_ = nullptr; + DHLOGI("DCameraSinkServiceIpc Start free recipient"); + sourceRemoteRecipient_ = nullptr; + isInit_ = false; + DHLOGI("DCameraSinkServiceIpc UnInit End"); +} + +sptr DCameraSinkServiceIpc::GetSourceRemoteDHMS(const std::string& deviceId) +{ + if (deviceId.empty()) { + DHLOGE("GetSourceRemoteDHMS deviceId is empty"); + return nullptr; + } + { + std::lock_guard autoLock(sourceRemoteDmsLock_); + auto iter = remoteSources_.find(deviceId); + if (iter != remoteSources_.end()) { + auto object = iter->second; + if (object != nullptr) { + DHLOGI("DCameraSinkServiceIpc GetSourceRemoteDHMS from cache devId: %s", + GetAnonyString(deviceId).c_str()); + return object; + } + } + } + DHLOGI("GetSourceRemoteDHMS remote deviceid is %s", GetAnonyString(deviceId).c_str()); + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + DHLOGE("GetSourceRemoteDHMS failed to connect to systemAbilityMgr!"); + return nullptr; + } + + auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_CAMERA_SOURCE_SA_ID, deviceId); + if (object == nullptr) { + DHLOGE("GetSourceRemoteDHMS failed get remote DHMS %s", GetAnonyString(deviceId).c_str()); + return nullptr; + } + int32_t ret = object->AddDeathRecipient(sourceRemoteRecipient_); + sptr remoteDmsObj = iface_cast(object); + if (remoteDmsObj == nullptr) { + DHLOGI("GetSourceRemoteDHMS failed, remoteDmsObj is null ret: %d", ret); + return nullptr; + } + { + std::lock_guard autoLock(sourceRemoteDmsLock_); + auto iter = remoteSources_.find(deviceId); + if (iter != remoteSources_.end()) { + iter->second->AsObject()->RemoveDeathRecipient(sourceRemoteRecipient_); + } + remoteSources_[deviceId] = remoteDmsObj; + } + DHLOGI("GetSourceRemoteDHMS success, AddDeathRecipient ret: %d", ret); + return remoteDmsObj; +} + +void DCameraSinkServiceIpc::DeleteSourceRemoteDhms(const std::string& deviceId) +{ + DHLOGI("DeleteSourceRemoteDhms devId: %s", GetAnonyString(deviceId).c_str()); + std::lock_guard autoLock(sourceRemoteDmsLock_); + auto item = remoteSources_.find(deviceId); + if (item == remoteSources_.end()) { + DHLOGI("DeleteSourceRemoteDhms not found device: %s", GetAnonyString(deviceId).c_str()); + return; + } + + if (item->second != nullptr) { + item->second->AsObject()->RemoveDeathRecipient(sourceRemoteRecipient_); + } + remoteSources_.erase(item); +} + +void DCameraSinkServiceIpc::ClearSourceRemoteDhms() +{ + DHLOGI("ClearSourceRemoteDhms Start"); + std::lock_guard autoLock(sourceRemoteDmsLock_); + for (auto iter = remoteSources_.begin(); iter != remoteSources_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->AsObject()->RemoveDeathRecipient(sourceRemoteRecipient_); + } + } + remoteSources_.clear(); + DHLOGI("ClearSourceRemoteDhms end"); +} + +void DCameraSinkServiceIpc::SourceRemoteRecipient::OnRemoteDied(const wptr& remote) +{ + DHLOGI("SourceRemoteRecipient OnRemoteDied received died notify!"); + DCameraSinkServiceIpc::GetInstance().OnSourceRemoteDmsDied(remote); +} + +void DCameraSinkServiceIpc::OnSourceRemoteDmsDied(const wptr& remote) +{ + sptr diedRemoted = remote.promote(); + if (diedRemoted == nullptr) { + DHLOGE("OnSourceRemoteDmsDied promote failed!"); + return; + } + DHLOGI("OnSourceRemoteDmsDied delete diedRemoted"); + auto remoteDmsDiedFunc = [this, diedRemoted]() { + OnSourceRemoteDmsDied(diedRemoted); + }; + if (serviceHandler_ != nullptr) { + serviceHandler_->PostTask(remoteDmsDiedFunc); + } +} + +void DCameraSinkServiceIpc::OnSourceRemoteDmsDied(const sptr& remote) +{ + std::lock_guard autoLock(sourceRemoteDmsLock_); + auto iter = std::find_if(remoteSources_.begin(), remoteSources_.end(), [&]( + const std::pair> &item)->bool { + return item.second->AsObject() == remote; + }); + if (iter == remoteSources_.end()) { + DHLOGI("OnSourceRemoteDmsDied not found remote object"); + return; + } + + DHLOGI("OnSourceRemoteDmsDied remote.devId: %s", GetAnonyString(iter->first).c_str()); + if (iter->second != nullptr) { + iter->second->AsObject()->RemoveDeathRecipient(sourceRemoteRecipient_); + } + remoteSources_.erase(iter); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_frame_trigger_event.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_frame_trigger_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ef08a79944cc33d3cd7743ac1daef96d7393b14 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_frame_trigger_event.cpp @@ -0,0 +1,34 @@ +/* + * 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 "dcamera_frame_trigger_event.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraFrameTriggerEvent::DCameraFrameTriggerEvent(EventSender& sender) : Event(sender) +{ +} + +DCameraFrameTriggerEvent::DCameraFrameTriggerEvent(EventSender& sender, std::string& param) + : Event(sender), param_(param) +{ +} + +std::string DCameraFrameTriggerEvent::GetParam() +{ + return param_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_photo_output_event.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_photo_output_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1db88ea722bc6b771c5e31cabb023dcd3db4aea6 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_photo_output_event.cpp @@ -0,0 +1,34 @@ +/* + * 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 "dcamera_photo_output_event.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraPhotoOutputEvent::DCameraPhotoOutputEvent(EventSender& sender) : Event(sender) +{ +} + +DCameraPhotoOutputEvent::DCameraPhotoOutputEvent(EventSender& sender, const std::shared_ptr& param) + : Event(sender), param_(param) +{ +} + +std::shared_ptr DCameraPhotoOutputEvent::GetParam() +{ + return param_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_post_authorization_event.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_post_authorization_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97bd0a6fb84b9c637408424961dd4308cb8a768d --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_post_authorization_event.cpp @@ -0,0 +1,34 @@ +/* + * 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 "dcamera_post_authorization_event.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraPostAuthorizationEvent::DCameraPostAuthorizationEvent(EventSender& sender) : Event(sender) +{ +} + +DCameraPostAuthorizationEvent::DCameraPostAuthorizationEvent(EventSender& sender, + std::vector>& param) : Event(sender), param_(param) +{ +} + +std::vector> DCameraPostAuthorizationEvent::GetParam() +{ + return param_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_video_output_event.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_video_output_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6de51a9aa38a1742c97c98c07d8bc35ab2bb6148 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/eventbus/dcamera_video_output_event.cpp @@ -0,0 +1,34 @@ +/* + * 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 "dcamera_video_output_event.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraVideoOutputEvent::DCameraVideoOutputEvent(EventSender& sender) : Event(sender) +{ +} + +DCameraVideoOutputEvent::DCameraVideoOutputEvent(EventSender& sender, const std::shared_ptr& param) + : Event(sender), param_(param) +{ +} + +std::shared_ptr DCameraVideoOutputEvent::GetParam() +{ + return param_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_controller_channel_listener.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_controller_channel_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4203ca5321148eb86d0bd66534d15b3619fc58be --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_controller_channel_listener.cpp @@ -0,0 +1,57 @@ +/* + * 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 "dcamera_sink_controller_channel_listener.h" + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkControllerChannelListener::DCameraSinkControllerChannelListener( + std::shared_ptr& controller) : controller_(controller) +{ +} + +void DCameraSinkControllerChannelListener::OnSessionState(int32_t state) +{ + std::shared_ptr controller = controller_.lock(); + if (controller == nullptr) { + DHLOGE("DCameraSinkControllerChannelListener::OnSessionState controller is null"); + return; + } + controller->OnSessionState(state); +} + +void DCameraSinkControllerChannelListener::OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) +{ + std::shared_ptr controller = controller_.lock(); + if (controller == nullptr) { + DHLOGE("DCameraSinkControllerChannelListener::OnSessionError controller is null"); + return; + } + controller->OnSessionError(eventType, eventReason, detail); +} + +void DCameraSinkControllerChannelListener::OnDataReceived(std::vector>& buffers) +{ + std::shared_ptr controller = controller_.lock(); + if (controller == nullptr) { + DHLOGE("DCameraSinkControllerChannelListener::OnReceivedData controller is null"); + return; + } + controller->OnDataReceived(buffers); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_data_process_listener.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_data_process_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1944688cc1fd33650a7fa94e1d92260a2c340e50 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_data_process_listener.cpp @@ -0,0 +1,47 @@ +/* + * 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 "dcamera_sink_data_process_listener.h" + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkDataProcessListener::DCameraSinkDataProcessListener( + std::shared_ptr& dataProcess) : dataProcess_(dataProcess) +{ +} + +void DCameraSinkDataProcessListener::OnProcessedVideoBuffer(const std::shared_ptr& videoResult) +{ + std::shared_ptr dataProcess = dataProcess_.lock(); + if (dataProcess == nullptr) { + DHLOGE("DCameraSinkDataProcessListener::OnProcessedVideoBuffer dataProcess is null"); + return; + } + dataProcess->OnProcessedVideoBuffer(videoResult); +} + +void DCameraSinkDataProcessListener::OnError(DataProcessErrorType errorType) +{ + std::shared_ptr dataProcess = dataProcess_.lock(); + if (dataProcess == nullptr) { + DHLOGE("DCameraSinkDataProcessListener::OnError dataProcess is null"); + return; + } + dataProcess->OnError(errorType); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_output_channel_listener.cpp b/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_output_channel_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2649c20b078a72e813b0ba29b358f77f2de95b9 --- /dev/null +++ b/services/cameraservice/sinkservice/src/distributedcameramgr/listener/dcamera_sink_output_channel_listener.cpp @@ -0,0 +1,57 @@ +/* + * 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 "dcamera_sink_output_channel_listener.h" + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSinkOutputChannelListener::DCameraSinkOutputChannelListener( + DCStreamType type, std::shared_ptr& output) : streamType_(type), output_(output) +{ +} + +void DCameraSinkOutputChannelListener::OnSessionState(int32_t state) +{ + std::shared_ptr output = output_.lock(); + if (output == nullptr) { + DHLOGE("DCameraSinkOutputChannelListener::OnSessionState output is null"); + return; + } + output->OnSessionState(streamType_, state); +} + +void DCameraSinkOutputChannelListener::OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) +{ + std::shared_ptr output = output_.lock(); + if (output == nullptr) { + DHLOGE("DCameraSinkOutputChannelListener::OnSessionError output is null"); + return; + } + output->OnSessionError(streamType_, eventType, eventReason, detail); +} + +void DCameraSinkOutputChannelListener::OnDataReceived(std::vector>& buffers) +{ + std::shared_ptr output = output_.lock(); + if (output == nullptr) { + DHLOGE("DCameraSinkOutputChannelListener::OnReceivedData output is null"); + return; + } + output->OnDataReceived(streamType_, buffers); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/BUILD.gn b/services/cameraservice/sinkservice/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5f7010901f226d0b1f134584505a4b767572f7da --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/BUILD.gn @@ -0,0 +1,20 @@ +# 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. + +group("sink_service_test") { + testonly = true + deps = [ + "common/distributedcamera:dcamera_sink_test", + "common/distributedcameramgr:dcamera_sink_mgr_test", + ] +} \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcamera/BUILD.gn b/services/cameraservice/sinkservice/test/unittest/common/distributedcamera/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..07221ccd8f76db98b99384931a6f66ae6ce5f9b0 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcamera/BUILD.gn @@ -0,0 +1,61 @@ +# 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. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") +module_out_path = "distributedcamera/dcamera_sink_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${services_path}/cameraservice/sinkservice/include/distributedcamera", + "${services_path}/cameraservice/sinkservice/include/distributedcameramgr", + "${services_path}/cameraservice/sinkservice/include/distributedcameramgr/interface", + "${services_path}/cameraservice/base/include", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${distributedcamera_hdf_path}/interfaces/include", + "${innerkits_path}/native_cpp/camera_sink/include", + "//drivers/peripheral/base", + ] +} + +ohos_unittest("DistributedCameraSinkServiceTest") { + module_out_path = module_out_path + + sources = [ + "distributed_camera_sink_service_test.cpp" + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/cameraservice/sinkservice:distributed_camera_sink", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + defines = [ + "HI_LOG_ENABLE", + ] + external_deps = [ + "ipc:ipc_core", + "safwk:system_ability_fwk", + "eventhandler:libeventhandler", + ] +} + +group("dcamera_sink_test") { + testonly = true + deps = [ ":DistributedCameraSinkServiceTest" ] +} \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcamera/distributed_camera_sink_service_test.cpp b/services/cameraservice/sinkservice/test/unittest/common/distributedcamera/distributed_camera_sink_service_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0146dcceec1c9fe49c4a5e6be9087f88350704c9 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcamera/distributed_camera_sink_service_test.cpp @@ -0,0 +1,204 @@ +/* + * 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 +#include +#define private public +#include "distributed_camera_sink_service.h" +#undef private + +#include "distributed_camera_errno.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DistributedCameraSinkServiceTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr service_; +}; +std::string g_testParams = ""; +std::string g_testCameraInfo = ""; +const int32_t TEST_SA_ID = 4804; +const bool TEST_RUN_ON_CREATE = true; + +std::string g_testChannelInfoContinue = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "CHANNEL_NEG", + "Value": {"SourceDevId": "TestDevId", + "Detail": [{"DataSessionFlag": "dataContinue", "StreamType": 0}]} +})"; + +std::string g_testOpenInfoService = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "OPEN_CHANNEL", + "Value": {"SourceDevId": "TestDevId"} +})"; + +void DistributedCameraSinkServiceTest::SetUpTestCase(void) +{ +} + +void DistributedCameraSinkServiceTest::TearDownTestCase(void) +{ +} + +void DistributedCameraSinkServiceTest::SetUp(void) +{ + service_ = std::make_shared(TEST_SA_ID, TEST_RUN_ON_CREATE); +} + +void DistributedCameraSinkServiceTest::TearDown(void) +{ + service_ = nullptr; +} + +/** + * @tc.name: dcamera_sink_service_test_001 + * @tc.desc: Verify the InitSink and ReleaseSink function. + * @tc.type: FUNC + * @tc.require: AR000GK6MV + */ +HWTEST_F(DistributedCameraSinkServiceTest, dcamera_sink_service_test_001, TestSize.Level1) +{ + int32_t ret = service_->InitSink(g_testParams); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(g_testParams, service_->sinkVer_); + EXPECT_NE(0, (int32_t)service_->camerasMap_.size()); + + ret = service_->ReleaseSink(); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(0, (int32_t)service_->camerasMap_.size()); +} + +/** + * @tc.name: dcamera_sink_service_test_002 + * @tc.desc: Verify the SubscribeLocalHardware function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DistributedCameraSinkServiceTest, dcamera_sink_service_test_002, TestSize.Level1) +{ + int32_t ret = service_->InitSink(g_testParams); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->SubscribeLocalHardware(service_->camerasMap_.begin()->first, g_testParams); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->ReleaseSink(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_service_test_003 + * @tc.desc: Verify the UnSubscribeLocalHardware function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DistributedCameraSinkServiceTest, dcamera_sink_service_test_003, TestSize.Level1) +{ + int32_t ret = service_->InitSink(g_testParams); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->UnsubscribeLocalHardware(service_->camerasMap_.begin()->first); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->ReleaseSink(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_service_test_004 + * @tc.desc: Verify the StopCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DistributedCameraSinkServiceTest, dcamera_sink_service_test_004, TestSize.Level1) +{ + int32_t ret = service_->InitSink(g_testParams); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->StopCapture(service_->camerasMap_.begin()->first); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->ReleaseSink(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_service_test_005 + * @tc.desc: Verify the ChannelNeg function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DistributedCameraSinkServiceTest, dcamera_sink_service_test_005, TestSize.Level1) +{ + int32_t ret = service_->InitSink(g_testParams); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->ChannelNeg(service_->camerasMap_.begin()->first, g_testChannelInfoContinue); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->ReleaseSink(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_service_test_006 + * @tc.desc: Verify the GetCameraInfo function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DistributedCameraSinkServiceTest, dcamera_sink_service_test_006, TestSize.Level1) +{ + int32_t ret = service_->InitSink(g_testParams); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->GetCameraInfo(service_->camerasMap_.begin()->first, g_testCameraInfo); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->ReleaseSink(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_service_test_007 + * @tc.desc: Verify the OpenChannel and CloseChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DistributedCameraSinkServiceTest, dcamera_sink_service_test_007, TestSize.Level1) +{ + int32_t ret = service_->InitSink(g_testParams); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->OpenChannel(service_->camerasMap_.begin()->first, g_testOpenInfoService); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->CloseChannel(service_->camerasMap_.begin()->first); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = service_->ReleaseSink(); + EXPECT_EQ(DCAMERA_OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/BUILD.gn b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5308312dd889096d5fb080e197bba54aa4a3befc --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/BUILD.gn @@ -0,0 +1,86 @@ +# 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. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") +module_out_path = "distributedcamera/dcamera_sink_mgr_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${services_path}/cameraservice/sinkservice/include/distributedcameramgr", + "${services_path}/cameraservice/sinkservice/include/distributedcameramgr/callback", + "${services_path}/cameraservice/sinkservice/include/distributedcameramgr/eventbus", + "${services_path}/cameraservice/sinkservice/include/distributedcameramgr/interface", + "${services_path}/cameraservice/sinkservice/include/distributedcameramgr/listener", + "${services_path}/cameraservice/cameraoperator/client/include", + "${services_path}/cameraservice/base/include", + "${services_path}/channel/include", + "${services_path}/data_process/include/pipeline", + "${services_path}/data_process/include/interfaces", + "${services_path}/data_process/include/utils", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${distributedcamera_hdf_path}/interfaces/include", + "${innerkits_path}/native_cpp/camera_source/include", + "${innerkits_path}/native_cpp/camera_source/include/callback", + + "${fwk_utils_path}/include/eventbus", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + "${fwk_common_path}/utils/include", + "${fwk_common_path}/log/include", + + "//drivers/peripheral/base", + ] +} + +ohos_unittest("DCameraSinkMgrTest") { + module_out_path = module_out_path + + sources = [ + "dcamera_sink_dev_test.cpp", + "dcamera_sink_access_control_test.cpp", + "dcamera_sink_controller_test.cpp", + "dcamera_sink_output_test.cpp", + "dcamera_sink_data_process_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/cameraservice/sinkservice:distributed_camera_sink", + "${services_path}/channel:distributed_camera_channel", + "${common_path}:distributed_camera_utils", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + + "${fwk_utils_path}:distributedhardwareutils", + ] + + external_deps = [ + "ipc:ipc_core", + "eventhandler:libeventhandler", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DCameraSinkMgrTest\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dcamera_sink_mgr_test") { + testonly = true + deps = [ ":DCameraSinkMgrTest" ] +} \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_access_control_test.cpp b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_access_control_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0458e23052510a1cf5ed7932a8a8cc8a86ae9f4f --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_access_control_test.cpp @@ -0,0 +1,108 @@ +/* + * 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 +#include +#define private public +#include "dcamera_sink_access_control.h" +#undef private + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkAccessControlTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr accessControl_; +}; +const std::string TEST_SRC_TYPE = "camera"; +const std::string TEST_DEVICE_NAME = ""; +const std::string TEST_ACCESS_TYPE = ""; + +void DCameraSinkAccessControlTest::SetUpTestCase(void) +{ +} + +void DCameraSinkAccessControlTest::TearDownTestCase(void) +{ +} + +void DCameraSinkAccessControlTest::SetUp(void) +{ + accessControl_ = std::make_shared(); +} + +void DCameraSinkAccessControlTest::TearDown(void) +{ + accessControl_ = nullptr; +} + +/** + * @tc.name: dcamera_sink_access_control_test_001 + * @tc.desc: Verify the IsSensitiveSrcAccess function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkAccessControlTest, dcamera_sink_access_control_test_001, TestSize.Level1) +{ + bool ret = accessControl_->IsSensitiveSrcAccess(TEST_SRC_TYPE); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: dcamera_sink_access_control_test_002 + * @tc.desc: Verify the NotifySensitiveSrc function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkAccessControlTest, dcamera_sink_access_control_test_002, TestSize.Level1) +{ + bool ret = accessControl_->NotifySensitiveSrc(TEST_SRC_TYPE); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: dcamera_sink_access_control_test_003 + * @tc.desc: Verify the GetAccessControlType function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkAccessControlTest, dcamera_sink_access_control_test_003, TestSize.Level1) +{ + int32_t ret = accessControl_->GetAccessControlType(TEST_ACCESS_TYPE); + EXPECT_EQ(DCAMERA_SAME_ACCOUNT, ret); +} + +/** + * @tc.name: dcamera_sink_access_control_test_004 + * @tc.desc: Verify the TriggerFrame function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkAccessControlTest, dcamera_sink_access_control_test_004, TestSize.Level1) +{ + int32_t ret = accessControl_->TriggerFrame(TEST_DEVICE_NAME); + EXPECT_EQ(DCAMERA_OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_controller_test.cpp b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_controller_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..058fca2c8576a1ebf9553860e37c57cb82f354ec --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_controller_test.cpp @@ -0,0 +1,356 @@ +/* + * 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 +#include +#define private public +#include "dcamera_sink_controller.h" +#undef private + +#include "distributed_hardware_log.h" + +#include "mock_camera_channel.h" +#include "mock_camera_operator.h" +#include "mock_dcamera_sink_output.h" + +#include "dcamera_metadata_setting_cmd.h" +#include "dcamera_sink_access_control.h" +#include "dcamera_sink_dev.h" +#include "dcamera_utils_tools.h" +#include "distributed_camera_errno.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkControllerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr controller_; + std::shared_ptr accessControl_; +}; +std::string g_testDeviceIdController; +const std::string TEST_DH_ID = "Camera_device@3.5/legacy/1"; +const std::string SESSION_FLAG_CONTINUE = "dataContinue"; +const std::string SESSION_FLAG_SNAPSHOT = "dataSnapshot"; +const std::string TEST_DEVICE_ID_EMPTY = ""; + +const std::string TEST_CAPTURE_INFO_CMD_JSON = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "CAPTURE", + "Value": [ + {"Width": 1920, "Height": 1080, "Format": 1, + "DataSpace": 1, "IsCapture":true, "EncodeType": 1, "StreamType": 1, + "CaptureSettings": [{"SettingType": 1, "SettingValue": "TestSetting"}]} + ] +})"; + +const std::string TEST_CHANNEL_INFO_CMD_CONTINUE_JSON = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "CHANNEL_NEG", + "Value": {"SourceDevId": "TestDevId", + "Detail": [{"DataSessionFlag": "dataContinue", "StreamType": 0}]} +})"; + +const std::string TEST_EVENT_CMD_JSON = R"({ + "Type": "MESSAGE", + "dhId": "camrea_0", + "Command": "STATE_NOTIFY", + "Value": {"EventType": 1, "EventResult": 1, "EventContent": "TestContent"} +})"; + +const std::string TEST_INFO_CMD_JSON = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "GET_INFO", + "Value": {"State": 1} +})"; + +const std::string TEST_METADATA_SETTING_CMD_JSON = R"({ + "Type": "MESSAGE", + "dhId": "camrea_0", + "Command": "UPDATE_METADATA", + "Value": [{"SettingType": 1, "SettingValue": "TestSetting"}] +})"; + +const std::string TEST_OPEN_INFO_CMD_JSON = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "OPEN_CHANNEL", + "Value": {"SourceDevId": "TestDevId" } +})"; + +std::vector g_testCamIndex; + +void DCameraSinkControllerTest::SetUpTestCase(void) +{ + GetLocalDeviceNetworkId(g_testDeviceIdController); + g_testCamIndex.push_back(DCameraIndex(g_testDeviceIdController, TEST_DH_ID)); +} + +void DCameraSinkControllerTest::TearDownTestCase(void) +{ +} + +void DCameraSinkControllerTest::SetUp(void) +{ + accessControl_ = std::make_shared(); + controller_ = std::make_shared(accessControl_); + + controller_->channel_ = std::make_shared(); + controller_->operator_ = std::make_shared(); + controller_->output_ = std::make_shared(TEST_DH_ID, controller_->operator_); + controller_->srcDevId_ = g_testDeviceIdController; + controller_->dhId_ = TEST_DH_ID; +} + +void DCameraSinkControllerTest::TearDown(void) +{ + accessControl_ = nullptr; + controller_ = nullptr; +} + +/** + * @tc.name: dcamera_sink_controller_test_001 + * @tc.desc: Verify the Init and UnInit function. + * @tc.type: FUNC + * @tc.require: AR000GK6MV + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_001, TestSize.Level1) +{ + int32_t ret = controller_->Init(g_testCamIndex); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(true, controller_->isInit_); + + ret = controller_->UnInit(); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(false, controller_->isInit_); +} + +/** + * @tc.name: dcamera_sink_controller_test_002 + * @tc.desc: Verify the GetCameraInfo function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_002, TestSize.Level1) +{ + DCameraInfoCmd cmd; + cmd.value_ = std::make_shared(); + int32_t ret = controller_->GetCameraInfo(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(DCAMERA_CHANNEL_STATE_DISCONNECTED, cmd.value_->state_); +} + +/** + * @tc.name: dcamera_sink_controller_test_003 + * @tc.desc: Verify the ChannelNeg function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_003, TestSize.Level1) +{ + DCameraChannelInfoCmd cmd; + cmd.Unmarshal(TEST_CHANNEL_INFO_CMD_CONTINUE_JSON); + int32_t ret = controller_->ChannelNeg(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_controller_test_004 + * @tc.desc: Verify the StartCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_004, TestSize.Level1) +{ + DCameraCaptureInfoCmd cmd; + cmd.Unmarshal(TEST_CAPTURE_INFO_CMD_JSON); + int32_t ret = controller_->StartCapture(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_controller_test_005 + * @tc.desc: Verify the UpdateSettings function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_005, TestSize.Level1) +{ + DCameraCaptureInfoCmd cmd; + cmd.Unmarshal(TEST_CAPTURE_INFO_CMD_JSON); + int32_t ret = controller_->StartCapture(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); + + DCameraMetadataSettingCmd cmdMetadata; + cmdMetadata.Unmarshal(TEST_METADATA_SETTING_CMD_JSON); + ret = controller_->UpdateSettings(cmdMetadata.value_); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_controller_test_006 + * @tc.desc: Verify the StopCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_006, TestSize.Level1) +{ + DCameraCaptureInfoCmd cmd; + cmd.Unmarshal(TEST_CAPTURE_INFO_CMD_JSON); + int32_t ret = controller_->StartCapture(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = controller_->StopCapture(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_controller_test_007 + * @tc.desc: Verify the DCameraNotify function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_007, TestSize.Level1) +{ + controller_->srcDevId_ = TEST_DEVICE_ID_EMPTY; + + DCameraEventCmd cmd; + cmd.Unmarshal(TEST_EVENT_CMD_JSON); + int32_t ret = controller_->DCameraNotify(cmd.value_); + EXPECT_EQ(DCAMERA_BAD_VALUE, ret); +} + +/** + * @tc.name: dcamera_sink_controller_test_008 + * @tc.desc: Verify the DCameraNotify function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_008, TestSize.Level1) +{ + DCameraEventCmd cmd; + cmd.Unmarshal(TEST_EVENT_CMD_JSON); + int32_t ret = controller_->DCameraNotify(cmd.value_); + EXPECT_NE(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_controller_test_009 + * @tc.desc: Verify the OnSessionState and GetCameraInfo function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_009, TestSize.Level1) +{ + controller_->OnSessionState(DCAMERA_CHANNEL_STATE_CONNECTING); + + DCameraInfoCmd cmd; + cmd.value_ = std::make_shared(); + int32_t ret = controller_->GetCameraInfo(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(DCAMERA_CHANNEL_STATE_CONNECTING, cmd.value_->state_); +} + +/** + * @tc.name: dcamera_sink_controller_test_010 + * @tc.desc: Verify the OnSessionState function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_010, TestSize.Level1) +{ + controller_->OnSessionState(DCAMERA_CHANNEL_STATE_CONNECTED); + + DCameraInfoCmd cmd; + cmd.value_ = std::make_shared(); + int32_t ret = controller_->GetCameraInfo(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(DCAMERA_CHANNEL_STATE_CONNECTED, cmd.value_->state_); +} + +/** + * @tc.name: dcamera_sink_controller_test_011 + * @tc.desc: Verify the OnSessionState function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_011, TestSize.Level1) +{ + controller_->OnSessionState(DCAMERA_CHANNEL_STATE_DISCONNECTED); + + DCameraInfoCmd cmd; + cmd.value_ = std::make_shared(); + int32_t ret = controller_->GetCameraInfo(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(DCAMERA_CHANNEL_STATE_DISCONNECTED, cmd.value_->state_); +} + +/** + * @tc.name: dcamera_sink_controller_test_012 + * @tc.desc: Verify the OpenChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_012, TestSize.Level1) +{ + DCameraOpenInfoCmd cmd; + cmd.Unmarshal(TEST_OPEN_INFO_CMD_JSON); + int32_t ret = controller_->OpenChannel(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_controller_test_013 + * @tc.desc: Verify the OpenChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_013, TestSize.Level1) +{ + controller_->OnSessionState(DCAMERA_CHANNEL_STATE_CONNECTED); + + DCameraInfoCmd cmd; + cmd.value_ = std::make_shared(); + int32_t ret = controller_->GetCameraInfo(cmd.value_); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(DCAMERA_CHANNEL_STATE_CONNECTED, cmd.value_->state_); + + DCameraOpenInfoCmd cmdOpenInfo; + cmdOpenInfo.Unmarshal(TEST_OPEN_INFO_CMD_JSON); + ret = controller_->OpenChannel(cmdOpenInfo.value_); + EXPECT_EQ(DCAMERA_WRONG_STATE, ret); +} + +/** + * @tc.name: dcamera_sink_controller_test_014 + * @tc.desc: Verify the CloseChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkControllerTest, dcamera_sink_controller_test_014, TestSize.Level1) +{ + int32_t ret = controller_->CloseChannel(); + EXPECT_EQ(DCAMERA_OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_data_process_test.cpp b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_data_process_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4509a2a5a71df64d0820a592f21f98c355e52428 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_data_process_test.cpp @@ -0,0 +1,198 @@ +/* + * 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 +#include +#define private public +#include "dcamera_sink_data_process.h" +#undef private + +#include +#include + +#include "distributed_camera_errno.h" +#include "mock_camera_channel.h" +#include "mock_data_process_pipeline.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkDataProcessTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr dataProcess_; + std::shared_ptr channel_; +}; +const std::string TEST_DH_ID = "Camera_device@3.5/legacy/1"; +const std::string TEST_STRING = "test_string"; +const int32_t TEST_WIDTH = 1080; +const int32_t TEST_HEIGHT = 1920; + +std::shared_ptr g_testCaptureInfoContinuousNotEncode; +std::shared_ptr g_testCaptureInfoContinuousNeedEncode; +std::shared_ptr g_testCaptureInfoSnapshot; + +std::shared_ptr g_testDataBuffer; + +void DCameraSinkDataProcessTest::SetUpTestCase(void) +{ + std::shared_ptr cameraSetting = std::make_shared(); + cameraSetting->type_ = UPDATE_METADATA; + cameraSetting->value_ = ""; + + g_testCaptureInfoContinuousNotEncode = std::make_shared(); + g_testCaptureInfoContinuousNotEncode->width_ = TEST_WIDTH; + g_testCaptureInfoContinuousNotEncode->height_ = TEST_HEIGHT; + g_testCaptureInfoContinuousNotEncode->format_ = ENCODE_TYPE_H264; + g_testCaptureInfoContinuousNotEncode->dataspace_ = 0; + g_testCaptureInfoContinuousNotEncode->encodeType_ = ENCODE_TYPE_H264; + g_testCaptureInfoContinuousNotEncode->streamType_ = CONTINUOUS_FRAME; + g_testCaptureInfoContinuousNotEncode->captureSettings_.push_back(cameraSetting); + + g_testCaptureInfoContinuousNeedEncode = std::make_shared(); + g_testCaptureInfoContinuousNeedEncode->width_ = TEST_WIDTH; + g_testCaptureInfoContinuousNeedEncode->height_ = TEST_HEIGHT; + g_testCaptureInfoContinuousNeedEncode->format_ = ENCODE_TYPE_H264; + g_testCaptureInfoContinuousNeedEncode->dataspace_ = 0; + g_testCaptureInfoContinuousNeedEncode->encodeType_ = ENCODE_TYPE_H265; + g_testCaptureInfoContinuousNeedEncode->streamType_ = CONTINUOUS_FRAME; + g_testCaptureInfoContinuousNeedEncode->captureSettings_.push_back(cameraSetting); + + g_testCaptureInfoSnapshot = std::make_shared(); + g_testCaptureInfoSnapshot->width_ = TEST_WIDTH; + g_testCaptureInfoSnapshot->height_ = TEST_HEIGHT; + g_testCaptureInfoSnapshot->format_ = ENCODE_TYPE_JPEG; + g_testCaptureInfoSnapshot->dataspace_ = 0; + g_testCaptureInfoSnapshot->encodeType_ = ENCODE_TYPE_JPEG; + g_testCaptureInfoSnapshot->streamType_ = SNAPSHOT_FRAME; + g_testCaptureInfoSnapshot->captureSettings_.push_back(cameraSetting); + + g_testDataBuffer = std::make_shared(TEST_STRING.length() + 1); + memcpy_s(g_testDataBuffer->Data(), g_testDataBuffer->Capacity(), + (uint8_t *)TEST_STRING.c_str(), TEST_STRING.length()); +} + +void DCameraSinkDataProcessTest::TearDownTestCase(void) +{ +} + +void DCameraSinkDataProcessTest::SetUp(void) +{ + channel_ = std::make_shared(); + dataProcess_ = std::make_shared(TEST_DH_ID, channel_); + + dataProcess_->pipeline_ = std::make_shared(); + dataProcess_->captureInfo_ = g_testCaptureInfoContinuousNeedEncode; +} + +void DCameraSinkDataProcessTest::TearDown(void) +{ + channel_ = nullptr; + dataProcess_ = nullptr; +} + +/** + * @tc.name: dcamera_sink_data_process_test_001 + * @tc.desc: Verify the StartCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkDataProcessTest, dcamera_sink_data_process_test_001, TestSize.Level1) +{ + int32_t ret = dataProcess_->StartCapture(g_testCaptureInfoContinuousNotEncode); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_data_process_test_002 + * @tc.desc: Verify the StartCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkDataProcessTest, dcamera_sink_data_process_test_002, TestSize.Level1) +{ + int32_t ret = dataProcess_->StartCapture(g_testCaptureInfoContinuousNeedEncode); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_data_process_test_003 + * @tc.desc: Verify the StartCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkDataProcessTest, dcamera_sink_data_process_test_003, TestSize.Level1) +{ + int32_t ret = dataProcess_->StartCapture(g_testCaptureInfoSnapshot); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_data_process_test_004 + * @tc.desc: Verify the StopCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkDataProcessTest, dcamera_sink_data_process_test_004, TestSize.Level1) +{ + int32_t ret = dataProcess_->StopCapture(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_data_process_test_005 + * @tc.desc: Verify the FeedStream function. + * @tc.type: FUNC + * @tc.require: AR000GK6MV + */ +HWTEST_F(DCameraSinkDataProcessTest, dcamera_sink_data_process_test_005, TestSize.Level1) +{ + dataProcess_->captureInfo_ = g_testCaptureInfoContinuousNotEncode; + int32_t ret = dataProcess_->FeedStream(g_testDataBuffer); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_data_process_test_006 + * @tc.desc: Verify the FeedStream function. + * @tc.type: FUNC + * @tc.require: AR000GK6MV + */ +HWTEST_F(DCameraSinkDataProcessTest, dcamera_sink_data_process_test_006, TestSize.Level1) +{ + dataProcess_->captureInfo_ = g_testCaptureInfoContinuousNeedEncode; + int32_t ret = dataProcess_->FeedStream(g_testDataBuffer); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_data_process_test_007 + * @tc.desc: Verify the FeedStream function. + * @tc.type: FUNC + * @tc.require: AR000GK6MV + */ +HWTEST_F(DCameraSinkDataProcessTest, dcamera_sink_data_process_test_007, TestSize.Level1) +{ + dataProcess_->captureInfo_ = g_testCaptureInfoSnapshot; + int32_t ret = dataProcess_->FeedStream(g_testDataBuffer); + EXPECT_EQ(DCAMERA_OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_dev_test.cpp b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_dev_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d79a09b9e3d4eff10de4696af1076a998f6f994d --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_dev_test.cpp @@ -0,0 +1,215 @@ +/* + * 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 +#include + +#include "anonymous_string.h" +#include "distributed_hardware_log.h" + +#define private public +#include "dcamera_sink_access_control.h" +#include "dcamera_sink_controller.h" +#include "dcamera_sink_dev.h" +#undef private + +#include "dcamera_utils_tools.h" +#include "distributed_camera_errno.h" +#include "mock_dcamera_sink_controller.h" + + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkDevTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr dev_; +}; +const std::string TEST_CAMERA_DH_ID_0 = "Camera_device@3.5/legacy/1"; +const std::string TEST_PARAMETER = ""; +std::string g_testCameraInfo = ""; + +std::string g_testChannelInfoDevContinue = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "CHANNEL_NEG", + "Value": {"SourceDevId": "TestDevId", + "Detail": [{"DataSessionFlag": "dataContinue", "StreamType": 0}]} +})"; + +std::string g_testOpenInfoDev = R"({ + "Type": "OPERATION", + "dhId": "camrea_0", + "Command": "OPEN_CHANNEL", + "Value": {"SourceDevId": "TestDevId"} +})"; + +std::string g_testChannelInfoDevEmpty = ""; +std::string g_testOpenInfoDevEmpty = ""; + +void DCameraSinkDevTest::SetUpTestCase(void) +{ +} + +void DCameraSinkDevTest::TearDownTestCase(void) +{ +} + +void DCameraSinkDevTest::SetUp(void) +{ + dev_ = std::make_shared(TEST_CAMERA_DH_ID_0); + + dev_->accessControl_ = std::make_shared(); + dev_->controller_ = std::make_shared(dev_->accessControl_); +} + +void DCameraSinkDevTest::TearDown(void) +{ + dev_ = nullptr; +} + +/** + * @tc.name: dcamera_sink_dev_test_001 + * @tc.desc: Verify the Init and UnInit function. + * @tc.type: FUNC + * @tc.require: AR000GK6MV + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_001, TestSize.Level1) +{ + int32_t ret = dev_->Init(); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(true, dev_->isInit_); + + ret = dev_->UnInit(); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(false, dev_->isInit_); +} + +/** + * @tc.name: dcamera_sink_dev_test_002 + * @tc.desc: Verify the SubscribeLocalHardware function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_002, TestSize.Level1) +{ + int32_t ret = dev_->SubscribeLocalHardware(TEST_PARAMETER); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_dev_test_003 + * @tc.desc: Verify the UnsubscribeLocalHardware function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_003, TestSize.Level1) +{ + int32_t ret = dev_->UnsubscribeLocalHardware(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_dev_test_004 + * @tc.desc: Verify the GetCameraInfo function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_004, TestSize.Level1) +{ + int32_t ret = dev_->GetCameraInfo(g_testCameraInfo); + EXPECT_EQ(DCAMERA_OK, ret); + DHLOGI("DCameraSinkDevTest::GetCameraInfo cameraInfo is %s", GetAnonyString(g_testCameraInfo).c_str()); +} + +/** + * @tc.name: dcamera_sink_dev_test_005 + * @tc.desc: Verify the ChannelNeg function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_005, TestSize.Level1) +{ + int32_t ret = dev_->ChannelNeg(g_testChannelInfoDevEmpty); + EXPECT_EQ(DCAMERA_BAD_VALUE, ret); +} + +/** + * @tc.name: dcamera_sink_dev_test_006 + * @tc.desc: Verify the ChannelNeg function. + * @tc.type: FUNC + * @tc.require: AR000GK6MT + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_006, TestSize.Level1) +{ + int32_t ret = dev_->ChannelNeg(g_testChannelInfoDevContinue); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_dev_test_007 + * @tc.desc: Verify the StopCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_007, TestSize.Level1) +{ + int32_t ret = dev_->StopCapture(); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_dev_test_008 + * @tc.desc: Verify the OpenChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_008, TestSize.Level1) +{ + int32_t ret = dev_->OpenChannel(g_testOpenInfoDevEmpty); + EXPECT_EQ(DCAMERA_BAD_VALUE, ret); +} + +/** + * @tc.name: dcamera_sink_dev_test_009 + * @tc.desc: Verify the OpenChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_009, TestSize.Level1) +{ + int32_t ret = dev_->OpenChannel(g_testOpenInfoDev); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_dev_test_010 + * @tc.desc: Verify the CloseChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkDevTest, dcamera_sink_dev_test_010, TestSize.Level1) +{ + int32_t ret = dev_->CloseChannel(); + EXPECT_EQ(DCAMERA_OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_output_test.cpp b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_output_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d4e64ec62fec1867d3f228f1fadee75e9820bbf8 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/dcamera_sink_output_test.cpp @@ -0,0 +1,240 @@ +/* + * 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 +#include +#define private public +#include "dcamera_sink_output.h" +#undef private + +#include "mock_camera_channel.h" +#include "mock_camera_operator.h" +#include "mock_dcamera_sink_data_process.h" + +#include "dcamera_sink_access_control.h" +#include "dcamera_sink_controller.h" +#include "dcamera_sink_data_process.h" +#include "dcamera_sink_dev.h" +#include "dcamera_utils_tools.h" +#include "distributed_camera_errno.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraSinkOutputTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr output_; + std::shared_ptr operator_; + std::shared_ptr channel_; + std::shared_ptr dataProcess_; +}; +const std::string TEST_DH_ID = "Camera_device@3.5/legacy/1"; +const std::string SESSION_FLAG_CONTINUE = "dataContinue"; +const std::string SESSION_FLAG_SNAPSHOT = "dataSnapshot"; +const int32_t TEST_WIDTH = 1080; +const int32_t TEST_HEIGHT = 1920; + +std::string g_testDeviceIdOutput; +DCameraChannelDetail g_testDetailOutput; + +std::shared_ptr g_testCaptureInfoOutputContinuousNotEncode; +std::shared_ptr g_testCaptureInfoOutputContinuousNeedEncode; +std::shared_ptr g_testCaptureInfoOutputSnapshot; + +std::shared_ptr g_testChannelInfo; + +std::vector> g_testCaptureInfosOutput; + +void DCameraSinkOutputTest::SetUpTestCase(void) +{ + GetLocalDeviceNetworkId(g_testDeviceIdOutput); + + std::shared_ptr cameraSetting = std::make_shared(); + cameraSetting->type_ = UPDATE_METADATA; + cameraSetting->value_ = ""; + + g_testCaptureInfoOutputContinuousNotEncode = std::make_shared(); + g_testCaptureInfoOutputContinuousNotEncode->width_ = TEST_WIDTH; + g_testCaptureInfoOutputContinuousNotEncode->height_ = TEST_HEIGHT; + g_testCaptureInfoOutputContinuousNotEncode->format_ = ENCODE_TYPE_H264; + g_testCaptureInfoOutputContinuousNotEncode->dataspace_ = 0; + g_testCaptureInfoOutputContinuousNotEncode->encodeType_ = ENCODE_TYPE_H264; + g_testCaptureInfoOutputContinuousNotEncode->streamType_ = CONTINUOUS_FRAME; + g_testCaptureInfoOutputContinuousNotEncode->captureSettings_.push_back(cameraSetting); + + g_testCaptureInfoOutputContinuousNeedEncode = std::make_shared(); + g_testCaptureInfoOutputContinuousNeedEncode->width_ = TEST_WIDTH; + g_testCaptureInfoOutputContinuousNeedEncode->height_ = TEST_HEIGHT; + g_testCaptureInfoOutputContinuousNeedEncode->format_ = ENCODE_TYPE_H264; + g_testCaptureInfoOutputContinuousNeedEncode->dataspace_ = 0; + g_testCaptureInfoOutputContinuousNeedEncode->encodeType_ = ENCODE_TYPE_H265; + g_testCaptureInfoOutputContinuousNeedEncode->streamType_ = CONTINUOUS_FRAME; + g_testCaptureInfoOutputContinuousNeedEncode->captureSettings_.push_back(cameraSetting); + + g_testCaptureInfoOutputSnapshot = std::make_shared(); + g_testCaptureInfoOutputSnapshot->width_ = TEST_WIDTH; + g_testCaptureInfoOutputSnapshot->height_ = TEST_HEIGHT; + g_testCaptureInfoOutputSnapshot->format_ = ENCODE_TYPE_JPEG; + g_testCaptureInfoOutputSnapshot->dataspace_ = 0; + g_testCaptureInfoOutputSnapshot->encodeType_ = ENCODE_TYPE_JPEG; + g_testCaptureInfoOutputSnapshot->streamType_ = SNAPSHOT_FRAME; + g_testCaptureInfoOutputSnapshot->captureSettings_.push_back(cameraSetting); + + g_testDetailOutput.dataSessionFlag_ = SESSION_FLAG_CONTINUE; + g_testDetailOutput.streamType_ = CONTINUOUS_FRAME; + + g_testChannelInfo = std::make_shared(); + g_testChannelInfo->sourceDevId_ = g_testDeviceIdOutput; + std::vector detail0; + detail0.push_back(g_testDetailOutput); + g_testChannelInfo->detail_ = detail0; +} + +void DCameraSinkOutputTest::TearDownTestCase(void) +{ +} + +void DCameraSinkOutputTest::SetUp(void) +{ + operator_ = std::make_shared(); + output_ = std::make_shared(TEST_DH_ID, operator_); + channel_ = std::make_shared(); + dataProcess_ = std::make_shared(channel_); + output_->channels_.emplace(SNAPSHOT_FRAME, channel_); + output_->channels_.emplace(CONTINUOUS_FRAME, channel_); + output_->dataProcesses_.emplace(SNAPSHOT_FRAME, dataProcess_); + output_->dataProcesses_.emplace(CONTINUOUS_FRAME, dataProcess_); +} + +void DCameraSinkOutputTest::TearDown(void) +{ + output_->channels_.clear(); + output_->dataProcesses_.clear(); + + operator_ = nullptr; + output_ = nullptr; +} + +/** + * @tc.name: dcamera_sink_output_test_001 + * @tc.desc: Verify the UnInit function. + * @tc.type: FUNC + * @tc.require: AR000GK6MV + */ +HWTEST_F(DCameraSinkOutputTest, dcamera_sink_output_test_001, TestSize.Level1) +{ + int32_t ret = output_->Init(); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(true, output_->isInit_); + + ret = output_->UnInit(); + EXPECT_EQ(DCAMERA_OK, ret); + EXPECT_EQ(false, output_->isInit_); +} + +/** + * @tc.name: dcamera_sink_output_test_002 + * @tc.desc: Verify the StartCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkOutputTest, dcamera_sink_output_test_002, TestSize.Level1) +{ + g_testCaptureInfosOutput.push_back(g_testCaptureInfoOutputContinuousNotEncode); + int32_t ret = output_->StartCapture(g_testCaptureInfosOutput); + EXPECT_EQ(DCAMERA_OK, ret); + + g_testCaptureInfosOutput.clear(); +} + +/** + * @tc.name: dcamera_sink_output_test_003 + * @tc.desc: Verify the StartCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkOutputTest, dcamera_sink_output_test_003, TestSize.Level1) +{ + g_testCaptureInfosOutput.push_back(g_testCaptureInfoOutputContinuousNeedEncode); + int32_t ret = output_->StartCapture(g_testCaptureInfosOutput); + EXPECT_EQ(DCAMERA_OK, ret); + + g_testCaptureInfosOutput.clear(); +} + +/** + * @tc.name: dcamera_sink_output_test_004 + * @tc.desc: Verify the StartCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6MU + */ +HWTEST_F(DCameraSinkOutputTest, dcamera_sink_output_test_004, TestSize.Level1) +{ + g_testCaptureInfosOutput.push_back(g_testCaptureInfoOutputSnapshot); + int32_t ret = output_->StartCapture(g_testCaptureInfosOutput); + EXPECT_EQ(DCAMERA_OK, ret); + + g_testCaptureInfosOutput.clear(); +} + +/** + * @tc.name: dcamera_sink_output_test_005 + * @tc.desc: Verify the StopCapture function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkOutputTest, dcamera_sink_output_test_005, TestSize.Level1) +{ + g_testCaptureInfosOutput.push_back(g_testCaptureInfoOutputContinuousNotEncode); + int32_t ret = output_->StartCapture(g_testCaptureInfosOutput); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = output_->StopCapture(); + EXPECT_EQ(DCAMERA_OK, ret); + + g_testCaptureInfosOutput.clear(); +} + +/** + * @tc.name: dcamera_sink_output_test_006 + * @tc.desc: Verify the OpenChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkOutputTest, dcamera_sink_output_test_006, TestSize.Level1) +{ + int32_t ret = output_->OpenChannel(g_testChannelInfo); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_sink_output_test_007 + * @tc.desc: Verify the CloseChannel function. + * @tc.type: FUNC + * @tc.require: AR000GK6N1 + */ +HWTEST_F(DCameraSinkOutputTest, dcamera_sink_output_test_007, TestSize.Level1) +{ + int32_t ret = output_->CloseChannel(); + EXPECT_EQ(DCAMERA_OK, ret); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_camera_channel.h b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_camera_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..479caf7524af4f6eed51f53dd356536b38e5c68b --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_camera_channel.h @@ -0,0 +1,63 @@ +/* + * 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_MOCK_CAMERA_CHANNEL_H +#define OHOS_MOCK_CAMERA_CHANNEL_H + +#include "distributed_camera_errno.h" +#include "icamera_channel.h" + +namespace OHOS { +namespace DistributedHardware { +class MockCameraChannel : public ICameraChannel { +public: + explicit MockCameraChannel() + { + } + + ~MockCameraChannel() + { + } + + int32_t OpenSession() + { + return DCAMERA_OK; + } + + int32_t CloseSession() + { + return DCAMERA_OK; + } + + int32_t CreateSession(std::vector& camIndexs, std::string sessionFlag, + DCameraSessionMode sessionMode, std::shared_ptr& listener) + { + return DCAMERA_OK; + } + + int32_t ReleaseSession() + { + return DCAMERA_OK; + } + + int32_t SendData(std::shared_ptr& buffer) + { + return DCAMERA_OK; + } +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_camera_operator.h b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_camera_operator.h new file mode 100644 index 0000000000000000000000000000000000000000..48deca9a4a72fea8be6aff7dd602885560314118 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_camera_operator.h @@ -0,0 +1,82 @@ +/* + * 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_MOCK_CAMERA_OPERATOR_H +#define OHOS_MOCK_CAMERA_OPERATOR_H + +#include "distributed_camera_errno.h" +#include "icamera_operator.h" + +namespace OHOS { +namespace DistributedHardware { +class MockCameraOperator : public ICameraOperator { +public: + explicit MockCameraOperator() + { + } + + ~MockCameraOperator() + { + } + + int32_t Init() + { + return DCAMERA_OK; + } + + int32_t UnInit() + { + return DCAMERA_OK; + } + + int32_t UpdateSettings(std::vector>& settings) + { + return DCAMERA_OK; + } + + int32_t OpenCamera(std::vector>& captureInfos) + { + return DCAMERA_OK; + } + + int32_t CloseCamera() + { + return DCAMERA_OK; + } + + int32_t StartCapture(std::vector>& captureInfos) + { + return DCAMERA_OK; + } + + int32_t StopCapture() + { + return DCAMERA_OK; + } + + int32_t SetStateCallback(std::shared_ptr& callback) + { + return DCAMERA_OK; + } + + int32_t SetResultCallback(std::shared_ptr& callback) + { + return DCAMERA_OK; + } +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_data_process_pipeline.h b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_data_process_pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..dca14bbf6b8286be4d691247c7a322438b873775 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_data_process_pipeline.h @@ -0,0 +1,56 @@ +/* + * 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_MOCK_DATA_PROCESS_PIPELINE_H +#define OHOS_MOCK_DATA_PROCESS_PIPELINE_H + +#include +#include + +#include "data_buffer.h" +#include "data_process_listener.h" +#include "distributed_camera_errno.h" +#include "idata_process_pipeline.h" +#include "image_common_type.h" + +namespace OHOS { +namespace DistributedHardware { +class MockDataProcessPipeline : public IDataProcessPipeline, + public std::enable_shared_from_this { +public: + ~MockDataProcessPipeline() + { + } + + int32_t CreateDataProcessPipeline(PipelineType piplineType, + const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig, + const std::shared_ptr& listener) + { + return DCAMERA_OK; + } + + int32_t ProcessData(std::vector>& dataBuffers) + { + return DCAMERA_OK; + } + + void DestroyDataProcessPipeline() + { + } +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_controller.h b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..abb5601dd681eefedd0521f43fd249fccc4173c2 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_controller.h @@ -0,0 +1,78 @@ +/* + * 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_MOCK_DCAMERA_SINK_CONTROLLER_H +#define OHOS_MOCK_DCAMERA_SINK_CONTROLLER_H + +#include "icamera_controller.h" +#include "icamera_sink_access_control.h" + +namespace OHOS { +namespace DistributedHardware { +class MockDCameraSinkController : public ICameraController { +public: + explicit MockDCameraSinkController(const std::shared_ptr& accessControl) + { + } + + ~MockDCameraSinkController() + { + } + + int32_t StartCapture(std::vector>& captureInfos) + { + return DCAMERA_OK; + } + int32_t StopCapture() + { + return DCAMERA_OK; + } + int32_t ChannelNeg(std::shared_ptr& info) + { + return DCAMERA_OK; + } + int32_t DCameraNotify(std::shared_ptr& events) + { + return DCAMERA_OK; + } + int32_t UpdateSettings(std::vector>& settings) + { + return DCAMERA_OK; + } + int32_t GetCameraInfo(std::shared_ptr& camInfo) + { + return DCAMERA_OK; + } + int32_t OpenChannel(std::shared_ptr& openInfo) + { + return DCAMERA_OK; + } + int32_t CloseChannel() + { + return DCAMERA_OK; + } + int32_t Init(std::vector& indexs) + { + return DCAMERA_OK; + } + int32_t UnInit() + { + return DCAMERA_OK; + } +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_data_process.h b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..7096cd47d20200edab0de2ea73dd39e084128265 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_data_process.h @@ -0,0 +1,78 @@ +/* + * 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_MOCK_DCAMERA_SINK_DATA_PROCESS_H +#define OHOS_MOCK_DCAMERA_SINK_DATA_PROCESS_H + +#include +#include + +#include "event.h" +#include "event_bus.h" + +#include "data_buffer.h" +#include "data_process_listener.h" +#include "dcamera_capture_info_cmd.h" +#include "dcamera_index.h" +#include "dcamera_photo_output_event.h" +#include "dcamera_video_output_event.h" +#include "icamera_channel.h" +#include "icamera_channel_listener.h" +#include "icamera_sink_data_process.h" + +namespace OHOS { +namespace DistributedHardware { +class MockDCameraSinkDataProcess : public ICameraSinkDataProcess, public EventSender, + public DistributedHardware::EventBusHandler, + public DistributedHardware::EventBusHandler, + public std::enable_shared_from_this { +public: + explicit MockDCameraSinkDataProcess(const std::shared_ptr& channel) + { + } + + ~MockDCameraSinkDataProcess() + { + } + + int32_t StartCapture(std::shared_ptr& captureInfo) + { + return DCAMERA_OK; + } + int32_t StopCapture() + { + return DCAMERA_OK; + } + int32_t FeedStream(std::shared_ptr& dataBuffer) + { + return DCAMERA_OK; + } + void OnEvent(DCameraPhotoOutputEvent& event) + { + } + void OnEvent(DCameraVideoOutputEvent& event) + { + } + void OnProcessedVideoBuffer(const std::shared_ptr& videoResult) + { + } + void OnError(DataProcessErrorType errorType) + { + } +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_output.h b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_output.h new file mode 100644 index 0000000000000000000000000000000000000000..56ca76b0fc53d0d7c4d52023bb696c7af00ed8e8 --- /dev/null +++ b/services/cameraservice/sinkservice/test/unittest/common/distributedcameramgr/mock_dcamera_sink_output.h @@ -0,0 +1,63 @@ +/* + * 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_MOCK_DCAMERA_SINK_OUTPUT_H +#define OHOS_MOCK_DCAMERA_SINK_OUTPUT_H + +#include "distributed_camera_errno.h" +#include "icamera_operator.h" +#include "icamera_sink_output.h" + +namespace OHOS { +namespace DistributedHardware { +class MockDCameraSinkOutput : public ICameraSinkOutput { +public: + explicit MockDCameraSinkOutput(const std::string& dhId, const std::shared_ptr& cameraOperator) + { + } + + ~MockDCameraSinkOutput() + { + } + + int32_t Init() + { + return DCAMERA_OK; + } + int32_t UnInit() + { + return DCAMERA_OK; + } + int32_t StartCapture(std::vector>& captureInfos) + { + return DCAMERA_OK; + } + int32_t StopCapture() + { + return DCAMERA_OK; + } + int32_t OpenChannel(std::shared_ptr& info) + { + return DCAMERA_OK; + } + int32_t CloseChannel() + { + return DCAMERA_OK; + } +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/BUILD.gn b/services/cameraservice/sourceservice/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..54b3d77204bd3843e87d2f238f072b9a4df3c960 --- /dev/null +++ b/services/cameraservice/sourceservice/BUILD.gn @@ -0,0 +1,115 @@ +# 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. + +import("//build/ohos.gni") +import("//build/ohos_var.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_source") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/eventbus", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + "//third_party/jsoncpp/include", + "//drivers/peripheral/base", + ] + + include_dirs += [ + "include/distributedcamera", + "include/distributedcameramgr", + "include/distributedcameramgr/dcamerainterface", + "include/distributedcameramgr/dcamerastate", + "include/distributedcameramgr/dcameracontrol", + "include/distributedcameramgr/dcameradata", + "include/distributedcameramgr/dcamerahdf", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${innerkits_path}/native_cpp/camera_source/include", + "${innerkits_path}/native_cpp/camera_sink/include", + "${innerkits_path}/native_cpp/camera_source/include/callback", + "${distributedcamera_hdf_path}/interfaces/include", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/client/provider", + "${services_path}/cameraservice/base/include", + "${services_path}/channel/include", + "${services_path}/data_process/include/eventbus", + "${services_path}/data_process/include/interfaces", + "${services_path}/data_process/include/pipeline", + "${services_path}/data_process/include/utils", + ] + + sources = [ + "src/distributedcamera/dcamera_service_state_listener.cpp", + "src/distributedcamera/distributed_camera_source_service.cpp", + "${innerkits_path}/native_cpp/camera_sink/src/distributed_camera_sink_proxy.cpp", + "src/distributedcamera/distributed_camera_source_stub.cpp", + "src/distributedcamera/dcamera_source_callback_proxy.cpp", + "src/distributedcameramgr/dcamera_source_dev.cpp", + "src/distributedcameramgr/dcamera_source_event.cpp", + "src/distributedcameramgr/dcamera_source_service_ipc.cpp", + "src/distributedcameramgr/dcamerastate/dcamera_source_state_factory.cpp", + "src/distributedcameramgr/dcamerastate/dcamera_source_state_machine.cpp", + "src/distributedcameramgr/dcamerastate/dcamera_source_init_state.cpp", + "src/distributedcameramgr/dcamerastate/dcamera_source_regist_state.cpp", + "src/distributedcameramgr/dcamerastate/dcamera_source_opened_state.cpp", + "src/distributedcameramgr/dcamerastate/dcamera_source_config_stream_state.cpp", + "src/distributedcameramgr/dcamerastate/dcamera_source_capture_state.cpp", + "src/distributedcameramgr/dcameracontrol/dcamera_source_controller.cpp", + "src/distributedcameramgr/dcameracontrol/dcamera_source_controller_channel_listener.cpp", + "${services_path}/cameraservice/base/src/dcamera_capture_info_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_channel_info_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_event_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_info_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_metadata_setting_cmd.cpp", + "${services_path}/cameraservice/base/src/dcamera_open_info_cmd.cpp", + + "src/distributedcameramgr/dcameradata/dcamera_source_data_process.cpp", + "src/distributedcameramgr/dcameradata/dcamera_source_input_channel_listener.cpp", + "src/distributedcameramgr/dcameradata/dcamera_source_input.cpp", + "src/distributedcameramgr/dcameradata/dcamera_stream_data_process_pipeline_listener.cpp", + "src/distributedcameramgr/dcameradata/dcamera_stream_data_process_producer.cpp", + "src/distributedcameramgr/dcameradata/dcamera_stream_data_process.cpp", + "src/distributedcameramgr/dcamerahdf/dcamera_provider_callback_impl.cpp", + ] + + deps = [ + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "${services_path}/channel:distributed_camera_channel", + "${services_path}/data_process:distributed_camera_data_process", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/client:distributed_camera_hdf_client", + "//utils/native/base:utils", + "//third_party/jsoncpp:jsoncpp", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dcamerasourcesvr\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcamera/dcamera_service_state_listener.h b/services/cameraservice/sourceservice/include/distributedcamera/dcamera_service_state_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..938e5662081e1911fe0bb04b7eb100bf0a8c1dbc --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcamera/dcamera_service_state_listener.h @@ -0,0 +1,39 @@ +/* + * 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_DCAMERA_SERVICE_STATE_LISTENER_H +#define OHOS_DCAMERA_SERVICE_STATE_LISTENER_H + +#include "icamera_state_listener.h" +#include "idcamera_source_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraServiceStateListener : public ICameraStateListener { +public: + DCameraServiceStateListener(sptr callback); + ~DCameraServiceStateListener(); + + int32_t OnRegisterNotify(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) override; + int32_t OnUnregisterNotify(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) override; + +private: + sptr callbackProxy_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcamera/dcamera_source_callback_proxy.h b/services/cameraservice/sourceservice/include/distributedcamera/dcamera_source_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..e2afe9baeec5a02e54fb7d9bb70cbe005258e74c --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcamera/dcamera_source_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_DCAMERA_SOURCE_CALLBACK_PROXY_H +#define OHOS_DCAMERA_SOURCE_CALLBACK_PROXY_H +#include + +#include "iremote_proxy.h" +#include "iremote_broker.h" +#include "refbase.h" + +#include "idcamera_source_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceCallbackProxy : public IRemoteProxy { +public: + explicit DCameraSourceCallbackProxy(const sptr &impl) : IRemoteProxy(impl) + {} + ~DCameraSourceCallbackProxy() + {} + + int32_t OnNotifyRegResult(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) override; + int32_t OnNotifyUnregResult(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) override; +private: + static inline BrokerDelegator delegator_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcamera/distributed_camera_source_service.h b/services/cameraservice/sourceservice/include/distributedcamera/distributed_camera_source_service.h new file mode 100644 index 0000000000000000000000000000000000000000..6dfb6ee57afa6473ab36a8a4fa3b12d0f927c23e --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcamera/distributed_camera_source_service.h @@ -0,0 +1,68 @@ +/* + * 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_DISTRIBUTED_CAMERA_SOURCE_SERVICE_H +#define OHOS_DISTRIBUTED_CAMERA_SOURCE_SERVICE_H + +#include +#include +#include + +#include "system_ability.h" +#include "ipc_object_stub.h" + +#include "dcamera_index.h" +#include "dcamera_source_dev.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_source_stub.h" + +namespace OHOS { +namespace DistributedHardware { +class DistributedCameraSourceService : public SystemAbility, public DistributedCameraSourceStub { +DECLARE_SYSTEM_ABILITY(DistributedCameraSourceService); +public: + DistributedCameraSourceService(int32_t saId, bool runOnCreate); + ~DistributedCameraSourceService() = default; + + int32_t InitSource(const std::string& params, const sptr& callback) override; + int32_t ReleaseSource() override; + int32_t RegisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId, const EnableParam& param) override; + int32_t UnregisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId) override; + int32_t DCameraNotify(const std::string& devId, const std::string& dhId, std::string& events) override; + + static std::map> camerasMap_; + +protected: + void OnStart() override; + void OnStop() override; + DISALLOW_COPY_AND_MOVE(DistributedCameraSourceService); + +private: + bool Init(); + int32_t LoadDCameraHDF(); + int32_t UnLoadCameraHDF(); + + bool registerToService_ = false; + DCameraServiceState state_ = DCameraServiceState::DCAMERA_SRV_STATE_NOT_START; + + sptr callbackProxy_; + std::string sourceVer_; +}; +} +} + +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcamera/distributed_camera_source_stub.h b/services/cameraservice/sourceservice/include/distributedcamera/distributed_camera_source_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..60eee15405ab1d785c397ec06bff23fe83fe51a0 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcamera/distributed_camera_source_stub.h @@ -0,0 +1,45 @@ +/* + * 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_DISTRIBUTED_CAMERA_SOURCE_STUB_H +#define OHOS_DISTRIBUTED_CAMERA_SOURCE_STUB_H + +#include +#include "iremote_stub.h" + +#include "idistributed_camera_source.h" + +namespace OHOS { +namespace DistributedHardware { +class DistributedCameraSourceStub : public IRemoteStub { +public: + DistributedCameraSourceStub(); + virtual ~DistributedCameraSourceStub(); + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t InitSourceInner(MessageParcel &data, MessageParcel &reply); + int32_t ReleaseSourceInner(MessageParcel &data, MessageParcel &reply); + int32_t RegisterDistributedHardwareInner(MessageParcel &data, MessageParcel &reply); + int32_t UnregisterDistributedHardwareInner(MessageParcel &data, MessageParcel &reply); + int32_t DCameraNotifyInner(MessageParcel &data, MessageParcel &reply); + + using DCameraFunc = int32_t (DistributedCameraSourceStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; +}; +} +} + +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_dev.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_dev.h new file mode 100644 index 0000000000000000000000000000000000000000..9e864ac13dfbb8ebda0b69858b568518357e1f12 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_dev.h @@ -0,0 +1,93 @@ +/* + * 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_DCAMERA_SOURCE_DEV_H +#define OHOS_DCAMERA_SOURCE_DEV_H + +#include "dcamera_index.h" +#include "dcamera_source_event.h" +#include "dcamera_source_state_machine.h" +#include "event_bus.h" +#include "icamera_controller.h" +#include "icamera_state_listener.h" +#include "icamera_input.h" + +#include "idistributed_camera_provider_callback.h" +#include "idistributed_camera_provider.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceDev : public EventSender, public DistributedHardware::EventBusHandler, + public std::enable_shared_from_this { +public: + explicit DCameraSourceDev(std::string devId, std::string dhId, std::shared_ptr& stateLisener); + virtual ~DCameraSourceDev(); + + int32_t InitDCameraSourceDev(); + int32_t RegisterDistributedHardware(const std::string& devId, const std::string& dhId, const std::string& reqId, + const std::string& ver, const std::string attrs); + int32_t UnRegisterDistributedHardware(const std::string devId, const std::string dhId, const std::string reqId); + int32_t DCameraNotify(std::string& eventStr); + + int32_t OpenSession(DCameraIndex& camIndex); + int32_t CloseSession(DCameraIndex& camIndex); + int32_t ConfigStreams(const std::vector>& streamInfos); + int32_t ReleaseStreams(const std::vector& streamIds); + int32_t StartCapture(const std::vector>& captureInfos); + int32_t StopCapture(); + int32_t UpdateCameraSettings(const std::vector>& settings); + + void OnEvent(DCameraSourceEvent& event) override; + +public: + virtual int32_t ExecuteRegister(std::shared_ptr& param); + virtual int32_t ExecuteUnRegister(std::shared_ptr& param); + virtual int32_t ExecuteOpenCamera(); + virtual int32_t ExecuteCloseCamera(); + virtual int32_t ExecuteConfigStreams(std::vector>& streamInfos); + virtual int32_t ExecuteReleaseStreams(std::vector& streamIds, bool& isAllRelease); + virtual int32_t ExecuteReleaseAllStreams(); + virtual int32_t ExecuteStartCapture(std::vector>& captureInfos); + virtual int32_t ExecuteStopCapture(); + virtual int32_t ExecuteUpdateSettings(std::vector>& settings); + virtual int32_t ExecuteCameraEventNotify(std::shared_ptr& events); + +private: + using DCameraNotifyFunc = void (DCameraSourceDev::*)(DCAMERA_EVENT eventType, DCameraSourceEvent& event, + int32_t result); + + void NotifyResult(DCAMERA_EVENT eventType, DCameraSourceEvent& event, int32_t result); + void NotifyRegisterResult(DCAMERA_EVENT eventType, DCameraSourceEvent& event, int32_t result); + void NotifyUnregisterResult(DCAMERA_EVENT eventType, DCameraSourceEvent& event, int32_t result); + void NotifyHalResult(DCAMERA_EVENT eventType, DCameraSourceEvent& event, int32_t result); + +private: + std::string devId_; + std::string dhId_; + std::string version_; + std::set actualDevInfo_; + std::shared_ptr stateListener_; + std::shared_ptr eventBus_; + std::shared_ptr stateMachine_; + std::shared_ptr controller_; + std::shared_ptr input_; + sptr hdiCallback_; + + std::map memberFuncMap_; + std::map eventResultMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_event.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_event.h new file mode 100644 index 0000000000000000000000000000000000000000..7517da9b6aa0d952a896289e4cafb618c4ae480d --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_event.h @@ -0,0 +1,124 @@ +/* + * 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_DCAMERA_SOURCE_EVENT_H +#define OHOS_DCAMERA_SOURCE_EVENT_H + +#include + +#include "event.h" +#include "types.h" + +#include "dcamera_event_cmd.h" +#include "dcamera_index.h" + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DCAMERA_EVENT_REGIST = 0, + DCAMERA_EVENT_UNREGIST = 1, + DCAMERA_EVENT_OPEN = 2, + DCAMERA_EVENT_CLOSE = 3, + DCAMERA_EVENT_CONFIG_STREAMS = 4, + DCAMERA_EVENT_RELEASE_STREAMS = 5, + DCAMERA_EVENT_START_CAPTURE = 6, + DCAMERA_EVENT_STOP_CAPTURE = 7, + DCAMERA_EVENT_UPDATE_SETTINGS = 8, + DCAMERA_EVENT_NOFIFY = 9, +} DCAMERA_EVENT; + +class DCameraRegistParam { +public: + DCameraRegistParam() = default; + DCameraRegistParam(std::string devId, std::string dhId, std::string reqId, std::string param) + : devId_(devId), dhId_(dhId), reqId_(reqId), param_(param) + {} + ~DCameraRegistParam() = default; + std::string devId_; + std::string dhId_; + std::string reqId_; + std::string param_; +}; + +class DCameraSourceEvent : public Event { + TYPEINDENT(DCameraSourceEvent) +public: + DCameraSourceEvent(EventSender& sender) : Event(sender) {} + ~DCameraSourceEvent() = default; + explicit DCameraSourceEvent(EventSender& sender, DCAMERA_EVENT eventType) + : Event(sender), eventType_(eventType) {} + explicit DCameraSourceEvent(EventSender& sender, DCAMERA_EVENT eventType, DCameraIndex& index) + : Event(sender), eventType_(eventType) + { + eventParam_ = index; + } + + explicit DCameraSourceEvent(EventSender& sender, DCAMERA_EVENT eventType, + std::shared_ptr& param) : Event(sender), eventType_(eventType) + { + eventParam_ = param; + } + + explicit DCameraSourceEvent(EventSender& sender, DCAMERA_EVENT eventType, + const std::vector>& streamInfos) : Event(sender), eventType_(eventType) + { + eventParam_ = std::move(streamInfos); + } + + explicit DCameraSourceEvent(EventSender& sender, DCAMERA_EVENT eventType, + const std::vector>& captureInfos) : Event(sender), eventType_(eventType) + { + eventParam_ = std::move(captureInfos); + } + + explicit DCameraSourceEvent(EventSender& sender, DCAMERA_EVENT eventType, + const std::vector>& settings) : Event(sender), eventType_(eventType) + { + eventParam_ = std::move(settings); + } + + explicit DCameraSourceEvent(EventSender& sender, DCAMERA_EVENT eventType, const std::vector& streamIds) + : Event(sender), eventType_(eventType) + { + eventParam_ = std::move(streamIds); + } + + explicit DCameraSourceEvent(EventSender& sender, DCAMERA_EVENT eventType, std::shared_ptr& camEvent) + : Event(sender), eventType_(eventType) + { + eventParam_ = camEvent; + } + + int32_t GetDCameraIndex(DCameraIndex& index); + int32_t GetDCameraRegistParam(std::shared_ptr& param); + int32_t GetStreamInfos(std::vector>& streamInfos); + int32_t GetCaptureInfos(std::vector>& captureInfos); + int32_t GetCameraSettings(std::vector>& settings); + int32_t GetStreamIds(std::vector& streamIds); + int32_t GetCameraEvent(std::shared_ptr& camEvent); + DCAMERA_EVENT GetEventType(); + +private: + using EventParam = std::variant, + std::vector>, std::vector>, + std::vector>, std::vector, std::shared_ptr>; + +private: + DCAMERA_EVENT eventType_; + EventParam eventParam_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_service_ipc.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_service_ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..b3bb6ced1f40e22b1084f78cb0b10a3a83a1b9f1 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamera_source_service_ipc.h @@ -0,0 +1,54 @@ +/* + * 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_DCAMERA_SOURCE_SERVICE_IPC_H +#define OHOS_DCAMERA_SOURCE_SERVICE_IPC_H + +#include "event_handler.h" +#include "idistributed_camera_sink.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceServiceIpc { +DECLARE_SINGLE_INSTANCE_BASE(DCameraSourceServiceIpc); +public: + void Init(); + void UnInit(); + sptr GetSinkRemoteDHMS(const std::string& deviceId); + void OnSinkRemoteDmsDied(const wptr& remote); + void DeleteSinkRemoteDhms(const std::string& deviceId); + +private: + DCameraSourceServiceIpc(); + ~DCameraSourceServiceIpc(); + void OnSinkRemoteDmsDied(const sptr& remote); + void ClearSinkRemoteDhms(); + + class SinkRemoteRecipient : public IRemoteObject::DeathRecipient { + public: + void OnRemoteDied(const wptr& remote) override; + }; + sptr sinkRemoteRecipient_; + std::map> remoteSinks_; + std::mutex sinkRemoteDmsLock_; + + bool isInit_; + std::shared_ptr serviceHandler_; + std::mutex initDmsLock_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcameracontrol/dcamera_source_controller.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameracontrol/dcamera_source_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..3817bce049f865a1e2ddae1c7533a8113669cbe2 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameracontrol/dcamera_source_controller.h @@ -0,0 +1,70 @@ +/* + * 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_DCAMERA_SOURCE_CONTROLLER_H +#define OHOS_DCAMERA_SOURCE_CONTROLLER_H + +#include "icamera_controller.h" + +#include "dcamera_index.h" +#include "icamera_channel_listener.h" +#include "dcamera_source_state_machine.h" +#include "event_bus.h" +#include "icamera_channel.h" + +#include "idistributed_camera_provider.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceController : public ICameraController, public EventSender, + public std::enable_shared_from_this { +public: + DCameraSourceController(std::string devId, std::string dhId, + std::shared_ptr& stateMachine, std::shared_ptr& eventBus); + ~DCameraSourceController(); + int32_t StartCapture(std::vector>& captureInfos) override; + int32_t StopCapture() override; + int32_t ChannelNeg(std::shared_ptr& info) override; + int32_t DCameraNotify(std::shared_ptr& events) override; + int32_t UpdateSettings(std::vector>& settings) override; + int32_t GetCameraInfo(std::shared_ptr& camInfo) override; + int32_t OpenChannel(std::shared_ptr& openInfo) override; + int32_t CloseChannel() override; + int32_t Init(std::vector& indexs) override; + int32_t UnInit() override; + + void OnSessionState(int32_t state); + void OnSessionError(int32_t eventType, int32_t eventReason, std::string detail); + void OnDataReceived(std::vector>& buffers); + +private: + void HandleMetaDataResult(std::string& jsonStr); + +private: + std::string devId_; + std::string dhId_; + std::shared_ptr channel_; + std::shared_ptr listener_; + std::vector indexs_; + std::shared_ptr stateMachine_; + std::shared_ptr eventBus_; + int32_t channelState_; + + bool isInit; + const std::string SESSION_FLAG = "control"; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcameracontrol/dcamera_source_controller_channel_listener.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameracontrol/dcamera_source_controller_channel_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..316e3831cb82600901bbbcd0eda8ca7579c4afb4 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameracontrol/dcamera_source_controller_channel_listener.h @@ -0,0 +1,39 @@ +/* + * 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_DCAMERA_SOURCE_CONTROLLER_CHANNEL_LISTENER_H +#define OHOS_DCAMERA_SOURCE_CONTROLLER_CHANNEL_LISTENER_H + +#include + +#include "icamera_channel_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceController; +class DCameraSourceControllerChannelListener : public ICameraChannelListener { +public: + DCameraSourceControllerChannelListener(std::shared_ptr& controller); + ~DCameraSourceControllerChannelListener(); + void OnSessionState(int32_t state) override; + void OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) override; + void OnDataReceived(std::vector>& buffers) override; + +private: + std::weak_ptr controller_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_data_process.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..8ab873c768c6fb3ab89a954903c42f93a9c57e33 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_data_process.h @@ -0,0 +1,50 @@ +/* + * 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_DCAMERA_SOURCE_DATRA_PROCESS_H +#define OHOS_DCAMERA_SOURCE_DATRA_PROCESS_H + +#include +#include + +#include "dcamera_stream_data_process.h" +#include "icamera_source_data_process.h" + +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceDataProcess : public ICameraSourceDataProcess { +public: + DCameraSourceDataProcess(std::string devId, std::string dhId, DCStreamType streamType); + ~DCameraSourceDataProcess(); + + int32_t FeedStream(std::vector>& buffers) override; + int32_t ConfigStreams(std::vector>& streamInfos) override; + int32_t ReleaseStreams(std::vector& streamIds) override; + int32_t StartCapture(std::shared_ptr& captureInfo) override; + int32_t StopCapture() override; + void GetAllStreamIds(std::vector& streamIds) override; + +private: + std::vector> streamProcess_; + std::set streamIds_; + std::string devId_; + std::string dhId_; + DCStreamType streamType_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_input.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_input.h new file mode 100644 index 0000000000000000000000000000000000000000..c67b59dfe0179d78eb3338948b0a80ce2421655e --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_input.h @@ -0,0 +1,65 @@ +/* + * 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_DCAMERA_SOURCE_INPUT_H +#define OHOS_DCAMERA_SOURCE_INPUT_H + +#include "icamera_channel.h" +#include "icamera_channel_listener.h" +#include "icamera_input.h" +#include "icamera_source_data_process.h" + +#include "event_bus.h" +#include "event_sender.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceInput : public ICameraInput, public EventSender, + public std::enable_shared_from_this { +public: + DCameraSourceInput(std::string devId, std::string dhId, std::shared_ptr& eventBus); + ~DCameraSourceInput(); + + int32_t ConfigStreams(std::vector>& streamInfos) override; + int32_t ReleaseStreams(std::vector& streamIds, bool& isAllRelease) override; + int32_t ReleaseAllStreams() override; + int32_t StartCapture(std::vector>& captureInfos) override; + int32_t StopCapture() override; + int32_t OpenChannel(std::vector& indexs) override; + int32_t CloseChannel() override; + int32_t Init() override; + int32_t UnInit() override; + int32_t UpdateSettings(std::vector>& settings) override; + + void OnSessionState(DCStreamType streamType, int32_t state); + void OnSessionError(DCStreamType streamType, int32_t eventType, int32_t eventReason, std::string detail); + void OnDataReceived(DCStreamType streamType, std::vector>& buffers); + +private: + std::map> channels_; + std::map> listeners_; + std::map> dataProcess_; + std::map channelState_; + std::string devId_; + std::string dhId_; + std::shared_ptr eventBus_; + + bool isInit = false; + std::mutex inputMutex_; + bool isCapture_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_input_channel_listener.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_input_channel_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..98f8a510c04735dbf7cf325441afaace95d71ac5 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_source_input_channel_listener.h @@ -0,0 +1,41 @@ +/* + * 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_DCAMERA_SOURCE_INPUT_CHANNEL_LISTENER_H +#define OHOS_DCAMERA_SOURCE_INPUT_CHANNEL_LISTENER_H + +#include + +#include "icamera_channel_listener.h" +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceInput; +class DCameraSourceInputChannelListener : public ICameraChannelListener { +public: + DCameraSourceInputChannelListener(std::shared_ptr& Input, DCStreamType streamType); + ~DCameraSourceInputChannelListener(); + void OnSessionState(int32_t state) override; + void OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) override; + void OnDataReceived(std::vector>& buffers) override; + +private: + std::weak_ptr input_; + DCStreamType streamType_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..a9f37b50234a823711dfa7899ff84b7aa942d272 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process.h @@ -0,0 +1,67 @@ +/* + * 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_DCAMERA_STREAM_DATA_PROCESS_H +#define OHOS_DCAMERA_STREAM_DATA_PROCESS_H + +#include + +#include "data_buffer.h" +#include "icamera_source_data_process.h" +#include "idata_process_pipeline.h" +#include "image_common_type.h" +#include "types.h" + +#include "dcamera_stream_data_process_producer.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraStreamDataProcess : public std::enable_shared_from_this { +public: + DCameraStreamDataProcess(std::string devId, std::string dhId, DCStreamType streamType); + ~DCameraStreamDataProcess(); + void FeedStream(std::shared_ptr& buffer); + void ConfigStreams(std::shared_ptr& dstConfig, std::set& streamIds); + void ReleaseStreams(std::set& streamIds); + void StartCapture(std::shared_ptr& srcConfig, std::set& streamIds); + void StopCapture(); + void GetAllStreamIds(std::set& streamIds); + + void OnProcessedVideoBuffer(const std::shared_ptr& videoResult); + void OnError(DataProcessErrorType errorType); + +private: + void FeedStreamToSnapShot(const std::shared_ptr& buffer); + void FeedStreamToContinue(const std::shared_ptr& buffer); + void CreatePipeline(); + void DestroyPipeline(); + VideoCodecType GetPipelineCodecType(DCEncodeType encodeType); + Videoformat GetPipelineFormat(int32_t format); + +private: + std::string devId_; + std::string dhId_; + DCStreamType streamType_; + + std::set streamIds_; + std::shared_ptr srcConfig_; + std::shared_ptr dstConfig_; + std::shared_ptr pipeline_; + std::shared_ptr listener_; + std::map> producers_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process_pipeline_listener.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process_pipeline_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..06c8bfa4d2c1e21c8844066e1258e131f9a9ed89 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process_pipeline_listener.h @@ -0,0 +1,40 @@ +/* + * 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_DCAMERA_STREAM_DATA_PROCESS_PIPELINE_LISTENER_H +#define OHOS_DCAMERA_STREAM_DATA_PROCESS_PIPELINE_LISTENER_H + +#include + +#include "data_buffer.h" +#include "data_process_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraStreamDataProcess; +class DCameraStreamDataProcessPipelineListener : public DataProcessListener { +public: + DCameraStreamDataProcessPipelineListener(std::shared_ptr& process); + ~DCameraStreamDataProcessPipelineListener(); + + void OnProcessedVideoBuffer(const std::shared_ptr& videoResult) override; + void OnError(DataProcessErrorType errorType) override; + +private: + std::weak_ptr process_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process_producer.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process_producer.h new file mode 100644 index 0000000000000000000000000000000000000000..ceb2d27a205e2c43585c0f582df795482ec3e111 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcameradata/dcamera_stream_data_process_producer.h @@ -0,0 +1,67 @@ +/* + * 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_ICAMERA_SOURCE_DATA_PROCESS_PRODUCER_H +#define OHOS_ICAMERA_SOURCE_DATA_PROCESS_PRODUCER_H + +#include +#include +#include +#include + +#include "data_buffer.h" +#include "event_handler.h" +#include "idistributed_camera_provider.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraStreamDataProcessProducer { +public: + typedef enum { + DCAMERA_PRODUCER_STATE_STOP = 0, + DCAMERA_PRODUCER_STATE_START = 1, + } DCameraProducerState; + + DCameraStreamDataProcessProducer(std::string devId, std::string dhId, int32_t streamId, DCStreamType streamType); + ~DCameraStreamDataProcessProducer(); + void Start(); + void Stop(); + void FeedStream(const std::shared_ptr& buffer); + void UpdateInterval(uint32_t fps); +private: + void LooperContinue(); + void LooperSnapShot(); + int32_t FeedStreamToDriver(const std::shared_ptr& dhBase, const std::shared_ptr& buffer); + + const uint32_t DCAMERA_PRODUCER_MAX_BUFFER_SIZE = 30; + const uint32_t DCAMERA_PRODUCER_RETRY_SLEEP_MS = 500; + +private: + std::string devId_; + std::string dhId_; + + std::thread producerThread_; + std::condition_variable producerCon_; + std::mutex producerMutex_; + std::queue> buffers_; + DCameraProducerState state_; + uint32_t interval_; + int32_t streamId_; + DCStreamType streamType_; + std::shared_ptr eventHandler_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerahdf/dcamera_provider_callback_impl.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerahdf/dcamera_provider_callback_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..51c7aac82e83d578788a41b3407f9d19d938f620 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerahdf/dcamera_provider_callback_impl.h @@ -0,0 +1,47 @@ +/* + * 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_DCAMERA_PROVIDER_CALLBACK_IMPL_H +#define OHOS_DCAMERA_PROVIDER_CALLBACK_IMPL_H + +#include "dcamera_provider_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceDev; +class DCameraProviderCallbackImpl : public DCameraProviderCallback { +public: + DCameraProviderCallbackImpl(std::string devId, std::string dhId, std::shared_ptr& sourceDev); + ~DCameraProviderCallbackImpl(); + + DCamRetCode OpenSession(const std::shared_ptr& dhBase) override; + DCamRetCode CloseSession(const std::shared_ptr& dhBase) override; + DCamRetCode ConfigureStreams(const std::shared_ptr& dhBase, + const std::vector>& streamInfos) override; + DCamRetCode ReleaseStreams(const std::shared_ptr& dhBase, const std::vector& streamIds) override; + DCamRetCode StartCapture(const std::shared_ptr& dhBase, + const std::vector>& captureInfos) override; + DCamRetCode StopCapture(const std::shared_ptr& dhBase) override; + DCamRetCode UpdateSettings(const std::shared_ptr& dhBase, + const std::vector>& settings) override; + +private: + std::string devId_; + std::string dhId_; + std::weak_ptr sourceDev_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_input.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_input.h new file mode 100644 index 0000000000000000000000000000000000000000..13e65810826b5016f7a993f718d5ee336d51c04e --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_input.h @@ -0,0 +1,40 @@ +/* + * 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_ICAMERA_INPUT_H +#define OHOS_ICAMERA_INPUT_H + +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class ICameraInput { +public: + virtual ~ICameraInput() = default; + + virtual int32_t ConfigStreams(std::vector>& streamInfos) = 0; + virtual int32_t ReleaseStreams(std::vector& streamIds, bool& isAllRelease) = 0; + virtual int32_t ReleaseAllStreams() = 0; + virtual int32_t StartCapture(std::vector>& captureInfos) = 0; + virtual int32_t StopCapture() = 0; + virtual int32_t OpenChannel(std::vector& indexs) = 0; + virtual int32_t CloseChannel() = 0; + virtual int32_t Init() = 0; + virtual int32_t UnInit() = 0; + virtual int32_t UpdateSettings(std::vector>& settings) = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_source_data_process.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_source_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..5c19df20c7a2f07bb216d58204024ad3c4b36b44 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_source_data_process.h @@ -0,0 +1,67 @@ +/* + * 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_ICAMERA_SOURCE_DATA_PROCESS_H +#define OHOS_ICAMERA_SOURCE_DATA_PROCESS_H + +#include + +#include "data_buffer.h" +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraStreamConfig { +public: + DCameraStreamConfig(int32_t width, int32_t height, int32_t format, int32_t dataspace, + DCEncodeType encodeType, DCStreamType streamType) + : width_(width), height_(height), format_(format), dataspace_(dataspace), encodeType_(encodeType), + type_(streamType) + {} + ~DCameraStreamConfig() = default; + int32_t width_; + int32_t height_; + int32_t format_; + int32_t dataspace_; + DCEncodeType encodeType_; + DCStreamType type_; + + bool operator == (const DCameraStreamConfig& others) const + { + return this->width_ == others.width_ && this->height_ == others.height_ && this->format_ == others.format_ && + this->dataspace_ == others.dataspace_ && this->encodeType_ == others.encodeType_ && + this->type_ == others.type_; + } + + bool operator < (const DCameraStreamConfig& others) const + { + return (this->width_ < others.width_) || ((this->width_ == others.width_) && (this->height_ < this->height_)); + } +}; + +class ICameraSourceDataProcess { +public: + virtual ~ICameraSourceDataProcess() = default; + + virtual int32_t FeedStream(std::vector>& buffers) = 0; + virtual int32_t ConfigStreams(std::vector>& streamInos) = 0; + virtual int32_t ReleaseStreams(std::vector& streamIds) = 0; + virtual int32_t StartCapture(std::shared_ptr& captureInfo) = 0; + virtual int32_t StopCapture() = 0; + virtual void GetAllStreamIds(std::vector& streamIds) = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_state_listener.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_state_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..613c2c26690058838bbc773a531692379645849d --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface/icamera_state_listener.h @@ -0,0 +1,34 @@ +/* + * 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_ICAMERA_STATE_LISTENER_H +#define OHOS_ICAMERA_STATE_LISTENER_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class ICameraStateListener { +public: + virtual ~ICameraStateListener() {} + virtual int32_t OnRegisterNotify(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) = 0; + virtual int32_t OnUnregisterNotify(const std::string& devId, const std::string& dhId, const std::string& reqId, + int32_t status, std::string& data) = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_capture_state.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_capture_state.h new file mode 100644 index 0000000000000000000000000000000000000000..b7ce816f07abf71bd65442e975f8cd208c3c996b --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_capture_state.h @@ -0,0 +1,52 @@ +/* + * 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_DCAMERA_SOURCE_CAPTURE_STATE_H +#define OHOS_DCAMERA_SOURCE_CAPTURE_STATE_H + +#include +#include "dcamera_source_state.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceCaptureState : public DCameraSourceState { +public: + DCameraSourceCaptureState(std::shared_ptr& stateMachine); + ~DCameraSourceCaptureState() {} + + int32_t Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) override; + DCameraStateType GetStateType() override; + +private: + int32_t DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoUnregisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoOpenTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoCloseTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoStartCaptureTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoStopCaptureTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoUpdateSettingsTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoEventNofityTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + + using DCameraFunc = int32_t (DCameraSourceCaptureState::*)(std::shared_ptr& camDev, + DCameraSourceEvent& event); + +private: + std::weak_ptr stateMachine_; + std::map memberFuncMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_config_stream_state.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_config_stream_state.h new file mode 100644 index 0000000000000000000000000000000000000000..c50149d38200c71e5687b91b417b58fa28acae52 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_config_stream_state.h @@ -0,0 +1,55 @@ +/* + * 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_DCAMERA_SOURCE_CONFIG_STREAM_STATE_H +#define OHOS_DCAMERA_SOURCE_CONFIG_STREAM_STATE_H + +#include +#include "dcamera_source_state.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceConfigStreamState : public DCameraSourceState { +public: + DCameraSourceConfigStreamState(std::shared_ptr& stateMachine); + DCameraSourceConfigStreamState() {} + ~DCameraSourceConfigStreamState() {} + + int32_t Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) override; + DCameraStateType GetStateType() override; + +private: + int32_t DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoUnregisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoOpenTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoCloseTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoConfigStreamsTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoReleaseStreamsTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoStartCaptureTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoStopCaptureTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoUpdateSettingsTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoEventNofityTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + + using DCameraFunc = int32_t (DCameraSourceConfigStreamState::*)(std::shared_ptr& camDev, + DCameraSourceEvent& event); + +private: + std::weak_ptr stateMachine_; + std::map memberFuncMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_init_state.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_init_state.h new file mode 100644 index 0000000000000000000000000000000000000000..dc93777989107f53629667114adc2a5d1570e64a --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_init_state.h @@ -0,0 +1,46 @@ +/* + * 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_DCAMERA_SOURCE_INIT_STATE_H +#define OHOS_DCAMERA_SOURCE_INIT_STATE_H + +#include +#include "dcamera_source_state.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceInitState : public DCameraSourceState { +public: + DCameraSourceInitState(std::shared_ptr& stateMachine); + ~DCameraSourceInitState() {} + + int32_t Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) override; + DCameraStateType GetStateType() override; + +private: + int32_t DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoUnregisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + + using DCameraFunc = int32_t (DCameraSourceInitState::*)(std::shared_ptr& camDev, + DCameraSourceEvent& event); + +private: + std::weak_ptr stateMachine_; + std::map memberFuncMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_opened_state.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_opened_state.h new file mode 100644 index 0000000000000000000000000000000000000000..b46b9e3229a4eeefea22a4d4f28fe08fcb37da1f --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_opened_state.h @@ -0,0 +1,52 @@ +/* + * 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_DCAMERA_SOURCE_OPENED_STATE_H +#define OHOS_DCAMERA_SOURCE_OPENED_STATE_H + +#include +#include "dcamera_source_state.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceOpenedState : public DCameraSourceState { +public: + DCameraSourceOpenedState(std::shared_ptr& stateMachine); + ~DCameraSourceOpenedState() {} + + int32_t Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) override; + DCameraStateType GetStateType() override; + +private: + int32_t DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoUnregisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoConfigStreamsTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoReleaseStreamsTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoUpdateSettingsTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoOpenTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoCloseTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoEventNofityTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + + using DCameraFunc = int32_t (DCameraSourceOpenedState::*)(std::shared_ptr& camDev, + DCameraSourceEvent& event); + +private: + std::weak_ptr stateMachine_; + std::map memberFuncMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_regist_state.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_regist_state.h new file mode 100644 index 0000000000000000000000000000000000000000..775cdc015f92851c90df01c87e173547147f442a --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_regist_state.h @@ -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. + */ + +#ifndef OHOS_DCAMERA_SOURCE_REGIST_STATE_H +#define OHOS_DCAMERA_SOURCE_REGIST_STATE_H + +#include +#include "dcamera_source_state.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceRegistState : public DCameraSourceState { +public: + DCameraSourceRegistState(std::shared_ptr& stateMachine); + ~DCameraSourceRegistState() {} + + int32_t Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) override; + DCameraStateType GetStateType() override; + +private: + int32_t DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoUnregisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoOpenTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoCloseTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + int32_t DoEventNofityTask(std::shared_ptr& camDev, DCameraSourceEvent& event); + + using DCameraFunc = int32_t (DCameraSourceRegistState::*)(std::shared_ptr& camDev, + DCameraSourceEvent& event); + +private: + std::weak_ptr stateMachine_; + std::map memberFuncMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state.h new file mode 100644 index 0000000000000000000000000000000000000000..1e908c2a2dc24831a54040ca2b1edff6537e25a9 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state.h @@ -0,0 +1,43 @@ +/* + * 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_DCAMERA_SOURCE_STATE_H +#define OHOS_DCAMERA_SOURCE_STATE_H +#include "dcamera_source_event.h" + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DCAMERA_STATE_INIT = 0, + DCAMERA_STATE_REGIST = 1, + DCAMERA_STATE_OPENED = 2, + DCAMERA_STATE_CONFIG_STREAM = 3, + DCAMERA_STATE_CAPTURE = 4, +} DCameraStateType; + +class DCameraSourceDev; +class DCameraSourceStateMachine; +class DCameraSourceState { +public: + DCameraSourceState() {} + virtual ~DCameraSourceState() {} + + virtual int32_t Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) = 0; + virtual DCameraStateType GetStateType() = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state_factory.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..44ddf0ad7d4c4a4680b137772e671a96bbba174d --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state_factory.h @@ -0,0 +1,31 @@ +/* + * 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_DCAMERA_SOURCE_STATE_FACTORY_H +#define OHOS_DCAMERA_SOURCE_STATE_FACTORY_H +#include "single_instance.h" +#include "dcamera_source_state.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceStateFactory { +DECLARE_SINGLE_INSTANCE(DCameraSourceStateFactory); +public: + std::shared_ptr CreateState(DCameraStateType stateType, + std::shared_ptr& stateMachine); +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state_machine.h b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state_machine.h new file mode 100644 index 0000000000000000000000000000000000000000..030ed940d550957d577caf8ce2dd453a062a3911 --- /dev/null +++ b/services/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate/dcamera_source_state_machine.h @@ -0,0 +1,37 @@ +/* + * 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_DCAMERA_SOURCE_STATE_MACHINE_H +#define OHOS_DCAMERA_SOURCE_STATE_MACHINE_H +#include "dcamera_source_event.h" +#include "dcamera_source_state.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceDev; +class DCameraSourceStateMachine : public std::enable_shared_from_this { +public: + DCameraSourceStateMachine(std::shared_ptr& camDev); + ~DCameraSourceStateMachine(); + int32_t Execute(DCAMERA_EVENT eventType, DCameraSourceEvent& event); + void UpdateState(DCameraStateType stateType); + +private: + std::shared_ptr currentState_; + std::weak_ptr camDev_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcamera/dcamera_service_state_listener.cpp b/services/cameraservice/sourceservice/src/distributedcamera/dcamera_service_state_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4eff7096879ad4fec58e95a3a95d9cb049a19746 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcamera/dcamera_service_state_listener.cpp @@ -0,0 +1,92 @@ +/* + * 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 "dcamera_service_state_listener.h" + +#include + +#include "anonymous_string.h" +#include "dcamera_index.h" +#include "distributed_camera_errno.h" +#include "distributed_camera_source_service.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraServiceStateListener::DCameraServiceStateListener(sptr callback) + : callbackProxy_(callback) +{ + DHLOGI("DCameraServiceStateListener Create"); +} + +DCameraServiceStateListener::~DCameraServiceStateListener() +{ + DHLOGI("DCameraServiceStateListener Delete"); + callbackProxy_ = nullptr; +} + +int32_t DCameraServiceStateListener::OnRegisterNotify(const std::string& devId, const std::string& dhId, + const std::string& reqId, int32_t status, std::string& data) +{ + DHLOGI("DCameraServiceStateListener OnRegisterNotify devId: %s, dhId: %s, status: %d", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), status); + if (callbackProxy_ == nullptr) { + DHLOGE("DCameraServiceStateListener OnRegisterNotify callbackProxy_ is nullptr"); + return DCAMERA_BAD_VALUE; + } + + int32_t ret = callbackProxy_->OnNotifyRegResult(devId, dhId, reqId, status, data); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraServiceStateListener OnRegisterNotify OnNotifyRegResult failed: %d", ret); + } + if (status != DCAMERA_OK) { + std::thread([this, &devId, &dhId]() { + DHLOGI("DCameraServiceStateListener OnRegisterNotify thread delete devId: %s dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + DCameraIndex camIndex(devId, dhId); + DistributedCameraSourceService::camerasMap_.erase(camIndex); + }).detach(); + } + return ret; +} + +int32_t DCameraServiceStateListener::OnUnregisterNotify(const std::string& devId, const std::string& dhId, + const std::string& reqId, int32_t status, std::string& data) +{ + DHLOGI("DCameraServiceStateListener OnUnregisterNotify devId: %s, dhId: %s, status: %d", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), status); + if (callbackProxy_ == nullptr) { + DHLOGE("DCameraServiceStateListener OnUnregisterNotify callbackProxy_ is nullptr"); + return DCAMERA_BAD_VALUE; + } + + int32_t ret = callbackProxy_->OnNotifyUnregResult(devId, dhId, reqId, status, data); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraServiceStateListener OnUnregisterNotify failed, ret: %d", ret); + } + + if (status == DCAMERA_OK) { + std::thread([this, &devId, &dhId]() { + DHLOGI("DCameraServiceStateListener OnUnregisterNotify thread delete devId: %s dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + DCameraIndex camIndex(devId, dhId); + DistributedCameraSourceService::camerasMap_.erase(camIndex); + }).detach(); + } + + return ret; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcamera/dcamera_source_callback_proxy.cpp b/services/cameraservice/sourceservice/src/distributedcamera/dcamera_source_callback_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ce269d75351e43b6fd15a78fc851d189a5c655c --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcamera/dcamera_source_callback_proxy.cpp @@ -0,0 +1,78 @@ +/* + * 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 "dcamera_source_callback_proxy.h" + +#include "parcel.h" + +#include "anonymous_string.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraSourceCallbackProxy::OnNotifyRegResult(const std::string& devId, const std::string& dhId, + const std::string& reqId, int32_t status, std::string& data) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DCameraSourceCallbackProxy remote service null"); + return DCAMERA_BAD_VALUE; + } + MessageParcel req; + MessageParcel reply; + MessageOption option; + if (!req.WriteInterfaceToken(DCameraSourceCallbackProxy::GetDescriptor())) { + DHLOGE("DCameraSourceCallbackProxy OnNotifyRegResult write token failed"); + return DCAMERA_BAD_VALUE; + } + + if (!req.WriteString(devId) || !req.WriteString(dhId) || !req.WriteString(reqId) || + !req.WriteInt32(status) || !req.WriteString(data)) { + DHLOGE("DistributedCameraSourceProxy InitSource write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(NOTIFY_REG_RESULT, req, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t DCameraSourceCallbackProxy::OnNotifyUnregResult(const std::string& devId, const std::string& dhId, + const std::string& reqId, int32_t status, std::string& data) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DHLOGE("DCameraSourceCallbackProxy remote service null"); + return DCAMERA_BAD_VALUE; + } + MessageParcel req; + MessageParcel reply; + MessageOption option; + if (!req.WriteInterfaceToken(DCameraSourceCallbackProxy::GetDescriptor())) { + DHLOGE("DCameraSourceCallbackProxy OnNotifyRegResult write token failed"); + return DCAMERA_BAD_VALUE; + } + + if (!req.WriteString(devId) || !req.WriteString(dhId) || !req.WriteString(reqId) || + !req.WriteInt32(status) || !req.WriteString(data)) { + DHLOGE("DistributedCameraSourceProxy InitSource write params failed"); + return DCAMERA_BAD_VALUE; + } + remote->SendRequest(NOTIFY_UNREG_RESULT, req, reply, option); + int32_t result = reply.ReadInt32(); + return result; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcamera/distributed_camera_source_service.cpp b/services/cameraservice/sourceservice/src/distributedcamera/distributed_camera_source_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fde25868584b29623854ce6876deccc3112ec3bf --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcamera/distributed_camera_source_service.cpp @@ -0,0 +1,198 @@ +/* + * 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 "distributed_camera_source_service.h" + +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +#include "anonymous_string.h" +#include "dcamera_service_state_listener.h" +#include "dcamera_source_service_ipc.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +REGISTER_SYSTEM_ABILITY_BY_ID(DistributedCameraSourceService, DISTRIBUTED_HARDWARE_CAMERA_SOURCE_SA_ID, true); + +std::map> DistributedCameraSourceService::camerasMap_; + +DistributedCameraSourceService::DistributedCameraSourceService(int32_t saId, bool runOnCreate) + : SystemAbility(saId, runOnCreate) +{ +} + +void DistributedCameraSourceService::OnStart() +{ + DHLOGI("DistributedCameraSourceService::OnStart"); + if (state_ == DCameraServiceState::DCAMERA_SRV_STATE_RUNNING) { + DHLOGI("DistributedCameraSourceService has already started."); + return; + } + + if (!Init()) { + DHLOGE("DistributedCameraSourceService init failed"); + return; + } + state_ = DCameraServiceState::DCAMERA_SRV_STATE_RUNNING; + DHLOGI("DCameraServiceState OnStart service success."); +} + +bool DistributedCameraSourceService::Init() +{ + DHLOGI("DistributedCameraSourceService start init"); + DCameraSourceServiceIpc::GetInstance().Init(); + if (!registerToService_) { + bool ret = Publish(this); + if (!ret) { + DHLOGE("DistributedCameraSourceService Publish service failed"); + return false; + } + registerToService_ = true; + } + DHLOGI("DistributedCameraSourceService init success"); + return true; +} + +void DistributedCameraSourceService::OnStop() +{ + DHLOGI("DistributedCameraSourceService OnStop service"); + state_ = DCameraServiceState::DCAMERA_SRV_STATE_NOT_START; + registerToService_ = false; + DCameraSourceServiceIpc::GetInstance().UnInit(); +} + +int32_t DistributedCameraSourceService::InitSource(const std::string& params, + const sptr& callback) +{ + DHLOGI("DistributedCameraSourceService InitSource param: %s", params.c_str()); + int32_t ret = LoadDCameraHDF(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSourceService InitSource LoadHDF failed, ret: %d", ret); + return ret; + } + sourceVer_ = params; + callbackProxy_ = callback; + return DCAMERA_OK; +} + +int32_t DistributedCameraSourceService::ReleaseSource() +{ + DHLOGI("DistributedCameraSourceService ReleaseSource"); + int32_t ret = UnLoadCameraHDF(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSourceService ReleaseSource UnLoadHDF failed, ret: %d", ret); + return ret; + } + callbackProxy_ = nullptr; + return DCAMERA_OK; +} + +int32_t DistributedCameraSourceService::RegisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId, const EnableParam& param) +{ + DHLOGI("DistributedCameraSourceService RegisterDistributedHardware devId: %s, dhId: %s, version: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), param.version.c_str()); + DCameraIndex camIndex(devId, dhId); + std::shared_ptr camDev = nullptr; + int32_t ret = DCAMERA_OK; + auto iter = camerasMap_.find(camIndex); + if (iter == camerasMap_.end()) { + DHLOGI("DistributedCameraSourceService RegisterDistributedHardware new dev devId: %s, dhId: %s, version: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), param.version.c_str()); + std::shared_ptr listener = std::make_shared(callbackProxy_); + camDev = std::make_shared(devId, dhId, listener); + if (camDev == nullptr) { + return DCAMERA_MEMORY_OPT_ERROR; + } + ret = camDev->InitDCameraSourceDev(); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSourceService RegisterDistributedHardware failed %d InitDev devId: %s, dhId: %s", + ret, GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + camerasMap_.emplace(camIndex, camDev); + } else { + DHLOGI("DistributedCameraSourceService RegisterDistributedHardware exist devId: %s, dhId: %s, version: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), param.version.c_str()); + camDev = iter->second; + } + + ret = camDev->RegisterDistributedHardware(devId, dhId, reqId, param.version, param.attrs); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSourceService RegisterDistributedHardware failed, ret: %d", ret); + camerasMap_.erase(camIndex); + } + DHLOGI("DistributedCameraSourceService RegisterDistributedHardware end devId: %s, dhId: %s, version: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str(), param.version.c_str()); + return ret; +} + +int32_t DistributedCameraSourceService::UnregisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId) +{ + DHLOGI("DistributedCameraSourceService UnregisterDistributedHardware devId: %s, dhId: %s", + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + DCameraIndex camIndex(devId, dhId); + auto iter = camerasMap_.find(camIndex); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSourceService UnregisterDistributedHardware not found device"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr camDev = iter->second; + int32_t ret = camDev->UnRegisterDistributedHardware(devId, dhId, reqId); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSourceService UnregisterDistributedHardware failed, ret: %d", ret); + } + return ret; +} + +int32_t DistributedCameraSourceService::DCameraNotify(const std::string& devId, const std::string& dhId, + std::string& events) +{ + DHLOGI("DistributedCameraSourceService DCameraNotify devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + DCameraIndex camIndex(devId, dhId); + auto iter = camerasMap_.find(camIndex); + if (iter == camerasMap_.end()) { + DHLOGE("DistributedCameraSourceService DCameraNotify not found device"); + return DCAMERA_NOT_FOUND; + } + + std::shared_ptr camDev = iter->second; + int32_t ret = camDev->DCameraNotify(events); + if (ret != DCAMERA_OK) { + DHLOGE("DistributedCameraSourceService DCameraNotify failed, ret: %d", ret); + } + return ret; +} + +int32_t DistributedCameraSourceService::LoadDCameraHDF() +{ + return DCAMERA_OK; +} + +int32_t DistributedCameraSourceService::UnLoadCameraHDF() +{ + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcamera/distributed_camera_source_stub.cpp b/services/cameraservice/sourceservice/src/distributedcamera/distributed_camera_source_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd45a32a81f555fe26e5302a2e2990fff45b66bb --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcamera/distributed_camera_source_stub.cpp @@ -0,0 +1,135 @@ +/* + * 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 "distributed_camera_source_stub.h" + +#include "dcamera_source_callback_proxy.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DistributedCameraSourceStub::DistributedCameraSourceStub() +{ + memberFuncMap_[INIT_SOURCE] = &DistributedCameraSourceStub::InitSourceInner; + memberFuncMap_[RELEASE_SOURCE] = &DistributedCameraSourceStub::ReleaseSourceInner; + memberFuncMap_[REGISTER_DISTRIBUTED_HARDWARE] = &DistributedCameraSourceStub::RegisterDistributedHardwareInner; + memberFuncMap_[UNREGISTER_DISTRIBUTED_HARDWARE] = &DistributedCameraSourceStub::UnregisterDistributedHardwareInner; + memberFuncMap_[CAMERA_NOTIFY] = &DistributedCameraSourceStub::DCameraNotifyInner; +} + +DistributedCameraSourceStub::~DistributedCameraSourceStub() +{} + +int32_t DistributedCameraSourceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DHLOGI("DistributedCameraSourceStub OnRemoteRequest code: %d", code); + std::u16string desc = DistributedCameraSourceStub::GetDescriptor(); + std::u16string remoteDesc = data.ReadInterfaceToken(); + if (desc != remoteDesc) { + DHLOGE("DistributedCameraSourceStub::OnRemoteRequest remoteDesc is invalid!"); + return ERR_INVALID_DATA; + } + auto itFunc = memberFuncMap_.find(code); + if (itFunc == memberFuncMap_.end()) { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + + auto memberFunc = itFunc->second; + return (this->*memberFunc)(data, reply); +} + +int32_t DistributedCameraSourceStub::InitSourceInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSourceStub InitSourceInner"); + int32_t ret = DCAMERA_OK; + do { + std::string params = data.ReadString(); + sptr remoteObj = data.ReadRemoteObject(); + if (remoteObj == nullptr) { + DHLOGE("DistributedCameraSourceStub initSource read object failed"); + ret = DCAMERA_BAD_VALUE; + break; + } + + sptr callbackProxy(new DCameraSourceCallbackProxy(remoteObj)); + if (callbackProxy == nullptr) { + DHLOGE("DistributedCameraSourceStub initSource get proxy failed"); + ret = DCAMERA_BAD_VALUE; + break; + } + + ret = InitSource(params, callbackProxy); + } while (0); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSourceStub::ReleaseSourceInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSourceStub ReleaseSourceInner"); + (void)data; + int32_t ret = ReleaseSource(); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSourceStub::RegisterDistributedHardwareInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSourceStub RegisterDistributedHardwareInner"); + int32_t ret = DCAMERA_OK; + do { + std::string devId = data.ReadString(); + std::string dhId = data.ReadString(); + std::string reqId = data.ReadString(); + EnableParam params; + params.version = data.ReadString(); + params.attrs = data.ReadString(); + ret = RegisterDistributedHardware(devId, dhId, reqId, params); + DHLOGI("DistributedCameraSourceStub RegisterDistributedHardware %d", ret); + } while (0); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSourceStub::UnregisterDistributedHardwareInner(MessageParcel &data, MessageParcel &reply) +{ + DHLOGI("DistributedCameraSourceStub UnregisterDistributedHardwareInner"); + int32_t ret = DCAMERA_OK; + do { + std::string devId = data.ReadString(); + std::string dhId = data.ReadString(); + std::string reqId = data.ReadString(); + ret = UnregisterDistributedHardware(devId, dhId, reqId); + } while (0); + reply.WriteInt32(ret); + return ret; +} + +int32_t DistributedCameraSourceStub::DCameraNotifyInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t ret = DCAMERA_OK; + do { + std::string devId = data.ReadString(); + std::string dhId = data.ReadString(); + std::string events = data.ReadString(); + ret = DCameraNotify(devId, dhId, events); + } while (0); + reply.WriteInt32(ret); + return ret; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_dev.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_dev.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59989035e8501898302720510e2b98970681907f --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_dev.cpp @@ -0,0 +1,538 @@ +/* + * 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 "dcamera_source_dev.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +#include "dcamera_channel_info_cmd.h" +#include "dcamera_info_cmd.h" +#include "dcamera_provider_callback_impl.h" +#include "dcamera_source_controller.h" +#include "dcamera_source_input.h" +#include "dcamera_utils_tools.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceDev::DCameraSourceDev(std::string devId, std::string dhId, + std::shared_ptr& stateLisener) : devId_(devId), dhId_(dhId), stateListener_(stateLisener) +{ + DHLOGI("DCameraSourceDev Construct devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + memberFuncMap_[DCAMERA_EVENT_REGIST] = &DCameraSourceDev::NotifyRegisterResult; + memberFuncMap_[DCAMERA_EVENT_UNREGIST] = &DCameraSourceDev::NotifyUnregisterResult; + memberFuncMap_[DCAMERA_EVENT_OPEN] = &DCameraSourceDev::NotifyHalResult; + memberFuncMap_[DCAMERA_EVENT_CLOSE] = &DCameraSourceDev::NotifyHalResult; + memberFuncMap_[DCAMERA_EVENT_CONFIG_STREAMS] = &DCameraSourceDev::NotifyHalResult; + memberFuncMap_[DCAMERA_EVENT_RELEASE_STREAMS] = &DCameraSourceDev::NotifyHalResult; + memberFuncMap_[DCAMERA_EVENT_START_CAPTURE] = &DCameraSourceDev::NotifyHalResult; + memberFuncMap_[DCAMERA_EVENT_STOP_CAPTURE] = &DCameraSourceDev::NotifyHalResult; + memberFuncMap_[DCAMERA_EVENT_UPDATE_SETTINGS] = &DCameraSourceDev::NotifyHalResult; + + eventResultMap_[DCAMERA_EVENT_OPEN] = DCAMERA_EVENT_OPEN_CHANNEL_ERROR; + eventResultMap_[DCAMERA_EVENT_CLOSE] = DCAMERA_EVENT_CLOSE_CHANNEL_ERROR; + eventResultMap_[DCAMERA_EVENT_CONFIG_STREAMS] = DCAMERA_EVENT_CONFIG_STREAMS_ERROR; + eventResultMap_[DCAMERA_EVENT_RELEASE_STREAMS] = DCAMERA_EVENT_RELEASE_STREAMS_ERROR; + eventResultMap_[DCAMERA_EVENT_START_CAPTURE] = DCAMERA_EVENT_START_CAPTURE_ERROR; + eventResultMap_[DCAMERA_EVENT_STOP_CAPTURE] = DCAMERA_EVENT_STOP_CAPTURE_ERROR; + eventResultMap_[DCAMERA_EVENT_UPDATE_SETTINGS] = DCAMERA_EVENT_UPDATE_SETTINGS_ERROR; +} + +DCameraSourceDev::~DCameraSourceDev() +{ + DHLOGI("DCameraSourceDev Delete devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); +} + +int32_t DCameraSourceDev::InitDCameraSourceDev() +{ + DHLOGI("DCameraSourceDev InitDCameraSourceDev devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + eventBus_ = std::make_shared(); + DCameraSourceEvent event(*this); + eventBus_->AddHandler(event.GetType(), *this); + auto cameraSourceDev = std::shared_ptr(shared_from_this()); + stateMachine_ = std::make_shared(cameraSourceDev); + stateMachine_->UpdateState(DCAMERA_STATE_INIT); + controller_ = std::make_shared(devId_, dhId_, stateMachine_, eventBus_); + input_ = std::make_shared(devId_, dhId_, eventBus_); + hdiCallback_ = new (std::nothrow) DCameraProviderCallbackImpl(devId_, dhId_, cameraSourceDev); + DHLOGI("DCameraSourceDev InitDCameraSourceDev end devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::RegisterDistributedHardware(const std::string& devId, const std::string& dhId, + const std::string& reqId, const std::string& ver, const std::string attrs) +{ + DHLOGI("DCameraSourceDev PostTask RegisterDistributedHardware devId %s dhId %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + version_ = ver; + DCameraIndex index(devId, dhId); + actualDevInfo_.insert(index); + + std::shared_ptr regParam = std::make_shared(devId, dhId, reqId, attrs); + DCameraSourceEvent event(*this, DCAMERA_EVENT_REGIST, regParam); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::UnRegisterDistributedHardware(const std::string devId, const std::string dhId, + const std::string reqId) +{ + DHLOGI("DCameraSourceDev PostTask UnRegisterDistributedHardware devId %s dhId %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + std::string param; + std::shared_ptr regParam = std::make_shared(devId, dhId, reqId, param); + DCameraSourceEvent event(*this, DCAMERA_EVENT_UNREGIST, regParam); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::DCameraNotify(std::string& eventStr) +{ + DHLOGI("DCameraSourceDev PostTask DCameraNotify devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + DCameraEventCmd cmd; + int32_t ret = cmd.Unmarshal(eventStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev DCameraNotify devId %s dhId %s marshal failed, ret: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), ret); + return ret; + } + + DCameraSourceEvent event(*this, DCAMERA_EVENT_NOFIFY, cmd.value_); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::OpenSession(DCameraIndex& camIndex) +{ + DHLOGI("DCameraSourceDev PostTask OpenSession devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + DCameraSourceEvent event(*this, DCAMERA_EVENT_OPEN, camIndex); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::CloseSession(DCameraIndex& camIndex) +{ + DHLOGI("DCameraSourceDev PostTask CloseSession devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + DCameraSourceEvent event(*this, DCAMERA_EVENT_CLOSE, camIndex); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ConfigStreams(const std::vector>& streamInfos) +{ + DHLOGI("DCameraSourceDev PostTask ConfigStreams devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + DCameraSourceEvent event(*this, DCAMERA_EVENT_CONFIG_STREAMS, streamInfos); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ReleaseStreams(const std::vector& streamIds) +{ + DHLOGI("DCameraSourceDev PostTask ReleaseStreams devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + DCameraSourceEvent event(*this, DCAMERA_EVENT_RELEASE_STREAMS, streamIds); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::StartCapture(const std::vector>& captureInfos) +{ + DHLOGI("DCameraSourceDev PostTask StartCapture devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + DCameraSourceEvent event(*this, DCAMERA_EVENT_START_CAPTURE, captureInfos); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::StopCapture() +{ + DHLOGI("DCameraSourceDev PostTask StopCapture devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + DCameraSourceEvent event(*this, DCAMERA_EVENT_STOP_CAPTURE); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::UpdateCameraSettings(const std::vector>& settings) +{ + DHLOGI("DCameraSourceDev PostTask UpdateCameraSettings devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + DCameraSourceEvent event(*this, DCAMERA_EVENT_UPDATE_SETTINGS, settings); + eventBus_->PostEvent(event); + return DCAMERA_OK; +} + +void DCameraSourceDev::OnEvent(DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceDev OnEvent devId %s dhId %s eventType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), event.GetEventType()); + int32_t ret = stateMachine_->Execute(event.GetEventType(), event); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev OnEvent failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + NotifyResult(event.GetEventType(), event, ret); +} + +int32_t DCameraSourceDev::ExecuteRegister(std::shared_ptr& param) +{ + DHLOGI("DCameraSourceDev Execute Register devId: %s dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + std::vector actualDevInfo; + actualDevInfo.assign(actualDevInfo_.begin(), actualDevInfo_.end()); + int32_t ret = controller_->Init(actualDevInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute Register controller init failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + ret = input_->Init(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute Register input init failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + controller_->UnInit(); + return ret; + } + + sptr camHdiProvider = IDCameraProvider::Get(); + if (camHdiProvider == nullptr) { + DHLOGI("ExecuteRegister camHdiProvider is nullptr devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + controller_->UnInit(); + input_->UnInit(); + return DCAMERA_BAD_OPERATE; + } + std::shared_ptr dhBase = std::make_shared(); + dhBase->deviceId_ = param->devId_; + dhBase->dhId_ = param->dhId_; + DCamRetCode retHdi = camHdiProvider->EnableDCameraDevice(dhBase, param->param_, hdiCallback_); + DHLOGI("DCameraSourceDev Execute Register register hal, ret: %d, devId: %s dhId: %s", retHdi, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + if (retHdi != SUCCESS) { + controller_->UnInit(); + input_->UnInit(); + return DCAMERA_REGIST_HAL_FAILED; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteUnRegister(std::shared_ptr& param) +{ + DHLOGI("DCameraSourceDev Execute UnRegister devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = controller_->UnInit(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute UnRegister controller uninit failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + + ret = input_->UnInit(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute UnRegister input uninit failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + + sptr camHdiProvider = IDCameraProvider::Get(); + if (camHdiProvider == nullptr) { + DHLOGI("ExecuteUnRegister camHdiProvider is nullptr devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + return DCAMERA_BAD_OPERATE; + } + + std::shared_ptr dhBase = std::make_shared(); + dhBase->deviceId_ = param->devId_; + dhBase->dhId_ = param->dhId_; + DCamRetCode retHdi = camHdiProvider->DisableDCameraDevice(dhBase); + DHLOGI("DCameraSourceDev Execute UnRegister unregister hal, ret: %d, devId: %s dhId: %s", retHdi, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + if (retHdi != SUCCESS) { + return DCAMERA_UNREGIST_HAL_FAILED; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteOpenCamera() +{ + DHLOGI("DCameraSourceDev Execute OpenCamera devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::shared_ptr openInfo = std::make_shared(); + int32_t ret = GetLocalDeviceNetworkId(openInfo->sourceDevId_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev getMyId failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + ret = controller_->OpenChannel(openInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute OpenCamera OpenChannel failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return DCAMERA_OPEN_CONFLICT; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteCloseCamera() +{ + DHLOGI("DCameraSourceDev Execute CloseCamera devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = input_->CloseChannel(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute CloseCamera input CloseChannel failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + ret = controller_->CloseChannel(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute CloseCamera controller CloseChannel failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteConfigStreams(std::vector>& streamInfos) +{ + DHLOGI("DCameraSourceDev Execute ConfigStreams devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = input_->ConfigStreams(streamInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute ConfigStreams ConfigStreams failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + std::shared_ptr chanInfo = std::make_shared(); + ret = GetLocalDeviceNetworkId(chanInfo->sourceDevId_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev getMyId failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + DCameraChannelDetail continueChInfo(CONTINUE_SESSION_FLAG, CONTINUOUS_FRAME); + DCameraChannelDetail snapShotChInfo(SNAP_SHOT_SESSION_FLAG, SNAPSHOT_FRAME); + chanInfo->detail_.push_back(continueChInfo); + chanInfo->detail_.push_back(snapShotChInfo); + + ret = controller_->ChannelNeg(chanInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev ChannelNeg failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + std::vector actualDevInfo; + actualDevInfo.assign(actualDevInfo_.begin(), actualDevInfo_.end()); + ret = input_->OpenChannel(actualDevInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev ChannelNeg OpenChannel failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteReleaseStreams(std::vector& streamIds, bool& isAllRelease) +{ + DHLOGI("DCameraSourceDev Execute ReleaseStreams devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = input_->ReleaseStreams(streamIds, isAllRelease); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute ReleaseStreams failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteReleaseAllStreams() +{ + DHLOGI("DCameraSourceDev Execute ReleaseAllStreams devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = input_->ReleaseAllStreams(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute ReleaseAllStreams failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteStartCapture(std::vector>& captureInfos) +{ + DHLOGI("DCameraSourceDev Execute StartCapture devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = input_->StartCapture(captureInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev input StartCapture failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + std::vector> captures; + for (auto iter = captureInfos.begin(); iter != captureInfos.end(); iter++) { + std::shared_ptr capture = std::make_shared(); + capture->width_ = (*iter)->width_; + capture->height_ = (*iter)->height_; + capture->format_ = (*iter)->format_; + capture->dataspace_ = (*iter)->dataspace_; + capture->isCapture_ = (*iter)->isCapture_; + capture->encodeType_ = (*iter)->encodeType_; + capture->streamType_ = (*iter)->type_; + DHLOGI("ExecuteStartCapture devId %s dhId %s settings size: %d w: %d h: %d fmt: %d isC: %d enc: %d streamT: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), (*iter)->captureSettings_.size(), + capture->width_, capture->height_, capture->format_, capture->isCapture_ ? 1 : 0, capture->encodeType_, + capture->streamType_); + for (auto settingIter = (*iter)->captureSettings_.begin(); settingIter != (*iter)->captureSettings_.end(); + settingIter++) { + std::shared_ptr setting = std::make_shared(); + setting->type_ = (*settingIter)->type_; + setting->value_ = (*settingIter)->value_; + capture->captureSettings_.push_back(setting); + } + captures.push_back(capture); + } + + ret = controller_->StartCapture(captures); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute StartCapture StartCapture failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + return ret; +} + +int32_t DCameraSourceDev::ExecuteStopCapture() +{ + DHLOGI("DCameraSourceDev Execute StopCapture devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = input_->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute StopCapture input StopCapture failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + ret = controller_->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute StopCapture controller StopCapture failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteUpdateSettings(std::vector>& settings) +{ + DHLOGI("DCameraSourceDev Execute UpdateSettings devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = input_->UpdateSettings(settings); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute UpdateSettings input UpdateSettings failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + ret = controller_->UpdateSettings(settings); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute UpdateSettings controller UpdateSettings failed, ret: %d, devId: %s dhId: %s", + ret, GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDev::ExecuteCameraEventNotify(std::shared_ptr& events) +{ + DHLOGI("DCameraSourceDev Execute CameraEventNotify devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = controller_->DCameraNotify(events); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceDev Execute CameraEventNotify DCameraNotify failed, ret: %d, devId: %s dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + return DCAMERA_OK; +} + +void DCameraSourceDev::NotifyResult(DCAMERA_EVENT eventType, DCameraSourceEvent& event, int32_t result) +{ + auto itFunc = memberFuncMap_.find(eventType); + if (itFunc == memberFuncMap_.end()) { + DHLOGE("Notify func map not find, execute %d notify, devId: %s dhId: %s", eventType, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return; + } + + auto memberFunc = itFunc->second; + (this->*memberFunc)(eventType, event, result); + return; +} + +void DCameraSourceDev::NotifyRegisterResult(DCAMERA_EVENT eventType, DCameraSourceEvent& event, int32_t result) +{ + std::string data = ""; + std::shared_ptr param; + int32_t ret = event.GetDCameraRegistParam(param); + if (ret != DCAMERA_OK) { + return; + } + + if (stateListener_ == nullptr) { + DHLOGE("DCameraSourceDev can not get listener"); + return; + } + stateListener_->OnRegisterNotify(param->devId_, param->dhId_, param->reqId_, result, data); +} + +void DCameraSourceDev::NotifyUnregisterResult(DCAMERA_EVENT eventType, DCameraSourceEvent& event, int32_t result) +{ + std::string data = ""; + std::shared_ptr param; + int32_t ret = event.GetDCameraRegistParam(param); + if (ret != DCAMERA_OK) { + return; + } + + if (stateListener_ == nullptr) { + DHLOGE("DCameraSourceDev can not get listener"); + return; + } + stateListener_->OnUnregisterNotify(param->devId_, param->dhId_, param->reqId_, result, data); +} + +void DCameraSourceDev::NotifyHalResult(DCAMERA_EVENT eventType, DCameraSourceEvent& event, int32_t result) +{ + DHLOGI("DCameraSourceDev NotifyHalResult eventType: %d, result: %d devId: %s dhId: %s", eventType, result, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + if (result == DCAMERA_OK) { + return; + } + + std::shared_ptr events = std::make_shared(); + events->eventType_ = DCAMERA_OPERATION; + auto iter = eventResultMap_.find(eventType); + if (iter == eventResultMap_.end()) { + return; + } + events->eventResult_ = iter->second; + ExecuteCameraEventNotify(events); + return; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_event.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fbcefe4cee1efc96c57b768dc6a7d494846b62fc --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_event.cpp @@ -0,0 +1,106 @@ +/* + * 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 "dcamera_source_event.h" + +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DCameraSourceEvent::GetDCameraIndex(DCameraIndex& index) +{ + auto indexPtr = std::get_if(&eventParam_); + if (indexPtr == nullptr) { + DHLOGE("DCameraSourceEvent can not get_if DCameraIndex"); + return DCAMERA_NOT_FOUND; + } + + index = *indexPtr; + return DCAMERA_OK; +} + +int32_t DCameraSourceEvent::GetDCameraRegistParam(std::shared_ptr& param) +{ + auto paramPtr = std::get_if>(&eventParam_); + if (paramPtr == nullptr) { + DHLOGE("DCameraSourceEvent can not get_if DCameraRegistParam"); + return DCAMERA_NOT_FOUND; + } + param = *paramPtr; + return DCAMERA_OK; +} + +int32_t DCameraSourceEvent::GetStreamInfos(std::vector>& streamInfos) +{ + auto streamInfosPtr = std::get_if>>(&eventParam_); + if (streamInfosPtr == nullptr) { + DHLOGE("DCameraSourceEvent can not get_if DCStreamInfo"); + return DCAMERA_NOT_FOUND; + } + streamInfos = std::move(*streamInfosPtr); + return DCAMERA_OK; +} + +int32_t DCameraSourceEvent::GetCaptureInfos(std::vector>& captureInfos) +{ + auto captureInfosPtr = std::get_if>>(&eventParam_); + if (captureInfosPtr == nullptr) { + DHLOGE("DCameraSourceEvent can not get_if DCCaptureInfo"); + return DCAMERA_NOT_FOUND; + } + captureInfos = std::move(*captureInfosPtr); + return DCAMERA_OK; +} + +int32_t DCameraSourceEvent::GetCameraSettings(std::vector>& settings) +{ + auto settingsPtr = std::get_if>>(&eventParam_); + if (settingsPtr == nullptr) { + DHLOGE("DCameraSourceEvent can not get_if DCameraSettings"); + return DCAMERA_NOT_FOUND; + } + settings = std::move(*settingsPtr); + return DCAMERA_OK; +} + +int32_t DCameraSourceEvent::GetStreamIds(std::vector& streamIds) +{ + auto streamIdsPtr = std::get_if>(&eventParam_); + if (streamIdsPtr == nullptr) { + DHLOGE("DCameraSourceEvent can not get_if streamIds"); + return DCAMERA_NOT_FOUND; + } + streamIds = std::move(*streamIdsPtr); + return DCAMERA_OK; +} + +int32_t DCameraSourceEvent::GetCameraEvent(std::shared_ptr& camEvent) +{ + auto camEventPtr = std::get_if>(&eventParam_); + if (camEventPtr == nullptr) { + DHLOGE("DCameraSourceEvent can not get_if camEventPtr"); + return DCAMERA_NOT_FOUND; + } + camEvent = *camEventPtr; + return DCAMERA_OK; +} + +DCAMERA_EVENT DCameraSourceEvent::GetEventType() +{ + return eventType_; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_service_ipc.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_service_ipc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b49c01449bd678ea66f91ef3cbdab909cfd38e05 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamera_source_service_ipc.cpp @@ -0,0 +1,191 @@ +/* + * 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 "dcamera_source_service_ipc.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceServiceIpc::DCameraSourceServiceIpc() : isInit_(false) +{ + DHLOGI("DCameraSourceServiceIpc Create"); +} + +DCameraSourceServiceIpc::~DCameraSourceServiceIpc() +{ + DHLOGI("DCameraSourceServiceIpc Delete"); + UnInit(); +} + +IMPLEMENT_SINGLE_INSTANCE(DCameraSourceServiceIpc); + +void DCameraSourceServiceIpc::Init() +{ + std::lock_guard autoLock(initDmsLock_); + DHLOGI("DCameraSourceServiceIpc Init Start"); + if (isInit_) { + DHLOGI("DCameraSourceServiceIpc has already init"); + return; + } + auto runner = AppExecFwk::EventRunner::Create("DCameraSourceServiceIpcHandler"); + serviceHandler_ = std::make_shared(runner); + sinkRemoteRecipient_ = new SinkRemoteRecipient(); + isInit_ = true; + DHLOGI("DCameraSourceServiceIpc Init End"); +} + +void DCameraSourceServiceIpc::UnInit() +{ + std::lock_guard autoLock(initDmsLock_); + DHLOGI("DCameraSourceServiceIpc UnInit Start"); + if (!isInit_) { + DHLOGI("DCameraSourceServiceIpc has already UnInit"); + return; + } + ClearSinkRemoteDhms(); + DHLOGI("DCameraSourceServiceIpc UnInit Start free servicehandle"); + serviceHandler_ = nullptr; + DHLOGI("DCameraSourceServiceIpc UnInit Start free recipient"); + sinkRemoteRecipient_ = nullptr; + isInit_ = false; + DHLOGI("DCameraSourceServiceIpc UnInit End"); +} + +sptr DCameraSourceServiceIpc::GetSinkRemoteDHMS(const std::string& deviceId) +{ + if (deviceId.empty()) { + DHLOGE("GetSinkRemoteDHMS deviceId is empty"); + return nullptr; + } + { + std::lock_guard autoLock(sinkRemoteDmsLock_); + auto iter = remoteSinks_.find(deviceId); + if (iter != remoteSinks_.end()) { + auto object = iter->second; + if (object != nullptr) { + DHLOGI("DCameraSourceServiceIpc GetSinkRemoteDHMS from cache devId: %s", + GetAnonyString(deviceId).c_str()); + return object; + } + } + } + DHLOGI("GetSinkRemoteDHMS remote deviceid is %s", GetAnonyString(deviceId).c_str()); + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + DHLOGE("GetSinkRemoteDHMS failed to connect to systemAbilityMgr!"); + return nullptr; + } + + auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_CAMERA_SINK_SA_ID, deviceId); + if (object == nullptr) { + DHLOGE("GetSinkRemoteDHMS failed get remote DHMS %s", GetAnonyString(deviceId).c_str()); + return nullptr; + } + int32_t ret = object->AddDeathRecipient(sinkRemoteRecipient_); + sptr remoteDmsObj = iface_cast(object); + if (remoteDmsObj == nullptr) { + DHLOGI("GetSinkRemoteDHMS failed, remoteDmsObj is null ret: %d", ret); + return nullptr; + } + { + std::lock_guard autoLock(sinkRemoteDmsLock_); + auto iter = remoteSinks_.find(deviceId); + if (iter != remoteSinks_.end()) { + iter->second->AsObject()->RemoveDeathRecipient(sinkRemoteRecipient_); + } + remoteSinks_[deviceId] = remoteDmsObj; + } + DHLOGI("GetSinkRemoteDHMS success, AddDeathRecipient ret: %d", ret); + return remoteDmsObj; +} + +void DCameraSourceServiceIpc::DeleteSinkRemoteDhms(const std::string& deviceId) +{ + DHLOGI("DeleteSinkRemoteDhms devId: %s", GetAnonyString(deviceId).c_str()); + std::lock_guard autoLock(sinkRemoteDmsLock_); + auto item = remoteSinks_.find(deviceId); + if (item == remoteSinks_.end()) { + DHLOGI("DeleteSinkRemoteDhms not found device: %s", GetAnonyString(deviceId).c_str()); + return; + } + + if (item->second != nullptr) { + item->second->AsObject()->RemoveDeathRecipient(sinkRemoteRecipient_); + } + remoteSinks_.erase(item); +} + +void DCameraSourceServiceIpc::ClearSinkRemoteDhms() +{ + DHLOGI("ClearSinkRemoteDhms Start"); + std::lock_guard autoLock(sinkRemoteDmsLock_); + for (auto iter = remoteSinks_.begin(); iter != remoteSinks_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->AsObject()->RemoveDeathRecipient(sinkRemoteRecipient_); + } + } + remoteSinks_.clear(); + DHLOGI("ClearSinkRemoteDhms end"); +} + +void DCameraSourceServiceIpc::SinkRemoteRecipient::OnRemoteDied(const wptr& remote) +{ + DHLOGI("SinkRemoteRecipient OnRemoteDied received died notify!"); + DCameraSourceServiceIpc::GetInstance().OnSinkRemoteDmsDied(remote); +} + +void DCameraSourceServiceIpc::OnSinkRemoteDmsDied(const wptr& remote) +{ + sptr diedRemoted = remote.promote(); + if (diedRemoted == nullptr) { + DHLOGE("OnSinkRemoteDmsDied promote failed!"); + return; + } + DHLOGI("OnSinkRemoteDmsDied delete diedRemoted"); + auto remoteDmsDiedFunc = [this, diedRemoted]() { + OnSinkRemoteDmsDied(diedRemoted); + }; + if (serviceHandler_ != nullptr) { + serviceHandler_->PostTask(remoteDmsDiedFunc); + } +} + +void DCameraSourceServiceIpc::OnSinkRemoteDmsDied(const sptr& remote) +{ + std::lock_guard autoLock(sinkRemoteDmsLock_); + auto iter = std::find_if(remoteSinks_.begin(), remoteSinks_.end(), [&]( + const std::pair> &item)->bool { + return item.second->AsObject() == remote; + }); + if (iter == remoteSinks_.end()) { + DHLOGI("OnSinkRemoteDmsDied not found remote object"); + return; + } + + DHLOGI("OnSinkRemoteDmsDied remote.devId: %s", GetAnonyString(iter->first).c_str()); + if (iter->second != nullptr) { + iter->second->AsObject()->RemoveDeathRecipient(sinkRemoteRecipient_); + } + remoteSinks_.erase(iter); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcameracontrol/dcamera_source_controller.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameracontrol/dcamera_source_controller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f993f583fb797ec498aa65b476556e6e1f7bf4a4 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameracontrol/dcamera_source_controller.cpp @@ -0,0 +1,472 @@ +/* + * 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 "dcamera_source_controller.h" + +#include +#include "json/json.h" + +#include "dcamera_capture_info_cmd.h" +#include "dcamera_channel_source_impl.h" +#include "dcamera_metadata_setting_cmd.h" +#include "dcamera_protocol.h" +#include "dcamera_source_controller_channel_listener.h" +#include "dcamera_source_service_ipc.h" +#include "dcamera_utils_tools.h" + +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" +#include "idistributed_camera_sink.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceController::DCameraSourceController(std::string devId, std::string dhId, + std::shared_ptr& stateMachine, std::shared_ptr& eventBus) + : devId_(devId), dhId_(dhId), stateMachine_(stateMachine), eventBus_(eventBus), + channelState_(DCAMERA_CHANNEL_STATE_DISCONNECTED) +{ + DHLOGI("DCameraSourceController create devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + isInit = false; +} + +DCameraSourceController::~DCameraSourceController() +{ + DHLOGI("DCameraSourceController delete devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + if (isInit) { + UnInit(); + } +} + +int32_t DCameraSourceController::StartCapture(std::vector>& captureInfos) +{ + if (indexs_.size() > DCAMERA_MAX_NUM) { + DHLOGE("DCameraSourceController StartCapture not support operate %d camera", indexs_.size()); + return DCAMERA_BAD_OPERATE; + } + + std::string dhId = indexs_.begin()->dhId_; + std::string devId = indexs_.begin()->devId_; + DHLOGI("DCameraSourceController StartCapture devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + DCameraCaptureInfoCmd cmd; + cmd.type_ = DCAMERA_PROTOCOL_TYPE_OPERATION; + cmd.dhId_ = dhId; + cmd.command_ = DCAMERA_PROTOCOL_CMD_CAPTURE; + cmd.value_.assign(captureInfos.begin(), captureInfos.end()); + std::string jsonStr; + int32_t ret = cmd.Marshal(jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController StartCapture Marshal faied %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + DHLOGI("DCameraSourceController StartCapture devId: %s, dhId: %s captureJson: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str(), jsonStr.c_str()); + std::shared_ptr buffer = std::make_shared(jsonStr.length() + 1); + ret = memcpy_s(buffer->Data(), buffer->Capacity(), (uint8_t *)jsonStr.c_str(), jsonStr.length()); + if (ret != EOK) { + DHLOGE("DCameraSourceController StartCapture memcpy_s failed %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + ret = channel_->SendData(buffer); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController StartCapture SendData failed %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + DHLOGI("DCameraSourceController StartCapture devId: %s, dhId: %s success", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSourceController::StopCapture() +{ + if (indexs_.size() > DCAMERA_MAX_NUM) { + DHLOGE("DCameraSourceController StopCapture not support operate %d camera", indexs_.size()); + return DCAMERA_BAD_OPERATE; + } + + std::string dhId = indexs_.begin()->dhId_; + std::string devId = indexs_.begin()->devId_; + DHLOGI("DCameraSourceController StopCapture devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + sptr camSinkSrv = DCameraSourceServiceIpc::GetInstance().GetSinkRemoteDHMS(devId); + if (camSinkSrv == nullptr) { + DHLOGE("DCameraSourceController StopCapture can not get service, devId: %s", GetAnonyString(devId).c_str()); + return DCAMERA_BAD_OPERATE; + } + int32_t ret = camSinkSrv->StopCapture(dhId); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController StopCapture failed: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return DCAMERA_BAD_OPERATE; + } + DHLOGI("DCameraSourceController StopCapture devId: %s, dhId: %s success", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSourceController::ChannelNeg(std::shared_ptr& info) +{ + if (indexs_.size() > DCAMERA_MAX_NUM) { + DHLOGE("DCameraSourceController ChannelNeg not support operate %d camera", indexs_.size()); + return DCAMERA_BAD_OPERATE; + } + + std::string dhId = indexs_.begin()->dhId_; + std::string devId = indexs_.begin()->devId_; + DHLOGI("DCameraSourceController ChannelNeg devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + sptr camSinkSrv = DCameraSourceServiceIpc::GetInstance().GetSinkRemoteDHMS(devId); + if (camSinkSrv == nullptr) { + DHLOGE("DCameraSourceController ChannelNeg can not get service, devId: %s", GetAnonyString(devId).c_str()); + return DCAMERA_BAD_OPERATE; + } + DCameraChannelInfoCmd cmd; + cmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE; + cmd.dhId_ = dhId; + cmd.command_ = DCAMERA_PROTOCOL_CMD_CHAN_NEG; + cmd.value_ = info; + std::string jsonStr; + int32_t ret = cmd.Marshal(jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController ChannelNeg Marshal failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + DHLOGD("DCameraSourceController ChannelNeg devId: %s, dhId: %s channelNegJson: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str(), jsonStr.c_str()); + ret = camSinkSrv->ChannelNeg(dhId, jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController ChannelNeg rpc failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + DHLOGD("DCameraSourceController ChannelNeg devId: %s, dhId: %s success", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSourceController::DCameraNotify(std::shared_ptr& events) +{ + sptr camHdiProvider = IDCameraProvider::Get(); + if (camHdiProvider == nullptr) { + DHLOGI("DCameraNotify camHdiProvider is nullptr devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + return DCAMERA_BAD_OPERATE; + } + std::shared_ptr dhBase = std::make_shared(); + dhBase->deviceId_ = devId_; + dhBase->dhId_ = dhId_; + std::shared_ptr hdiEvent = std::make_shared(); + hdiEvent->type_ = events->eventType_; + hdiEvent->result_ = events->eventResult_; + hdiEvent->content_ = events->eventContent_; + DCamRetCode retHdi = camHdiProvider->Notify(dhBase, hdiEvent); + DHLOGI("Nofify hal, ret: %d, devId: %s dhId: %s, type: %d, result: %d, content: %s", retHdi, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), events->eventType_, events->eventResult_, + events->eventContent_.c_str()); + if (retHdi != SUCCESS) { + return DCAMERA_BAD_OPERATE; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceController::UpdateSettings(std::vector>& settings) +{ + if (indexs_.size() > DCAMERA_MAX_NUM) { + DHLOGE("DCameraSourceController UpdateSettings not support operate %d camera", indexs_.size()); + return DCAMERA_BAD_OPERATE; + } + + std::string dhId = indexs_.begin()->dhId_; + std::string devId = indexs_.begin()->devId_; + DHLOGI("DCameraSourceController UpdateSettings devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + DCameraMetadataSettingCmd cmd; + cmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE; + cmd.dhId_ = dhId; + cmd.command_ = DCAMERA_PROTOCOL_CMD_UPDATE_METADATA; + cmd.value_.assign(settings.begin(), settings.end()); + std::string jsonStr; + int32_t ret = cmd.Marshal(jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController UpdateSettings Marshal faied %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + std::shared_ptr buffer = std::make_shared(jsonStr.length() + 1); + ret = memcpy_s(buffer->Data(), buffer->Capacity(), (uint8_t *)jsonStr.c_str(), jsonStr.length()); + if (ret != EOK) { + DHLOGE("DCameraSourceController UpdateSettings memcpy_s failed %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + ret = channel_->SendData(buffer); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController UpdateSettings SendData failed %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + DHLOGI("DCameraSourceController UpdateSettings devId: %s, dhId: %s success", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSourceController::GetCameraInfo(std::shared_ptr& camInfo) +{ + if (indexs_.size() > DCAMERA_MAX_NUM) { + DHLOGE("DCameraSourceController GetCameraInfo not support operate %d camera", indexs_.size()); + return DCAMERA_BAD_OPERATE; + } + + std::string dhId = indexs_.begin()->dhId_; + std::string devId = indexs_.begin()->devId_; + DHLOGI("DCameraSourceController GetCameraInfo devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + sptr camSinkSrv = DCameraSourceServiceIpc::GetInstance().GetSinkRemoteDHMS(devId); + if (camSinkSrv == nullptr) { + DHLOGE("DCameraSourceController GetCameraInfo can not get service, devId: %s", GetAnonyString(devId).c_str()); + return DCAMERA_BAD_OPERATE; + } + std::string camInfoJson; + int32_t ret = camSinkSrv->GetCameraInfo(dhId, camInfoJson); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController GetCameraInfo GetCameraInfo failed: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + return ret; + } + DCameraInfoCmd cmd; + ret = cmd.Unmarshal(camInfoJson); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController GetCameraInfo DCameraInfoCmd Unmarshal failed: %d", ret); + return ret; + } + camInfo = cmd.value_; + return DCAMERA_OK; +} + +int32_t DCameraSourceController::OpenChannel(std::shared_ptr& openInfo) +{ + if (indexs_.size() > DCAMERA_MAX_NUM) { + DHLOGE("DCameraSourceController OpenChannel not support operate %d camera", indexs_.size()); + return DCAMERA_BAD_OPERATE; + } + std::string dhId = indexs_.begin()->dhId_; + std::string devId = indexs_.begin()->devId_; + DHLOGI("DCameraSourceController OpenChannel devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + sptr camSinkSrv = DCameraSourceServiceIpc::GetInstance().GetSinkRemoteDHMS(devId); + if (camSinkSrv == nullptr) { + DHLOGE("DCameraSourceController can not get service, devId: %s", GetAnonyString(devId).c_str()); + return DCAMERA_BAD_OPERATE; + } + + DCameraOpenInfoCmd cmd; + cmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE; + cmd.dhId_ = dhId; + cmd.command_ = DCAMERA_PROTOCOL_CMD_OPEN_CHANNEL; + cmd.value_ = openInfo; + std::string jsonStr; + int32_t ret = cmd.Marshal(jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController Marshal OpenInfo failed %d", ret); + return ret; + } + DHLOGD("DCameraSourceController OpenChannel devId: %s, dhId: %s openJson: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str(), jsonStr.c_str()); + ret = camSinkSrv->OpenChannel(dhId, jsonStr); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController SA OpenChannel failed %d", ret); + return ret; + } + DHLOGD("DCameraSourceController OpenChannel devId: %s, dhId: %s success", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str(), jsonStr.c_str()); + + std::vector indexs; + indexs.push_back(DCameraIndex(devId, dhId)); + ret = channel_->CreateSession(indexs, SESSION_FLAG, DCAMERA_SESSION_MODE_CTRL, listener_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController CreateSession failed %d", ret); + return ret; + } + ret = channel_->OpenSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController OpenChannel OpenChannel failed %d", ret); + return ret; + } + + return DCAMERA_OK; +} + +int32_t DCameraSourceController::CloseChannel() +{ + if (indexs_.size() > DCAMERA_MAX_NUM) { + DHLOGE("DCameraSourceController CloseChannel not support operate %d camera", indexs_.size()); + return DCAMERA_BAD_OPERATE; + } + + std::string dhId = indexs_.begin()->dhId_; + std::string devId = indexs_.begin()->devId_; + DHLOGI("DCameraSourceController CloseChannel devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + int32_t ret = channel_->CloseSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController CloseChannel CloseSession failed %d", ret); + } + DHLOGI("DCameraSourceController CloseChannel devId: %s, dhId: %s success", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + channelState_ = DCAMERA_CHANNEL_STATE_DISCONNECTED; + ret = channel_->ReleaseSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController CloseChannel ReleaseSession failed %d", ret); + } + sptr camSinkSrv = DCameraSourceServiceIpc::GetInstance().GetSinkRemoteDHMS(devId); + if (camSinkSrv != nullptr) { + ret = camSinkSrv->CloseChannel(dhId); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceController SA CloseChannel failed %d", ret); + } + DCameraSourceServiceIpc::GetInstance().DeleteSinkRemoteDhms(devId); + } + return ret; +} + +int32_t DCameraSourceController::Init(std::vector& indexs) +{ + DHLOGI("DCameraSourceController Init"); + if (indexs.size() > DCAMERA_MAX_NUM) { + DHLOGE("DCameraSourceController init error"); + return DCAMERA_INIT_ERR; + } + indexs_.assign(indexs.begin(), indexs.end()); + std::string dhId = indexs_.begin()->dhId_; + std::string devId = indexs_.begin()->devId_; + auto controller = std::shared_ptr(shared_from_this()); + listener_ = std::make_shared(controller); + channel_ = std::make_shared(); + DHLOGI("DCameraSourceController Init GetProvider end devId: %s, dhId: %s", GetAnonyString(devId).c_str(), + GetAnonyString(dhId).c_str()); + isInit = true; + return DCAMERA_OK; +} + +int32_t DCameraSourceController::UnInit() +{ + DHLOGI("DCameraSourceController UnInit"); + indexs_.clear(); + isInit = false; + return DCAMERA_OK; +} + +void DCameraSourceController::OnSessionState(int32_t state) +{ + DHLOGI("DCameraSourceController OnSessionState state %d", state); + channelState_ = state; + switch (state) { + case DCAMERA_CHANNEL_STATE_CONNECTED: { + stateMachine_->UpdateState(DCAMERA_STATE_OPENED); + std::shared_ptr camEvent = std::make_shared(); + camEvent->eventType_ = DCAMERA_MESSAGE; + camEvent->eventResult_ = DCAMERA_EVENT_CHANNEL_CONNECTED; + DCameraSourceEvent event(*this, DCAMERA_EVENT_NOFIFY, camEvent); + eventBus_->PostEvent(event); + break; + } + case DCAMERA_CHANNEL_STATE_DISCONNECTED: { + DHLOGI("DCameraSourceDev PostTask Controller CloseSession OnClose devId %s dhId %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + DCameraIndex camIndex(devId_, dhId_); + DCameraSourceEvent event(*this, DCAMERA_EVENT_CLOSE, camIndex); + eventBus_->PostEvent(event); + std::shared_ptr camEvent = std::make_shared(); + camEvent->eventType_ = DCAMERA_MESSAGE; + camEvent->eventResult_ = DCAMERA_EVENT_CHANNEL_DISCONNECTED; + DCameraSourceEvent eventNotify(*this, DCAMERA_EVENT_NOFIFY, camEvent); + eventBus_->PostEvent(eventNotify); + break; + } + default: { + break; + } + } +} + +void DCameraSourceController::OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) +{ + DHLOGI("DCameraSourceController OnSessionError devId: %s, dhId: %s, eventType: %d, eventReason: %d, detail %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), eventType, eventReason, detail.c_str()); + return; +} + +void DCameraSourceController::OnDataReceived(std::vector>& buffers) +{ + if (buffers.empty()) { + DHLOGI("DCameraSourceController OnDataReceived empty, devId: %s, dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + return; + } + std::shared_ptr buffer = *(buffers.begin()); + std::string jsonStr((char *)buffer->Data()); + JSONCPP_STRING errs; + Json::CharReaderBuilder readerBuilder; + Json::Value rootValue; + + std::unique_ptr const jsonReader(readerBuilder.newCharReader()); + if (!jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &rootValue, &errs) || + !rootValue.isObject()) { + return; + } + + if (!rootValue.isMember("Command") || !rootValue["Command"].isString()) { + return; + } + std::string command = rootValue["Command"].asString(); + if (command == DCAMERA_PROTOCOL_CMD_METADATA_RESULT) { + HandleMetaDataResult(jsonStr); + } + return; +} + +void DCameraSourceController::HandleMetaDataResult(std::string& jsonStr) +{ + sptr camHdiProvider = IDCameraProvider::Get(); + if (camHdiProvider == nullptr) { + DHLOGI("DCameraSourceController HandleMetaDataResult camHdiProvider is null, devId: %s, dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return; + } + DCameraMetadataSettingCmd cmd; + int32_t ret = cmd.Unmarshal(jsonStr); + if (ret != DCAMERA_OK) { + DHLOGI("DCameraSourceController HandleMetaDataResult failed, ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return; + } + std::shared_ptr dhBase = std::make_shared(); + dhBase->deviceId_ = devId_; + dhBase->dhId_ = dhId_; + for (auto iter = cmd.value_.begin(); iter != cmd.value_.end(); iter++) { + DCamRetCode retHdi = camHdiProvider->OnSettingsResult(dhBase, (*iter)); + DHLOGI("OnSettingsResult hal, ret: %d, devId: %s dhId: %s, type: %d, result: %d, content: %s", retHdi, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcameracontrol/dcamera_source_controller_channel_listener.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameracontrol/dcamera_source_controller_channel_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0792381b70b0bfc268a9eb3422619da970ce899 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameracontrol/dcamera_source_controller_channel_listener.cpp @@ -0,0 +1,67 @@ +/* + * 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 "dcamera_source_controller_channel_listener.h" + +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +#include "dcamera_source_controller.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceControllerChannelListener::DCameraSourceControllerChannelListener( + std::shared_ptr& controller) : controller_(controller) +{ +} + +DCameraSourceControllerChannelListener::~DCameraSourceControllerChannelListener() +{ +} + +void DCameraSourceControllerChannelListener::OnSessionState(int32_t state) +{ + std::shared_ptr controller = controller_.lock(); + if (controller == nullptr) { + DHLOGE("DCameraSourceController OnSessionState not found controller"); + return; + } + + controller->OnSessionState(state); +} + +void DCameraSourceControllerChannelListener::OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) +{ + std::shared_ptr controller = controller_.lock(); + if (controller == nullptr) { + DHLOGE("DCameraSourceController OnSessionError not found controller"); + return; + } + + controller->OnSessionError(eventType, eventReason, detail); +} + +void DCameraSourceControllerChannelListener::OnDataReceived(std::vector>& buffers) +{ + std::shared_ptr controller = controller_.lock(); + if (controller == nullptr) { + DHLOGE("DCameraSourceController OnDataReceived not found controller"); + return; + } + + controller->OnDataReceived(buffers); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_data_process.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_data_process.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c383f37dc121cb86a8cab6a625d0089614139494 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_data_process.cpp @@ -0,0 +1,165 @@ +/* + * 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 "dcamera_source_data_process.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceDataProcess::DCameraSourceDataProcess(std::string devId, std::string dhId, DCStreamType streamType) + : devId_(devId), dhId_(dhId), streamType_(streamType) +{ + DHLOGI("DCameraSourceDataProcess Constructor devId %s dhId %s streamType %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamType_); +} + +DCameraSourceDataProcess::~DCameraSourceDataProcess() +{ + DHLOGI("DCameraSourceDataProcess Destructor devId %s dhId %s streamType %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamType_); + streamProcess_.clear(); + streamIds_.clear(); +} + +int32_t DCameraSourceDataProcess::FeedStream(std::vector>& buffers) +{ + if (buffers.size() > DCAMERA_MAX_NUM) { + DHLOGI("DCameraSourceDataProcess FeedStream devId %s dhId %s size: %d over flow", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), buffers.size()); + return DCAMERA_BAD_VALUE; + } + + auto buffer = *(buffers.begin()); + DHLOGD("DCameraSourceDataProcess FeedStream devId %s dhId %s streamType %d streamSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, buffer->Size()); + for (auto iter = streamProcess_.begin(); iter != streamProcess_.end(); iter++) { + (*iter)->FeedStream(buffer); + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDataProcess::ConfigStreams(std::vector>& streamInfos) +{ + DHLOGI("DCameraSourceDataProcess ConfigStreams devId %s dhId %s streamType %d size %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamInfos.size()); + if (streamInfos.empty()) { + DHLOGI("DCameraSourceDataProcess ConfigStreams is empty"); + return DCAMERA_OK; + } + std::map> streamConfigs; + for (auto iter = streamInfos.begin(); iter != streamInfos.end(); iter++) { + std::shared_ptr streamInfo = *iter; + DCameraStreamConfig streamConfig(streamInfo->width_, streamInfo->height_, streamInfo->format_, + streamInfo->dataspace_, streamInfo->encodeType_, streamInfo->type_); + DHLOGI("DCameraSourceDataProcess ConfigStreams devId %s dhId %s, streamId: %d info: width: %d, height: %d," + + "format: %d, dataspace: %d, encodeType: %d streamType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamInfo->streamId_, streamConfig.width_, streamConfig.height_, + streamConfig.format_, streamConfig.dataspace_, streamConfig.encodeType_, streamConfig.type_); + if (streamConfigs.find(streamConfig) == streamConfigs.end()) { + std::set streamIdSet; + streamConfigs.emplace(streamConfig, streamIdSet); + } + streamConfigs[streamConfig].insert(streamInfo->streamId_); + streamIds_.insert(streamInfo->streamId_); + } + + for (auto iter = streamConfigs.begin(); iter != streamConfigs.end(); iter++) { + DHLOGI("DCameraSourceDataProcess ConfigStreams devId %s dhId %s, info: width: %d, height: %d, format: %d," + + "dataspace: %d, encodeType: %d streamType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), iter->first.width_, iter->first.height_, iter->first.format_, + iter->first.dataspace_, iter->first.encodeType_, iter->first.type_); + + std::shared_ptr streamProcess = + std::make_shared(devId_, dhId_, streamType_); + std::shared_ptr streamConfig = + std::make_shared(iter->first.width_, iter->first.height_, iter->first.format_, + iter->first.dataspace_, iter->first.encodeType_, iter->first.type_); + streamProcess->ConfigStreams(streamConfig, iter->second); + + streamProcess_.push_back(streamProcess); + } + + return DCAMERA_OK; +} + +int32_t DCameraSourceDataProcess::ReleaseStreams(std::vector& streamIds) +{ + DHLOGI("DCameraSourceDataProcess ReleaseStreams devId %s dhId %s streamType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamType_); + std::set streamIdSet(streamIds.begin(), streamIds.end()); + auto iter = streamProcess_.begin(); + while (iter != streamProcess_.end()) { + (*iter)->ReleaseStreams(streamIdSet); + std::set processStreamIds; + (*iter)->GetAllStreamIds(processStreamIds); + if (processStreamIds.empty()) { + iter = streamProcess_.erase(iter); + } else { + iter++; + } + } + + std::string strStreams; + for (auto iterSet = streamIdSet.begin(); iterSet != streamIdSet.end(); iterSet++) { + strStreams += (std::to_string(*iterSet) + std::string(" ")); + streamIds_.erase(*iterSet); + } + DHLOGI("DCameraSourceDataProcess ReleaseStreams devId %s dhId %s streamType: %d streamProcessSize: %d streams: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamProcess_.size(), + strStreams.c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSourceDataProcess::StartCapture(std::shared_ptr& captureInfo) +{ + DHLOGI("DCameraSourceDataProcess StartCapture devId %s dhId %s, info: width: %d, height: %d, format: %d,\ + dataspace: %d, encodeType: %d streamType: %d", GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), + captureInfo->width_, captureInfo->height_, captureInfo->format_, captureInfo->dataspace_, + captureInfo->encodeType_, captureInfo->type_); + + std::shared_ptr streamConfig = + std::make_shared(captureInfo->width_, captureInfo->height_, captureInfo->format_, + captureInfo->dataspace_, captureInfo->encodeType_, captureInfo->type_); + std::set streamIds(captureInfo->streamIds_.begin(), captureInfo->streamIds_.end()); + for (auto iterSet = streamIds.begin(); iterSet != streamIds.end(); iterSet++) { + DHLOGI("DCameraSourceDataProcess StartCapture devId %s dhId %s StartCapture id: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), *iterSet); + } + for (auto iter = streamProcess_.begin(); iter != streamProcess_.end(); iter++) { + (*iter)->StartCapture(streamConfig, streamIds); + } + return DCAMERA_OK; +} + +int32_t DCameraSourceDataProcess::StopCapture() +{ + DHLOGI("DCameraSourceDataProcess StopCapture devId %s dhId %s streamType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamType_); + for (auto iter = streamProcess_.begin(); iter != streamProcess_.end(); iter++) { + (*iter)->StopCapture(); + } + return DCAMERA_OK; +} + +void DCameraSourceDataProcess::GetAllStreamIds(std::vector& streamIds) +{ + streamIds.assign(streamIds_.begin(), streamIds_.end()); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_input.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_input.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93d97013d6187e2aa106ccd05dbf468784995429 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_input.cpp @@ -0,0 +1,377 @@ +/* + * 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 "dcamera_source_input.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +#include "dcamera_channel_source_impl.h" +#include "dcamera_source_data_process.h" +#include "dcamera_source_event.h" +#include "dcamera_source_input_channel_listener.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceInput::DCameraSourceInput(std::string devId, std::string dhId, std::shared_ptr& eventBus) + : devId_(devId), dhId_(dhId), eventBus_(eventBus), isInit(false), isCapture_(false) +{ + DHLOGI("DCameraSourceInput Constructor devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); +} + +DCameraSourceInput::~DCameraSourceInput() +{ + DHLOGI("DCameraSourceInput Destructor devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + if (isInit) { + UnInit(); + } +} + +int32_t DCameraSourceInput::ConfigStreams(std::vector>& streamInfos) +{ + DHLOGI("DCameraSourceInput ConfigStreams devId %s dhId %s, size: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamInfos.size()); + int32_t ret = ReleaseAllStreams(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput ConfigStreams ReleaseAllStreams failed %d devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + if (streamInfos.empty()) { + return DCAMERA_OK; + } + + std::vector> snapStreams; + std::vector> continueStreams; + for (auto iter = streamInfos.begin(); iter != streamInfos.end(); iter++) { + std::shared_ptr streamInfo = *iter; + DHLOGI("DCameraSourceInput ConfigStreams devId: %s, dhId: %s, streamId: %d, width: %d, height: %d," + + "format: %d, dataspace: %d, encodeType:%d streamType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamInfo->streamId_, streamInfo->width_, streamInfo->height_, + streamInfo->format_, streamInfo->dataspace_, streamInfo->encodeType_, streamInfo->type_); + switch (streamInfo->type_) { + case CONTINUOUS_FRAME: { + continueStreams.push_back(streamInfo); + break; + } + case SNAPSHOT_FRAME: { + snapStreams.push_back(streamInfo); + break; + } + default: + break; + } + } + + do { + ret = dataProcess_[CONTINUOUS_FRAME]->ConfigStreams(continueStreams); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput ConfigStreams continue failed %d devId %s dhId %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + break; + } + ret = dataProcess_[SNAPSHOT_FRAME]->ConfigStreams(snapStreams); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput ConfigStreams snapshot failed %d devId %s dhId %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + break; + } + } while (0); + + if (ret != DCAMERA_OK) { + ReleaseAllStreams(); + } + return ret; +} + +int32_t DCameraSourceInput::ReleaseStreams(std::vector& streamIds, bool& isAllRelease) +{ + DHLOGI("DCameraSourceInput ReleaseStreams devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = dataProcess_[CONTINUOUS_FRAME]->ReleaseStreams(streamIds); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput ReleaseStreams continue stream ReleaseStreams ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + ret = dataProcess_[SNAPSHOT_FRAME]->ReleaseStreams(streamIds); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput ReleaseStreams snapshot stream ReleaseStreams ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + std::vector continueStreamIds; + dataProcess_[CONTINUOUS_FRAME]->GetAllStreamIds(continueStreamIds); + std::vector snapStreamIds; + dataProcess_[CONTINUOUS_FRAME]->GetAllStreamIds(snapStreamIds); + if (continueStreamIds.empty() && snapStreamIds.empty()) { + isAllRelease = true; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceInput::StartCapture(std::vector>& captureInfos) +{ + DHLOGI("DCameraSourceInput StartCapture devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + int32_t ret = DCAMERA_OK; + for (auto iter = captureInfos.begin(); iter != captureInfos.end(); iter++) { + for (auto iterSet = (*iter)->streamIds_.begin(); iterSet != (*iter)->streamIds_.end(); iterSet++) { + DHLOGI("DCameraSourceInput StartCapture devId %s dhId %s StartCapture id: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), *iterSet); + } + DHLOGI("DCameraSourceInput StartCapture Inner devId %s dhId %s streamType: %d idSize: %d isCap: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), (*iter)->type_, (*iter)->streamIds_.size(), + (*iter)->isCapture_ ? 1 : 0); + ret = dataProcess_[(*iter)->type_]->StartCapture(*iter); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput StartCapture ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + } + std::lock_guard autoLock(inputMutex_); + isCapture_ = true; + return DCAMERA_OK; +} + +int32_t DCameraSourceInput::StopCapture() +{ + DHLOGI("DCameraSourceInput StopCapture devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::lock_guard autoLock(inputMutex_); + isCapture_ = false; + int32_t ret = dataProcess_[CONTINUOUS_FRAME]->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput StopCapture continue ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + ret = dataProcess_[SNAPSHOT_FRAME]->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput StopCapture snapshot ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceInput::OpenChannel(std::vector& indexs) +{ + DHLOGI("DCameraSourceInput OpenChannel devId %s dhId %s continue state: %d, snapshot state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), channelState_[CONTINUOUS_FRAME], + channelState_[SNAPSHOT_FRAME]); + int32_t ret = DCAMERA_OK; + if (channelState_[CONTINUOUS_FRAME] == DCAMERA_CHANNEL_STATE_DISCONNECTED) { + ret = channels_[CONTINUOUS_FRAME]->CreateSession(indexs, CONTINUE_SESSION_FLAG, DCAMERA_SESSION_MODE_VIDEO, + listeners_[CONTINUOUS_FRAME]); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput CreateSession continue failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + ret = channels_[CONTINUOUS_FRAME]->OpenSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput OpenChannel continue stream failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + } + + if (channelState_[SNAPSHOT_FRAME] == DCAMERA_CHANNEL_STATE_DISCONNECTED) { + ret = channels_[SNAPSHOT_FRAME]->CreateSession(indexs, SNAP_SHOT_SESSION_FLAG, DCAMERA_SESSION_MODE_JPEG, + listeners_[SNAPSHOT_FRAME]); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput Init CreateSession snapshot failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + ret = channels_[SNAPSHOT_FRAME]->OpenSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput OpenChannel snapshot stream failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + } + return DCAMERA_OK; +} + +int32_t DCameraSourceInput::CloseChannel() +{ + DHLOGI("DCameraSourceInput CloseChannel devId %s dhId %s continue state: %d, snapshot state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), channelState_[CONTINUOUS_FRAME], + channelState_[SNAPSHOT_FRAME]); + int32_t ret = DCAMERA_OK; + if (channelState_[CONTINUOUS_FRAME] != DCAMERA_CHANNEL_STATE_DISCONNECTED) { + ret = channels_[CONTINUOUS_FRAME]->CloseSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput CloseChannel continue stream failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + channelState_[CONTINUOUS_FRAME] = DCAMERA_CHANNEL_STATE_DISCONNECTED; + + ret = channels_[CONTINUOUS_FRAME]->ReleaseSession(); + if (ret != DCAMERA_OK) { + DHLOGI("DCameraSourceInput release continue session failed: %d devId %s dhId %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + } + + if (channelState_[SNAPSHOT_FRAME] != DCAMERA_CHANNEL_STATE_DISCONNECTED) { + ret = channels_[SNAPSHOT_FRAME]->CloseSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput CloseChannel snapshot stream failed ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + channelState_[SNAPSHOT_FRAME] = DCAMERA_CHANNEL_STATE_DISCONNECTED; + + ret = channels_[SNAPSHOT_FRAME]->ReleaseSession(); + if (ret != DCAMERA_OK) { + DHLOGI("DCameraSourceInput release snapshot session failed: %d devId %s dhId %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } + } + return DCAMERA_OK; +} + +int32_t DCameraSourceInput::Init() +{ + DHLOGI("DCameraSourceInput Init devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + auto input = std::shared_ptr(shared_from_this()); + std::shared_ptr conDataProcess = std::make_shared(devId_, dhId_, + CONTINUOUS_FRAME); + std::shared_ptr continueCh = std::make_shared(); + std::shared_ptr conListener = + std::make_shared(input, CONTINUOUS_FRAME); + channels_.emplace(CONTINUOUS_FRAME, continueCh); + listeners_.emplace(CONTINUOUS_FRAME, conListener); + dataProcess_.emplace(CONTINUOUS_FRAME, conDataProcess); + channelState_.emplace(CONTINUOUS_FRAME, DCAMERA_CHANNEL_STATE_DISCONNECTED); + + std::shared_ptr snapDataProcess = std::make_shared(devId_, + dhId_, SNAPSHOT_FRAME); + std::shared_ptr snapShotCh = std::make_shared(); + std::shared_ptr snapListener = + std::make_shared(input, SNAPSHOT_FRAME); + channels_.emplace(SNAPSHOT_FRAME, snapShotCh); + listeners_.emplace(SNAPSHOT_FRAME, snapListener); + dataProcess_.emplace(SNAPSHOT_FRAME, snapDataProcess); + channelState_.emplace(SNAPSHOT_FRAME, DCAMERA_CHANNEL_STATE_DISCONNECTED); + isInit = true; + DHLOGI("DCameraSourceInput Init devId end %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + return DCAMERA_OK; +} + +int32_t DCameraSourceInput::UnInit() +{ + DHLOGI("DCameraSourceInput UnInit devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + channels_.clear(); + listeners_.clear(); + dataProcess_.clear(); + channelState_.clear(); + isInit = false; + return DCAMERA_OK; +} + +int32_t DCameraSourceInput::UpdateSettings(std::vector>& settings) +{ + return DCAMERA_OK; +} + +void DCameraSourceInput::OnSessionState(DCStreamType streamType, int32_t state) +{ + DHLOGI("DCameraSourceInput OnSessionState devId: %s, dhId: %s, streamType: %d, state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType, state); + channelState_[streamType] = (DCameraChannelState)state; + switch (state) { + case DCAMERA_CHANNEL_STATE_DISCONNECTED: { + DHLOGI("DCameraSourceDev PostTask CloseSession Input OnClose devId %s dhId %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + DCameraIndex camIndex(devId_, dhId_); + DCameraSourceEvent event(*this, DCAMERA_EVENT_CLOSE, camIndex); + eventBus_->PostEvent(event); + std::shared_ptr camEvent = std::make_shared(); + camEvent->eventType_ = DCAMERA_MESSAGE; + camEvent->eventResult_ = DCAMERA_EVENT_CHANNEL_DISCONNECTED; + DCameraSourceEvent srcEvent(*this, DCAMERA_EVENT_NOFIFY, camEvent); + eventBus_->PostEvent(srcEvent); + break; + } + default: { + DHLOGI("DCameraSourceInput OnSessionState state %d", state); + break; + } + } +} + +void DCameraSourceInput::OnSessionError(DCStreamType streamType, int32_t eventType, int32_t eventReason, + std::string detail) +{ + DHLOGI("DCameraSourceInput OnSessionError devId: %s, dhId: %s, eventType: %d, eventReason: %d, detail %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), eventType, eventReason, detail.c_str()); +} + +void DCameraSourceInput::OnDataReceived(DCStreamType streamType, std::vector>& buffers) +{ + std::lock_guard autoLock(inputMutex_); + if (!isCapture_) { + DHLOGE("DCameraSourceInput OnDataReceived FeedStream %d stream capture stop, devId: %s, dhId: %s", streamType, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return; + } + int32_t ret = dataProcess_[streamType]->FeedStream(buffers); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput OnDataReceived FeedStream %d stream failed ret: %d, devId: %s, dhId: %s", streamType, + ret, GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + } +} + +int32_t DCameraSourceInput::ReleaseAllStreams() +{ + DHLOGI("DCameraSourceInput ReleaseAllStreams devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::vector continueStreamIds; + dataProcess_[CONTINUOUS_FRAME]->GetAllStreamIds(continueStreamIds); + int32_t ret = dataProcess_[CONTINUOUS_FRAME]->ReleaseStreams(continueStreamIds); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput ReleaseAllStreams continue stream ReleaseStreams ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + + std::vector snapStreamIds; + dataProcess_[SNAPSHOT_FRAME]->GetAllStreamIds(snapStreamIds); + ret = dataProcess_[SNAPSHOT_FRAME]->ReleaseStreams(snapStreamIds); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInput ReleaseAllStreams snapshot stream ReleaseStreams ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return ret; + } + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_input_channel_listener.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_input_channel_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3bbcf8869a81de8be45aaeb225ab5ea7948d2a7f --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_source_input_channel_listener.cpp @@ -0,0 +1,67 @@ +/* + * 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 "dcamera_source_input_channel_listener.h" + +#include "dcamera_source_input.h" + +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceInputChannelListener::DCameraSourceInputChannelListener(std::shared_ptr& input, + DCStreamType streamType) : input_(input), streamType_(streamType) +{ +} + +DCameraSourceInputChannelListener::~DCameraSourceInputChannelListener() +{ +} + +void DCameraSourceInputChannelListener::OnSessionState(int32_t state) +{ + std::shared_ptr input = input_.lock(); + if (input == nullptr) { + DHLOGE("DCameraSourceInput OnSessionState not found input"); + return; + } + + input->OnSessionState(streamType_, state); +} + +void DCameraSourceInputChannelListener::OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) +{ + std::shared_ptr input = input_.lock(); + if (input == nullptr) { + DHLOGE("DCameraSourceInput OnSessionError not found input"); + return; + } + + input->OnSessionError(streamType_, eventType, eventReason, detail); +} + +void DCameraSourceInputChannelListener::OnDataReceived(std::vector>& buffers) +{ + std::shared_ptr input = input_.lock(); + if (input == nullptr) { + DHLOGE("DCameraSourceInput OnDataReceived not found input"); + return; + } + + input->OnDataReceived(streamType_, buffers); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bf016f58b94d7e646d379ce187a568fc294b40d --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process.cpp @@ -0,0 +1,229 @@ +/* + * 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 "dcamera_stream_data_process.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +#include "dcamera_pipeline_source.h" +#include "dcamera_stream_data_process_pipeline_listener.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraStreamDataProcess::DCameraStreamDataProcess(std::string devId, std::string dhId, DCStreamType streamType) + : devId_(devId), dhId_(dhId), streamType_(streamType) +{ + DHLOGI("DCameraSourceDataProcess Constructor devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + pipeline_ = nullptr; + listener_ = nullptr; +} + +DCameraStreamDataProcess::~DCameraStreamDataProcess() +{ + DHLOGI("DCameraStreamDataProcess Destructor devId %s dhId %s streamType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamType_); + streamIds_.clear(); + producers_.clear(); + if (pipeline_ != nullptr) { + pipeline_->DestroyDataProcessPipeline(); + } +} + +void DCameraStreamDataProcess::FeedStream(std::shared_ptr& buffer) +{ + DHLOGD("DCameraStreamDataProcess FeedStream devId %s dhId %s streamType %d streamSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, buffer->Size()); + switch (streamType_) { + case SNAPSHOT_FRAME: { + FeedStreamToSnapShot(buffer); + break; + } + case CONTINUOUS_FRAME: { + FeedStreamToContinue(buffer); + break; + } + default: + break; + } +} + +void DCameraStreamDataProcess::ConfigStreams(std::shared_ptr& dstConfig, + std::set& streamIds) +{ + DHLOGI("DCameraStreamDataProcess ConfigStreams devId %s dhId %s streamType: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_); + dstConfig_ = dstConfig; + streamIds_ = streamIds; +} + +void DCameraStreamDataProcess::ReleaseStreams(std::set& streamIds) +{ + for (auto iter = streamIds.begin(); iter != streamIds.end(); iter++) { + int32_t streamId = *iter; + DHLOGI("DCameraStreamDataProcess ReleaseStreams devId %s dhId %s streamId: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), streamId); + streamIds_.erase(streamId); + auto producerIter = producers_.find(streamId); + if (producerIter == producers_.end()) { + continue; + } + producerIter->second->Stop(); + producers_.erase(streamId); + } +} + +void DCameraStreamDataProcess::StartCapture(std::shared_ptr& srcConfig, + std::set& streamIds) +{ + srcConfig_ = srcConfig; + if (streamType_ == CONTINUOUS_FRAME) { + CreatePipeline(); + } + for (auto iter = streamIds_.begin(); iter != streamIds_.end(); iter++) { + uint32_t streamId = *iter; + DHLOGI("DCameraStreamDataProcess StartCapture devId %s dhId %s streamType: %d streamId: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId); + if (streamIds.find(streamId) == streamIds.end()) { + continue; + } + + DHLOGI("DCameraStreamDataProcess StartCapture findProducer devId %s dhId %s streamType: %d streamId: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId); + auto producerIter = producers_.find(streamId); + if (producerIter != producers_.end()) { + continue; + } + DHLOGI("DCameraStreamDataProcess StartCapture CreateProducer devId %s dhId %s streamType: %d streamId: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId); + producers_[streamId] = std::make_shared(devId_, dhId_, streamId, streamType_); + producers_[streamId]->Start(); + } +} + +void DCameraStreamDataProcess::StopCapture() +{ + DHLOGI("DCameraStreamDataProcess StopCapture devId %s dhId %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + if (streamType_ == CONTINUOUS_FRAME) { + DestroyPipeline(); + } + auto iter = producers_.begin(); + while (iter != producers_.end()) { + iter->second->Stop(); + iter = producers_.erase(iter); + } +} + +void DCameraStreamDataProcess::GetAllStreamIds(std::set& streamIds) +{ + streamIds = streamIds_; +} + +void DCameraStreamDataProcess::FeedStreamToSnapShot(const std::shared_ptr& buffer) +{ + DHLOGD("DCameraStreamDataProcess FeedStreamToSnapShot devId %s dhId %s streamType %d streamSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, buffer->Size()); + for (auto iter = producers_.begin(); iter != producers_.end(); iter++) { + iter->second->FeedStream(buffer); + } +} + +void DCameraStreamDataProcess::FeedStreamToContinue(const std::shared_ptr& buffer) +{ + DHLOGD("DCameraStreamDataProcess FeedStreamToContinue devId %s dhId %s streamType %d streamSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, buffer->Size()); + std::vector> buffers; + buffers.push_back(buffer); + if (pipeline_ == nullptr) { + DHLOGE("DCameraStreamDataProcess FeedStreamToContinue pipeline null devId %s dhId %s type: %d streamSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, buffer->Size()); + return; + } + int32_t ret = pipeline_->ProcessData(buffers); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraStreamDataProcess FeedStreamToContinue pipeline ProcessData failed, ret: %d", ret); + } +} + +void DCameraStreamDataProcess::OnProcessedVideoBuffer(const std::shared_ptr& videoResult) +{ + DHLOGI("DCameraStreamDataProcess OnProcessedVideoBuffer devId %s dhId %s streamType: %d streamSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, videoResult->Size()); + for (auto iter = producers_.begin(); iter != producers_.end(); iter++) { + iter->second->FeedStream(videoResult); + } +} + +void DCameraStreamDataProcess::OnError(DataProcessErrorType errorType) +{ + DHLOGE("DCameraStreamDataProcess OnError pipeline errorType: %d", errorType); +} + +void DCameraStreamDataProcess::CreatePipeline() +{ + if (pipeline_ != nullptr) { + DHLOGI("DCameraStreamDataProcess CreatePipeline already exist, devId %s dhId %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return; + } + pipeline_ = std::make_shared(); + auto process = std::shared_ptr(shared_from_this()); + listener_ = std::make_shared(process); + VideoConfigParams srcParams(GetPipelineCodecType(srcConfig_->encodeType_), GetPipelineFormat(srcConfig_->format_), + DCAMERA_PRODUCER_FPS_DEFAULT, srcConfig_->width_, srcConfig_->height_); + VideoConfigParams dstParams(GetPipelineCodecType(dstConfig_->encodeType_), GetPipelineFormat(dstConfig_->format_), + DCAMERA_PRODUCER_FPS_DEFAULT, dstConfig_->width_, dstConfig_->height_); + int32_t ret = pipeline_->CreateDataProcessPipeline(PipelineType::VIDEO, srcParams, dstParams, listener_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraStreamDataProcess CreateDataProcessPipeline type: %d failed, ret: %d", PipelineType::VIDEO, ret); + } +} + +void DCameraStreamDataProcess::DestroyPipeline() +{ + if (pipeline_ == nullptr) { + return; + } + pipeline_->DestroyDataProcessPipeline(); + pipeline_ = nullptr; +} + +VideoCodecType DCameraStreamDataProcess::GetPipelineCodecType(DCEncodeType encodeType) +{ + VideoCodecType codecType; + switch (encodeType) { + case ENCODE_TYPE_H264: + codecType = VideoCodecType::CODEC_H264; + break; + case ENCODE_TYPE_H265: + codecType = VideoCodecType::CODEC_H265; + break; + default: + codecType = VideoCodecType::NO_CODEC; + break; + } + return codecType; +} + +Videoformat DCameraStreamDataProcess::GetPipelineFormat(int32_t format) +{ + return Videoformat::NV21; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process_pipeline_listener.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process_pipeline_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0151a8fdb715cc23fffb50ff56bb6838df2bfce6 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process_pipeline_listener.cpp @@ -0,0 +1,55 @@ +/* + * 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 "dcamera_stream_data_process_pipeline_listener.h" + +#include "dcamera_stream_data_process.h" + +#include "anonymous_string.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraStreamDataProcessPipelineListener::DCameraStreamDataProcessPipelineListener( + std::shared_ptr& process) : process_(process) +{ +} + +DCameraStreamDataProcessPipelineListener::~DCameraStreamDataProcessPipelineListener() +{ +} + +void DCameraStreamDataProcessPipelineListener::OnProcessedVideoBuffer(const std::shared_ptr& videoResult) +{ + std::shared_ptr process = process_.lock(); + if (process == nullptr) { + DHLOGE("DCameraStreamDataProcessPipelineListener OnProcessedVideoBuffer not found process"); + return; + } + process->OnProcessedVideoBuffer(videoResult); +} + +void DCameraStreamDataProcessPipelineListener::OnError(DataProcessErrorType errorType) +{ + std::shared_ptr process = process_.lock(); + if (process == nullptr) { + DHLOGE("DCameraStreamDataProcessPipelineListener OnProcessedVideoBuffer not found process"); + return; + } + process->OnError(errorType); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process_producer.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process_producer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..902a2c13d78ce0e289cf2557af48ad90806c04bd --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcameradata/dcamera_stream_data_process_producer.cpp @@ -0,0 +1,235 @@ +/* + * 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 "dcamera_stream_data_process_producer.h" + +#include +#include + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraStreamDataProcessProducer::DCameraStreamDataProcessProducer(std::string devId, std::string dhId, + int32_t streamId, DCStreamType streamType) + : devId_(devId), dhId_(dhId), streamId_(streamId), streamType_(streamType) +{ + DHLOGI("DCameraStreamDataProcessProducer Constructor devId %s dhId %s streamType: %d streamId: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_); + state_ = DCAMERA_PRODUCER_STATE_STOP; + interval_ = DCAMERA_PRODUCER_ONE_MINUTE_MS / DCAMERA_PRODUCER_FPS_DEFAULT; +} + +DCameraStreamDataProcessProducer::~DCameraStreamDataProcessProducer() +{ + DHLOGI("DCameraStreamDataProcessProducer Destructor devId %s dhId %s state: %d streamType: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), state_, streamType_); + if (state_ == DCAMERA_PRODUCER_STATE_START) { + Stop(); + } +} + +void DCameraStreamDataProcessProducer::Start() +{ + DHLOGI("DCameraStreamDataProcessProducer Start producer devId: %s dhId: %s streamType: %d streamId: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_); + state_ = DCAMERA_PRODUCER_STATE_START; + if (streamType_ == CONTINUOUS_FRAME) { + producerThread_ = std::thread(&DCameraStreamDataProcessProducer::LooperContinue, this); + std::string threadName = "DCameraProducer_" + std::to_string(streamType_) + "_" + std::to_string(streamId_); + auto runner = AppExecFwk::EventRunner::Create(threadName); + eventHandler_ = std::make_shared(runner); + } else { + producerThread_ = std::thread(&DCameraStreamDataProcessProducer::LooperSnapShot, this); + } +} + +void DCameraStreamDataProcessProducer::Stop() +{ + DHLOGI("DCameraStreamDataProcessProducer Stop devId: %s dhId: %s streamType: %d streamId: %d state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_, state_); + state_ = DCAMERA_PRODUCER_STATE_STOP; + producerCon_.notify_one(); + producerThread_.join(); + eventHandler_ = nullptr; + DHLOGI("DCameraStreamDataProcessProducer Stop end devId: %s dhId: %s streamType: %d streamId: %d state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_, state_); +} + +void DCameraStreamDataProcessProducer::FeedStream(const std::shared_ptr& buffer) +{ + DHLOGD("DCameraStreamDataProcessProducer FeedStream devId %s dhId %s streamType: %d streamSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, buffer->Size()); + std::unique_lock lock(producerMutex_); + if (buffers_.size() >= DCAMERA_PRODUCER_MAX_BUFFER_SIZE) { + DHLOGD("DCameraStreamDataProcessProducer FeedStream OverSize devId %s dhId %s streamType: %d streamSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, buffer->Size()); + buffers_.pop(); + } + buffers_.push(buffer); + if (streamType_ == SNAPSHOT_FRAME) { + producerCon_.notify_one(); + } +} + +void DCameraStreamDataProcessProducer::LooperContinue() +{ + DHLOGI("LooperContinue producer devId: %s dhId: %s streamType: %d streamId: %d state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_, state_); + std::shared_ptr dhBase = std::make_shared(); + dhBase->deviceId_ = devId_; + dhBase->dhId_ = dhId_; + + while (state_ == DCAMERA_PRODUCER_STATE_START) { + std::shared_ptr buffer = nullptr; + { + std::unique_lock lock(producerMutex_); + producerCon_.wait_for(lock, std::chrono::milliseconds(interval_), [this] { + return (this->state_ == DCAMERA_PRODUCER_STATE_STOP); + }); + if (state_ == DCAMERA_PRODUCER_STATE_STOP || buffers_.empty()) { + continue; + } + + buffer = buffers_.front(); + if (buffers_.size() > 1) { + buffers_.pop(); + DHLOGD("common devId %s dhId %s streamSize: %d bufferSize: %d streamType: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), buffer->Size(), buffers_.size(), + streamType_); + } else { + DHLOGD("repeat devId %s dhId %s streamSize: %d bufferSize: %d streamType: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), buffer->Size(), buffers_.size(), + streamType_); + } + } + + auto feedFunc = [this, dhBase, buffer]() { + FeedStreamToDriver(dhBase, buffer); + }; + if (eventHandler_ != nullptr) { + eventHandler_->PostTask(feedFunc); + } + } + DHLOGI("LooperContinue producer end devId: %s dhId: %s streamType: %d streamId: %d state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_, state_); +} + +void DCameraStreamDataProcessProducer::LooperSnapShot() +{ + DHLOGI("LooperSnapShot producer devId: %s dhId: %s streamType: %d streamId: %d state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_, state_); + std::shared_ptr dhBase = std::make_shared(); + dhBase->deviceId_ = devId_; + dhBase->dhId_ = dhId_; + + while (state_ == DCAMERA_PRODUCER_STATE_START) { + std::shared_ptr buffer = nullptr; + { + std::unique_lock lock(producerMutex_); + producerCon_.wait(lock, [this] { + return (!buffers_.empty() || state_ == DCAMERA_PRODUCER_STATE_STOP); + }); + if (state_ == DCAMERA_PRODUCER_STATE_STOP) { + continue; + } + + if (!buffers_.empty()) { + DHLOGI("LooperSnapShot producer get buffer devId: %s dhId: %s streamType: %d streamId: %d state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_, state_); + buffer = buffers_.front(); + } + } + + if (buffer == nullptr) { + DHLOGI("LooperSnapShot producer get buffer failed devId: %s dhId: %s streamType: %d streamId: %d state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_, state_); + continue; + } + int32_t ret = FeedStreamToDriver(dhBase, buffer); + if (ret != DCAMERA_OK) { + std::this_thread::sleep_for(std::chrono::milliseconds(DCAMERA_PRODUCER_RETRY_SLEEP_MS)); + continue; + } + { + std::unique_lock lock(producerMutex_); + buffers_.pop(); + } + } + DHLOGI("LooperSnapShot producer end devId: %s dhId: %s streamType: %d streamId: %d state: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamType_, streamId_, state_); +} + +int32_t DCameraStreamDataProcessProducer::FeedStreamToDriver(const std::shared_ptr& dhBase, + const std::shared_ptr& buffer) +{ + DHLOGD("LooperFeed devId %s dhId %s streamSize: %d streamType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), buffer->Size(), streamType_); + sptr camHdiProvider = IDCameraProvider::Get(); + if (camHdiProvider == nullptr) { + DHLOGI("camHdiProvider is nullptr"); + return DCAMERA_BAD_VALUE; + } + std::shared_ptr sharedMemory; + DCamRetCode retHdi = camHdiProvider->AcquireBuffer(dhBase, streamId_, sharedMemory); + if (retHdi != SUCCESS) { + DHLOGE("AcquireBuffer devId: %s dhId: %s streamId: %d ret: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamId_, retHdi); + return DCAMERA_BAD_OPERATE; + } + + int32_t ret = DCAMERA_OK; + do { + if (sharedMemory == nullptr) { + DHLOGE("sharedMemory devId: %s dhId: %s streamId: %d, sharedMemory is null", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamId_); + ret = DCAMERA_MEMORY_OPT_ERROR; + break; + } + + if (buffer->Size() > sharedMemory->size_) { + DHLOGE("sharedMemory devId: %s dhId: %s streamId: %d bufSize: %d, addressSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamId_, buffer->Size(), + sharedMemory->size_); + ret = DCAMERA_MEMORY_OPT_ERROR; + break; + } + int32_t ret = memcpy_s(sharedMemory->bufferHandle_->virAddr, sharedMemory->size_, buffer->Data(), + buffer->Size()); + if (ret != EOK) { + DHLOGE("memcpy_s devId: %s dhId: %s streamId: %d bufSize: %d, addressSize: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamId_, buffer->Size(), + sharedMemory->size_); + ret = DCAMERA_MEMORY_OPT_ERROR; + break; + } + sharedMemory->size_ = buffer->Size(); + } while (0); + + retHdi = camHdiProvider->ShutterBuffer(dhBase, streamId_, sharedMemory); + if (retHdi != SUCCESS) { + DHLOGE("ShutterBuffer devId: %s dhId: %s streamId: %d ret: %d", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str(), streamId_, retHdi); + return DCAMERA_BAD_OPERATE; + } + DHLOGD("LooperFeed end devId %s dhId %s streamSize: %d streamType: %d", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str(), buffer->Size(), streamType_); + return ret; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerahdf/dcamera_provider_callback_impl.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerahdf/dcamera_provider_callback_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..768f41c46e5fd07eff2d86a2e224089708aa5641 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerahdf/dcamera_provider_callback_impl.cpp @@ -0,0 +1,181 @@ +/* + * 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 "dcamera_provider_callback_impl.h" + +#include "dcamera_index.h" +#include "dcamera_source_dev.h" + +#include "anonymous_string.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +#include "types.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraProviderCallbackImpl::DCameraProviderCallbackImpl(std::string devId, std::string dhId, + std::shared_ptr& sourceDev) : devId_(devId), dhId_(dhId), sourceDev_(sourceDev) +{ + DHLOGI("DCameraProviderCallbackImpl create devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); +} + +DCameraProviderCallbackImpl::~DCameraProviderCallbackImpl() +{ + DHLOGI("DCameraProviderCallbackImpl delete devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); +} + +DCamRetCode DCameraProviderCallbackImpl::OpenSession(const std::shared_ptr& dhBase) +{ + DHLOGI("DCameraProviderCallbackImpl OpenSession devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::shared_ptr sourceDev = sourceDev_.lock(); + if (sourceDev == nullptr) { + DHLOGE("DCameraProviderCallbackImpl OpenSession failed, can not get device, devId: %s, dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + DCameraIndex camIndex(devId_, dhId_); + int32_t ret = sourceDev->OpenSession(camIndex); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraProviderCallbackImpl OpenSession failed, ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + return SUCCESS; +} + +DCamRetCode DCameraProviderCallbackImpl::CloseSession(const std::shared_ptr& dhBase) +{ + DHLOGI("DCameraProviderCallbackImpl CloseSession devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::shared_ptr sourceDev = sourceDev_.lock(); + if (sourceDev == nullptr) { + DHLOGE("DCameraProviderCallbackImpl CloseSession failed, can not get device, devId: %s, dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + DCameraIndex camIndex(devId_, dhId_); + int32_t ret = sourceDev->CloseSession(camIndex); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraProviderCallbackImpl CloseSession failed, ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + return SUCCESS; +} + +DCamRetCode DCameraProviderCallbackImpl::ConfigureStreams(const std::shared_ptr& dhBase, + const std::vector>& streamInfos) +{ + DHLOGI("DCameraProviderCallbackImpl ConfigStreams devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::shared_ptr sourceDev = sourceDev_.lock(); + if (sourceDev == nullptr) { + DHLOGE("DCameraProviderCallbackImpl ConfigStreams failed, can not get device, devId: %s, dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + int32_t ret = sourceDev->ConfigStreams(streamInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraProviderCallbackImpl CloseSession failed, ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + return SUCCESS; +} + +DCamRetCode DCameraProviderCallbackImpl::ReleaseStreams(const std::shared_ptr& dhBase, + const std::vector& streamIds) +{ + DHLOGI("DCameraProviderCallbackImpl ReleaseStreams devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::shared_ptr sourceDev = sourceDev_.lock(); + if (sourceDev == nullptr) { + DHLOGE("DCameraProviderCallbackImpl ReleaseStreams failed, can not get device, devId: %s, dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + int32_t ret = sourceDev->ReleaseStreams(streamIds); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraProviderCallbackImpl ReleaseStreams failed, ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + return SUCCESS; +} + +DCamRetCode DCameraProviderCallbackImpl::StartCapture(const std::shared_ptr& dhBase, + const std::vector>& captureInfos) +{ + DHLOGI("DCameraProviderCallbackImpl StartCapture devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::shared_ptr sourceDev = sourceDev_.lock(); + if (sourceDev == nullptr) { + DHLOGE("DCameraProviderCallbackImpl StartCapture failed, can not get device, devId: %s, dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + int32_t ret = sourceDev->StartCapture(captureInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraProviderCallbackImpl StartCapture failed, ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + return SUCCESS; +} + +DCamRetCode DCameraProviderCallbackImpl::StopCapture(const std::shared_ptr& dhBase) +{ + DHLOGI("DCameraProviderCallbackImpl StopCapture devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::shared_ptr sourceDev = sourceDev_.lock(); + if (sourceDev == nullptr) { + DHLOGE("DCameraProviderCallbackImpl StopCapture failed, can not get device, devId: %s, dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + int32_t ret = sourceDev->StopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraProviderCallbackImpl StopCapture failed, ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + return SUCCESS; +} + +DCamRetCode DCameraProviderCallbackImpl::UpdateSettings(const std::shared_ptr& dhBase, + const std::vector>& settings) +{ + DHLOGI("DCameraProviderCallbackImpl UpdateSettings devId: %s dhId: %s", GetAnonyString(devId_).c_str(), + GetAnonyString(dhId_).c_str()); + std::shared_ptr sourceDev = sourceDev_.lock(); + if (sourceDev == nullptr) { + DHLOGE("DCameraProviderCallbackImpl UpdateSettings failed, can not get device, devId: %s, dhId: %s", + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + int32_t ret = sourceDev->UpdateCameraSettings(settings); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraProviderCallbackImpl UpdateSettings failed, ret: %d, devId: %s, dhId: %s", ret, + GetAnonyString(devId_).c_str(), GetAnonyString(dhId_).c_str()); + return FAILED; + } + return SUCCESS; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_capture_state.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_capture_state.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b6e3072f5c5d2c65ddb3dba307587b390e196e6 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_capture_state.cpp @@ -0,0 +1,217 @@ +/* + * 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 "dcamera_source_capture_state.h" + +#include "dcamera_source_dev.h" +#include "dcamera_source_state_machine.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceCaptureState::DCameraSourceCaptureState(std::shared_ptr& stateMachine) + : stateMachine_(stateMachine) +{ + memberFuncMap_[DCAMERA_EVENT_REGIST] = &DCameraSourceCaptureState::DoRegisterTask; + memberFuncMap_[DCAMERA_EVENT_UNREGIST] = &DCameraSourceCaptureState::DoUnregisterTask; + memberFuncMap_[DCAMERA_EVENT_OPEN] = &DCameraSourceCaptureState::DoOpenTask; + memberFuncMap_[DCAMERA_EVENT_CLOSE] = &DCameraSourceCaptureState::DoCloseTask; + memberFuncMap_[DCAMERA_EVENT_START_CAPTURE] = &DCameraSourceCaptureState::DoStartCaptureTask; + memberFuncMap_[DCAMERA_EVENT_STOP_CAPTURE] = &DCameraSourceCaptureState::DoStopCaptureTask; + memberFuncMap_[DCAMERA_EVENT_UPDATE_SETTINGS] = &DCameraSourceCaptureState::DoUpdateSettingsTask; + memberFuncMap_[DCAMERA_EVENT_NOFIFY] = &DCameraSourceCaptureState::DoEventNofityTask; +} + +int32_t DCameraSourceCaptureState::Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) +{ + auto itFunc = memberFuncMap_.find(eventType); + if (itFunc == memberFuncMap_.end()) { + DHLOGE("DCameraSourceCaptureState execute %d in wrong state", eventType); + return DCAMERA_WRONG_STATE; + } + + auto memberFunc = itFunc->second; + int32_t ret = (this->*memberFunc)(camDev, event); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState execute %d failed, ret: %d", eventType, ret); + } + return ret; +} + +DCameraStateType DCameraSourceCaptureState::GetStateType() +{ + return DCAMERA_STATE_CAPTURE; +} + +int32_t DCameraSourceCaptureState::DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceCaptureState DoRegisterTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceCaptureState::DoUnregisterTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::shared_ptr camEvent = std::make_shared(); + camEvent->eventType_ = DCAMERA_MESSAGE; + camEvent->eventResult_ = DCAMERA_EVENT_CHANNEL_DISCONNECTED; + int32_t ret = camDev->ExecuteCameraEventNotify(camEvent); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState DoUnregisterTask ExecuteCameraEventNotify failed: %d", ret); + return ret; + } + + ret = camDev->ExecuteStopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState DoUnregisterTask ExecuteStopCapture failed: %d", ret); + return ret; + } + + ret = camDev->ExecuteCloseCamera(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState DoUnregisterTask ExecuteCloseCamera failed, ret: %d", ret); + return ret; + } + + ret = camDev->ExecuteReleaseAllStreams(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState DoUnregisterTask ExecuteReleaseAllStreams failed, ret: %d", ret); + return ret; + } + + std::shared_ptr param; + ret = event.GetDCameraRegistParam(param); + if (ret != DCAMERA_OK) { + return ret; + } + ret = camDev->ExecuteUnRegister(param); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState DoUnregisterTask ExecuteUnRegister failed: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceCaptureState DoUnregisterTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_INIT); + return DCAMERA_OK; +} + +int32_t DCameraSourceCaptureState::DoOpenTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceCaptureState DoOpenTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceCaptureState::DoCloseTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + int32_t ret = camDev->ExecuteStopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState ExecuteStopCapture failed, ret: %d", ret); + return ret; + } + + ret = camDev->ExecuteReleaseAllStreams(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState ExecuteReleaseAllStreams failed, ret: %d", ret); + return ret; + } + + ret = camDev->ExecuteCloseCamera(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState ExecuteCloseCamera failed, ret: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceCaptureState DoOpenTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_REGIST); + return DCAMERA_OK; +} + +int32_t DCameraSourceCaptureState::DoStartCaptureTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::vector> captureInfos; + int32_t ret = event.GetCaptureInfos(captureInfos); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteStartCapture(captureInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState DoStartCaptureTask failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceCaptureState::DoStopCaptureTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + int32_t ret = camDev->ExecuteStopCapture(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState ExecuteStopCapture failed, ret: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceCaptureState DoStopCaptureTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_CONFIG_STREAM); + return DCAMERA_OK; +} + +int32_t DCameraSourceCaptureState::DoUpdateSettingsTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::vector> settings; + int32_t ret = event.GetCameraSettings(settings); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteUpdateSettings(settings); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState ExecuteUpdateSettings failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceCaptureState::DoEventNofityTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::shared_ptr camEvent; + int32_t ret = event.GetCameraEvent(camEvent); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteCameraEventNotify(camEvent); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceCaptureState ExecuteCameraEventNotify failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_config_stream_state.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_config_stream_state.cpp new file mode 100644 index 0000000000000000000000000000000000000000..654b41259437d972d3fb511dd7d968fcb1415bcd --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_config_stream_state.cpp @@ -0,0 +1,258 @@ +/* + * 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 "dcamera_source_config_stream_state.h" + +#include "dcamera_source_dev.h" +#include "dcamera_source_state_machine.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceConfigStreamState::DCameraSourceConfigStreamState(std::shared_ptr& stateMachine) + : stateMachine_(stateMachine) +{ + memberFuncMap_[DCAMERA_EVENT_REGIST] = &DCameraSourceConfigStreamState::DoRegisterTask; + memberFuncMap_[DCAMERA_EVENT_UNREGIST] = &DCameraSourceConfigStreamState::DoUnregisterTask; + memberFuncMap_[DCAMERA_EVENT_OPEN] = &DCameraSourceConfigStreamState::DoOpenTask; + memberFuncMap_[DCAMERA_EVENT_CLOSE] = &DCameraSourceConfigStreamState::DoCloseTask; + memberFuncMap_[DCAMERA_EVENT_CONFIG_STREAMS] = &DCameraSourceConfigStreamState::DoConfigStreamsTask; + memberFuncMap_[DCAMERA_EVENT_RELEASE_STREAMS] = &DCameraSourceConfigStreamState::DoReleaseStreamsTask; + memberFuncMap_[DCAMERA_EVENT_START_CAPTURE] = &DCameraSourceConfigStreamState::DoStartCaptureTask; + memberFuncMap_[DCAMERA_EVENT_STOP_CAPTURE] = &DCameraSourceConfigStreamState::DoStopCaptureTask; + memberFuncMap_[DCAMERA_EVENT_UPDATE_SETTINGS] = &DCameraSourceConfigStreamState::DoUpdateSettingsTask; + memberFuncMap_[DCAMERA_EVENT_NOFIFY] = &DCameraSourceConfigStreamState::DoEventNofityTask; +} + +int32_t DCameraSourceConfigStreamState::Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) +{ + auto itFunc = memberFuncMap_.find(eventType); + if (itFunc == memberFuncMap_.end()) { + DHLOGE("DCameraSourceConfigStreamState execute %d in wrong state", eventType); + return DCAMERA_WRONG_STATE; + } + + auto memberFunc = itFunc->second; + int32_t ret = (this->*memberFunc)(camDev, event); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState execute %d failed, ret: %d", eventType, ret); + } + return ret; +} + +DCameraStateType DCameraSourceConfigStreamState::GetStateType() +{ + return DCAMERA_STATE_CONFIG_STREAM; +} + +int32_t DCameraSourceConfigStreamState::DoRegisterTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceConfigStreamState DoRegisterTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoUnregisterTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::shared_ptr camEvent = std::make_shared(); + camEvent->eventType_ = DCAMERA_MESSAGE; + camEvent->eventResult_ = DCAMERA_EVENT_CHANNEL_DISCONNECTED; + int32_t ret = camDev->ExecuteCameraEventNotify(camEvent); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState DoUnregisterTask ExecuteCameraEventNotify failed: %d", ret); + return ret; + } + + ret = camDev->ExecuteCloseCamera(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState DoUnregisterTask ExecuteCloseCamera failed, ret: %d", ret); + return ret; + } + + ret = camDev->ExecuteReleaseAllStreams(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState DoUnregisterTask ExecuteReleaseAllStreams failed, ret: %d", ret); + return ret; + } + + std::shared_ptr param; + ret = event.GetDCameraRegistParam(param); + if (ret != DCAMERA_OK) { + return ret; + } + ret = camDev->ExecuteUnRegister(param); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState DoUnregisterTask ExecuteUnRegister failed: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceConfigStreamState DoUnregisterTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_INIT); + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoOpenTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceConfigStreamState DoOpenTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoCloseTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + int32_t ret = camDev->ExecuteCloseCamera(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState ExecuteCloseCamera failed, ret: %d", ret); + return ret; + } + + ret = camDev->ExecuteReleaseAllStreams(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState ExecuteReleaseAllStreams failed, ret: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceConfigStreamState DoOpenTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_REGIST); + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoConfigStreamsTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::vector> streamInfos; + int32_t ret = event.GetStreamInfos(streamInfos); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteConfigStreams(streamInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState ExecuteConfigStreams failed, ret: %d", ret); + return ret; + } + + if (streamInfos.empty()) { + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceConfigStreamState DoOpenTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_OPENED); + } + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoReleaseStreamsTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::vector streamIds; + int32_t ret = event.GetStreamIds(streamIds); + if (ret != DCAMERA_OK) { + return ret; + } + + bool isAllRelease = false; + ret = camDev->ExecuteReleaseStreams(streamIds, isAllRelease); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState ExecuteConfigStreams failed, ret: %d", ret); + return ret; + } + + if (isAllRelease) { + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceConfigStreamState DoOpenTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_OPENED); + } + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoStartCaptureTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::vector> captureInfos; + int32_t ret = event.GetCaptureInfos(captureInfos); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteStartCapture(captureInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState ExecuteStartCapture failed, ret: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceConfigStreamState DoOpenTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_CAPTURE); + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoStopCaptureTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceConfigStreamState DoStopCaptureTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoUpdateSettingsTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::vector> settings; + int32_t ret = event.GetCameraSettings(settings); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteUpdateSettings(settings); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState ExecuteConfigStreams failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceConfigStreamState::DoEventNofityTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::shared_ptr camEvent; + int32_t ret = event.GetCameraEvent(camEvent); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteCameraEventNotify(camEvent); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceConfigStreamState ExecuteCameraEventNotify failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_init_state.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_init_state.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da582aa81f29678a4a0b44bf8706822258252fae --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_init_state.cpp @@ -0,0 +1,80 @@ +/* + * 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 "dcamera_source_init_state.h" + +#include "dcamera_source_dev.h" +#include "dcamera_source_state_machine.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceInitState::DCameraSourceInitState(std::shared_ptr& stateMachine) + : stateMachine_(stateMachine) +{ + memberFuncMap_[DCAMERA_EVENT_REGIST] = &DCameraSourceInitState::DoRegisterTask; + memberFuncMap_[DCAMERA_EVENT_UNREGIST] = &DCameraSourceInitState::DoUnregisterTask; +} + +int32_t DCameraSourceInitState::Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) +{ + auto itFunc = memberFuncMap_.find(eventType); + if (itFunc == memberFuncMap_.end()) { + DHLOGE("DCameraSourceInitState execute %d in wrong state", eventType); + return DCAMERA_WRONG_STATE; + } + + auto memberFunc = itFunc->second; + int32_t ret = (this->*memberFunc)(camDev, event); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceInitState execute %d failed, ret: %d", eventType, ret); + } + return ret; +} + +DCameraStateType DCameraSourceInitState::GetStateType() +{ + return DCAMERA_STATE_INIT; +} + +int32_t DCameraSourceInitState::DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + std::shared_ptr param; + int32_t ret = event.GetDCameraRegistParam(param); + if (ret != DCAMERA_OK) { + return ret; + } + ret = camDev->ExecuteRegister(param); + if (ret != DCAMERA_OK) { + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceInitState can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_REGIST); + return DCAMERA_OK; +} + +int32_t DCameraSourceInitState::DoUnregisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceInitState DoUnregisterTask Idempotent"); + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_opened_state.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_opened_state.cpp new file mode 100644 index 0000000000000000000000000000000000000000..975a302ad66df8bd2318863c3e412cbc11bca15a --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_opened_state.cpp @@ -0,0 +1,188 @@ +/* + * 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 "dcamera_source_opened_state.h" + +#include "dcamera_source_dev.h" +#include "dcamera_source_state_machine.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceOpenedState::DCameraSourceOpenedState(std::shared_ptr& stateMachine) + : stateMachine_(stateMachine) +{ + memberFuncMap_[DCAMERA_EVENT_REGIST] = &DCameraSourceOpenedState::DoRegisterTask; + memberFuncMap_[DCAMERA_EVENT_UNREGIST] = &DCameraSourceOpenedState::DoUnregisterTask; + memberFuncMap_[DCAMERA_EVENT_OPEN] = &DCameraSourceOpenedState::DoOpenTask; + memberFuncMap_[DCAMERA_EVENT_CLOSE] = &DCameraSourceOpenedState::DoCloseTask; + memberFuncMap_[DCAMERA_EVENT_CONFIG_STREAMS] = &DCameraSourceOpenedState::DoConfigStreamsTask; + memberFuncMap_[DCAMERA_EVENT_RELEASE_STREAMS] = &DCameraSourceOpenedState::DoReleaseStreamsTask; + memberFuncMap_[DCAMERA_EVENT_UPDATE_SETTINGS] = &DCameraSourceOpenedState::DoUpdateSettingsTask; + memberFuncMap_[DCAMERA_EVENT_NOFIFY] = &DCameraSourceOpenedState::DoEventNofityTask; +} + +int32_t DCameraSourceOpenedState::Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) +{ + auto itFunc = memberFuncMap_.find(eventType); + if (itFunc == memberFuncMap_.end()) { + DHLOGE("DCameraSourceOpenedState execute %d in wrong state", eventType); + return DCAMERA_WRONG_STATE; + } + + auto memberFunc = itFunc->second; + int32_t ret = (this->*memberFunc)(camDev, event); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceOpenedState execute %d failed, ret: %d", eventType, ret); + } + return ret; +} + +DCameraStateType DCameraSourceOpenedState::GetStateType() +{ + return DCAMERA_STATE_OPENED; +} + +int32_t DCameraSourceOpenedState::DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceOpenedState DoRegisterTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceOpenedState::DoUnregisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + std::shared_ptr camEvent = std::make_shared(); + camEvent->eventType_ = DCAMERA_MESSAGE; + camEvent->eventResult_ = DCAMERA_EVENT_CHANNEL_DISCONNECTED; + int32_t ret = camDev->ExecuteCameraEventNotify(camEvent); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceOpenedState DoUnregisterTask ExecuteCameraEventNotify failed: %d", ret); + return ret; + } + + ret = camDev->ExecuteCloseCamera(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceOpenedState DoUnregisterTask ExecuteCloseCamera failed: %d", ret); + return ret; + } + + std::shared_ptr param; + ret = event.GetDCameraRegistParam(param); + if (ret != DCAMERA_OK) { + return ret; + } + ret = camDev->ExecuteUnRegister(param); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceOpenedState DoUnregisterTask ExecuteUnRegister failed: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceOpenedState DoUnregisterTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_INIT); + return DCAMERA_OK; +} + +int32_t DCameraSourceOpenedState::DoConfigStreamsTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::vector> streamInfos; + int32_t ret = event.GetStreamInfos(streamInfos); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteConfigStreams(streamInfos); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceOpenedState ExecuteConfigStreams failed, ret: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceOpenedState DoConfigStreamsTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_CONFIG_STREAM); + return DCAMERA_OK; +} + +int32_t DCameraSourceOpenedState::DoReleaseStreamsTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceOpenedState DoReleaseStreamsTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceOpenedState::DoUpdateSettingsTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::vector> settings; + int32_t ret = event.GetCameraSettings(settings); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteUpdateSettings(settings); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceOpenedState ExecuteConfigStreams failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceOpenedState::DoOpenTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceOpenedState DoOpenTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceOpenedState::DoCloseTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + int32_t ret = camDev->ExecuteCloseCamera(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceOpenedState DoOpenTask ExecuteCloseCamera failed, ret: %d", ret); + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceOpenedState DoOpenTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_REGIST); + return DCAMERA_OK; +} + +int32_t DCameraSourceOpenedState::DoEventNofityTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::shared_ptr camEvent; + int32_t ret = event.GetCameraEvent(camEvent); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteCameraEventNotify(camEvent); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceOpenedState DoEventNofityTask ExecuteCameraEventNotify failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_regist_state.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_regist_state.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f6b9095dac7410b801b3f724dd6dbfe97d406ae --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_regist_state.cpp @@ -0,0 +1,117 @@ +/* + * 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 "dcamera_source_regist_state.h" + +#include "dcamera_source_dev.h" +#include "dcamera_source_state_machine.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceRegistState::DCameraSourceRegistState(std::shared_ptr& stateMachine) + : stateMachine_(stateMachine) +{ + memberFuncMap_[DCAMERA_EVENT_REGIST] = &DCameraSourceRegistState::DoRegisterTask; + memberFuncMap_[DCAMERA_EVENT_UNREGIST] = &DCameraSourceRegistState::DoUnregisterTask; + memberFuncMap_[DCAMERA_EVENT_OPEN] = &DCameraSourceRegistState::DoOpenTask; + memberFuncMap_[DCAMERA_EVENT_CLOSE] = &DCameraSourceRegistState::DoCloseTask; + memberFuncMap_[DCAMERA_EVENT_NOFIFY] = &DCameraSourceRegistState::DoEventNofityTask; +} + +int32_t DCameraSourceRegistState::Execute(std::shared_ptr& camDev, DCAMERA_EVENT eventType, + DCameraSourceEvent& event) +{ + auto itFunc = memberFuncMap_.find(eventType); + if (itFunc == memberFuncMap_.end()) { + DHLOGE("DCameraSourceRegistState execute %d in wrong state", eventType); + return DCAMERA_WRONG_STATE; + } + + auto memberFunc = itFunc->second; + int32_t ret = (this->*memberFunc)(camDev, event); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceRegistState execute %d failed, ret: %d", eventType, ret); + } + return ret; +} + +DCameraStateType DCameraSourceRegistState::GetStateType() +{ + return DCAMERA_STATE_REGIST; +} + +int32_t DCameraSourceRegistState::DoRegisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceRegistState DoRegisterTask Idempotent"); + return DCAMERA_OK; +} + + +int32_t DCameraSourceRegistState::DoUnregisterTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + std::shared_ptr param; + int32_t ret = event.GetDCameraRegistParam(param); + if (ret != DCAMERA_OK) { + return ret; + } + ret = camDev->ExecuteUnRegister(param); + if (ret != DCAMERA_OK) { + return ret; + } + std::shared_ptr stateMachine = stateMachine_.lock(); + if (stateMachine == nullptr) { + DHLOGE("DCameraSourceRegistState DoUnregisterTask can not get stateMachine"); + return DCAMERA_BAD_VALUE; + } + stateMachine->UpdateState(DCAMERA_STATE_INIT); + return DCAMERA_OK; +} + +int32_t DCameraSourceRegistState::DoOpenTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + int32_t ret = camDev->ExecuteOpenCamera(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceRegistState ExecuteOpenCamera failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} + +int32_t DCameraSourceRegistState::DoCloseTask(std::shared_ptr& camDev, DCameraSourceEvent& event) +{ + DHLOGI("DCameraSourceRegistState DoCloseTask Idempotent"); + return DCAMERA_OK; +} + +int32_t DCameraSourceRegistState::DoEventNofityTask(std::shared_ptr& camDev, + DCameraSourceEvent& event) +{ + std::shared_ptr camEvent; + int32_t ret = event.GetCameraEvent(camEvent); + if (ret != DCAMERA_OK) { + return ret; + } + + ret = camDev->ExecuteCameraEventNotify(camEvent); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceRegistState DoEventNofityTask ExecuteCameraEventNotify failed, ret: %d", ret); + return ret; + } + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_state_factory.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_state_factory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d43f8aed119c7e1b6825f8e3d6b82a98346737e3 --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_state_factory.cpp @@ -0,0 +1,65 @@ +/* + * 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 "dcamera_source_state_factory.h" + +#include "dcamera_source_capture_state.h" +#include "dcamera_source_config_stream_state.h" +#include "dcamera_source_init_state.h" +#include "dcamera_source_opened_state.h" +#include "dcamera_source_regist_state.h" + +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DCameraSourceStateFactory); + +std::shared_ptr DCameraSourceStateFactory::CreateState(DCameraStateType stateType, + std::shared_ptr& stateMachine) +{ + std::shared_ptr state = nullptr; + switch (stateType) { + case DCAMERA_STATE_INIT: { + state = std::make_shared(stateMachine); + break; + } + case DCAMERA_STATE_REGIST: { + state = std::make_shared(stateMachine); + break; + } + case DCAMERA_STATE_OPENED: { + state = std::make_shared(stateMachine); + break; + } + case DCAMERA_STATE_CONFIG_STREAM: { + state = std::make_shared(stateMachine); + break; + } + case DCAMERA_STATE_CAPTURE: { + state = std::make_shared(stateMachine); + break; + } + default: { + DHLOGE("DCameraSourceStateFactory create state failed, wrong type %d", stateType); + return nullptr; + } + } + + return state; +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_state_machine.cpp b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_state_machine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95c0fab6f33b86ab42d01b1637cbc3ef5f8131ee --- /dev/null +++ b/services/cameraservice/sourceservice/src/distributedcameramgr/dcamerastate/dcamera_source_state_machine.cpp @@ -0,0 +1,63 @@ +/* + * 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 "dcamera_source_state_machine.h" + +#include + +#include "dcamera_source_state_factory.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSourceStateMachine::DCameraSourceStateMachine(std::shared_ptr& camDev) : camDev_(camDev) +{ + DHLOGI("DCameraSourceStateMachine Create"); +} + +DCameraSourceStateMachine::~DCameraSourceStateMachine() +{ + DHLOGI("DCameraSourceStateMachine Delete"); +} + +int32_t DCameraSourceStateMachine::Execute(DCAMERA_EVENT eventType, DCameraSourceEvent& event) +{ + DHLOGI("In state %d execute event %d", currentState_->GetStateType(), eventType); + std::shared_ptr camDev = camDev_.lock(); + if (camDev == nullptr) { + DHLOGE("DCameraSourceStateMachine execute failed, camDev is nullptr"); + return DCAMERA_BAD_VALUE; + } + int32_t ret = currentState_->Execute(camDev, event.GetEventType(), event); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSourceStateMachine currentState_: %d execute event: %d failed", currentState_->GetStateType(), + event.GetEventType()); + } + return ret; +} + +void DCameraSourceStateMachine::UpdateState(DCameraStateType stateType) +{ + if (stateType != DCAMERA_STATE_INIT) { + DHLOGI("DCameraSourceStateMachine update state from %d to %d", currentState_->GetStateType(), stateType); + } else { + DHLOGI("DCameraSourceStateMachine update state %d", stateType); + } + auto stateMachine = std::shared_ptr(shared_from_this()); + currentState_ = DCameraSourceStateFactory::GetInstance().CreateState(stateType, stateMachine); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/test/unittest/BUILD.gn b/services/cameraservice/sourceservice/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b4ed56ba3b28b2fe92ceb526eab0b4f125423c8a --- /dev/null +++ b/services/cameraservice/sourceservice/test/unittest/BUILD.gn @@ -0,0 +1,19 @@ +# 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. + +group("source_service_test") { + testonly = true + deps = [ + "common/distributedcameramgr:dcamera_mgr_test", + ] +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/BUILD.gn b/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5401e17c8f2263aaac187aa083d885ca1fc85882 --- /dev/null +++ b/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/BUILD.gn @@ -0,0 +1,93 @@ +# 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. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") +module_out_path = "distributedcamera/dcamera_source_mgr_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${services_path}/cameraservice/sourceservice/include/distributedcamera", + "${services_path}/cameraservice/sourceservice/include/distributedcameramgr", + "${services_path}/cameraservice/sourceservice/include/distributedcameramgr/dcameracontrol", + "${services_path}/cameraservice/sourceservice/include/distributedcameramgr/dcameradata", + "${services_path}/cameraservice/sourceservice/include/distributedcameramgr/dcamerahdf", + "${services_path}/cameraservice/sourceservice/include/distributedcameramgr/dcamerainterface", + "${services_path}/cameraservice/sourceservice/include/distributedcameramgr/dcamerastate", + "${services_path}/cameraservice/cameraoperator/client/include", + "${services_path}/cameraservice/base/include", + "${services_path}/channel/include", + "${services_path}/data_process/include/pipeline", + "${services_path}/data_process/include/interfaces", + "${services_path}/data_process/include/utils", + "${services_path}/data_process/include/eventbus", + "${common_path}/include/constants", + "${common_path}/include/utils", + + "${innerkits_path}/native_cpp/camera_source/include", + "${innerkits_path}/native_cpp/camera_source/include/callback", + "${innerkits_path}/native_cpp/camera_sink/include", + + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + "${fwk_utils_path}/include/eventbus", + "${fwk_common_path}/utils/include", + "${fwk_common_path}/log/include", + "${distributedcamera_hdf_path}/interfaces/include", + "${distributedcamera_hdf_path}/interfaces/hdi_ipc/client/provider", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "//third_party/jsoncpp/include", + "//drivers/peripheral/base/", + ] +} + +ohos_unittest("DCameraSourceMgrTest") { + module_out_path = module_out_path + + sources = [ + "dcamera_source_state_machine_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${services_path}/cameraservice/sourceservice:distributed_camera_source", + "${services_path}/channel:distributed_camera_channel", + "${common_path}:distributed_camera_utils", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + "${fwk_utils_path}:distributedhardwareutils", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ipc:ipc_core", + "eventhandler:libeventhandler", + + "dsoftbus_standard:softbus_client", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DCameraSourceMgrTest\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("dcamera_mgr_test") { + testonly = true + deps = [ ":DCameraSourceMgrTest" ] +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/dcamera_source_state_machine_test.cpp b/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/dcamera_source_state_machine_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..493b1e56c3f77551b8e9a06f1f0f064fce3b5a61 --- /dev/null +++ b/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/dcamera_source_state_machine_test.cpp @@ -0,0 +1,355 @@ +/* + * 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 +#include +#define private public +#include "dcamera_source_state.h" +#undef private + +#include "dcamera_source_capture_state.h" +#include "dcamera_source_config_stream_state.h" +#include "dcamera_source_init_state.h" +#include "dcamera_source_opened_state.h" +#include "dcamera_source_regist_state.h" +#include "dcamera_source_state_factory.h" +#include "dcamera_source_state_machine.h" +#include "mock_dcamera_source_dev.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +class DCameraSourceStateMachineTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr camDev_; + std::shared_ptr stateMachine_; + +private: + static void SetStreamInfos(); + static void SetCaptureInfos(); +}; + +namespace { +const std::string TEST_DEVICE_ID = "bb536a637105409e904d4da83790a4a7"; +const std::string TEST_CAMERA_DH_ID_0 = "camera_0"; +const std::string TEST_REQID = "0xFFFF"; +const std::string TEST_PARAM = "0xFFFF"; +const int32_t TEST_WIDTH = 1920; +const int32_t TEST_HEIGTH = 1080; +const int32_t TEST_STREAMID = 2; +} + +std::vector> g_streamInfosSnap; +std::vector> g_captureInfoSnap; +std::vector> g_cameraSettingSnap; +std::vector g_streamIdSnap; +std::shared_ptr g_camEvent; +std::shared_ptr g_registParam; +DCameraIndex g_camIndex; + +void DCameraSourceStateMachineTest::SetUpTestCase(void) +{ + SetStreamInfos(); + SetCaptureInfos(); +} + +void DCameraSourceStateMachineTest::SetStreamInfos() +{ + g_camIndex.devId_ = TEST_DEVICE_ID; + g_camIndex.dhId_ = TEST_CAMERA_DH_ID_0; + g_camEvent = std::make_shared(); + std::shared_ptr streamInfo1 = std::make_shared(); + streamInfo1->streamId_ = 1; + streamInfo1->width_ = TEST_WIDTH; + streamInfo1->height_ = TEST_HEIGTH; + streamInfo1->stride_ = 1; + streamInfo1->format_ = 1; + streamInfo1->dataspace_ = 1; + streamInfo1->encodeType_ = ENCODE_TYPE_JPEG; + streamInfo1->type_ = SNAPSHOT_FRAME; + + std::shared_ptr streamInfo2 = std::make_shared(); + streamInfo2->streamId_ = TEST_STREAMID; + streamInfo2->width_ = TEST_WIDTH; + streamInfo2->height_ = TEST_HEIGTH; + streamInfo2->stride_ = 1; + streamInfo2->format_ = 1; + streamInfo2->dataspace_ = 1; + streamInfo2->encodeType_ = ENCODE_TYPE_JPEG; + streamInfo2->type_ = SNAPSHOT_FRAME; + g_streamInfosSnap.push_back(streamInfo1); + g_streamInfosSnap.push_back(streamInfo2); +} + +void DCameraSourceStateMachineTest::SetCaptureInfos() +{ + std::shared_ptr captureInfo1 = std::make_shared(); + captureInfo1->streamIds_.push_back(1); + captureInfo1->width_ = TEST_WIDTH; + captureInfo1->height_ = TEST_HEIGTH; + captureInfo1->stride_ = 1; + captureInfo1->format_ = 1; + captureInfo1->dataspace_ = 1; + captureInfo1->encodeType_ = ENCODE_TYPE_H265; + captureInfo1->type_ = CONTINUOUS_FRAME; + + std::shared_ptr captureInfo2 = std::make_shared(); + captureInfo2->streamIds_.push_back(1); + captureInfo2->width_ = TEST_WIDTH; + captureInfo2->height_ = TEST_HEIGTH; + captureInfo2->stride_ = 1; + captureInfo2->format_ = 1; + captureInfo2->dataspace_ = 1; + captureInfo2->encodeType_ = ENCODE_TYPE_H265; + captureInfo2->type_ = CONTINUOUS_FRAME; + g_captureInfoSnap.push_back(captureInfo1); + g_captureInfoSnap.push_back(captureInfo2); + + std::shared_ptr camSettings1 = std::make_shared(); + camSettings1->type_ = UPDATE_METADATA; + camSettings1->value_ = "SettingValue"; + + std::shared_ptr camSettings2 = std::make_shared(); + camSettings2->type_ = ENABLE_METADATA; + camSettings2->value_ = "SettingValue"; + g_cameraSettingSnap.push_back(camSettings1); + g_cameraSettingSnap.push_back(camSettings2); + + g_streamIdSnap.push_back(1); + g_streamIdSnap.push_back(TEST_STREAMID); + + g_registParam = std::make_shared(TEST_DEVICE_ID, TEST_CAMERA_DH_ID_0, TEST_REQID, TEST_PARAM); +} + +void DCameraSourceStateMachineTest::TearDownTestCase(void) +{ +} + +void DCameraSourceStateMachineTest::SetUp(void) +{ + camDev_ = std::make_shared(TEST_DEVICE_ID, TEST_CAMERA_DH_ID_0); + stateMachine_ = std::make_shared(camDev_); +} + +void DCameraSourceStateMachineTest::TearDown(void) +{ + stateMachine_ = nullptr; + camDev_ = nullptr; +} + +/** + * @tc.name: dcamera_source_state_machine_test_001 + * @tc.desc: Verify source init state. + * @tc.type: FUNC + * @tc.require: AR000GK6MC + */ +HWTEST_F(DCameraSourceStateMachineTest, dcamera_source_state_machine_test_001, TestSize.Level1) +{ + DCameraSourceEvent event0(*camDev_, DCAMERA_EVENT_REGIST, g_registParam); + DCameraSourceEvent event1(*camDev_, DCAMERA_EVENT_UNREGIST, g_registParam); + stateMachine_ ->UpdateState(DCAMERA_STATE_INIT); + int32_t ret = stateMachine_ ->Execute(DCAMERA_EVENT_REGIST, event0); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_UNREGIST, event1); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_source_state_machine_test_002 + * @tc.desc: Verify source regist state. + * @tc.type: FUNC + * @tc.require: AR000GK6MC + */ +HWTEST_F(DCameraSourceStateMachineTest, dcamera_source_state_machine_test_002, TestSize.Level1) +{ + DCameraSourceEvent event0(*camDev_, DCAMERA_EVENT_REGIST, g_registParam); + DCameraSourceEvent event1(*camDev_, DCAMERA_EVENT_UNREGIST, g_registParam); + DCameraSourceEvent event2(*camDev_, DCAMERA_EVENT_OPEN, g_camIndex); + DCameraSourceEvent event3(*camDev_, DCAMERA_EVENT_CLOSE, g_camIndex); + DCameraSourceEvent event9(*camDev_, DCAMERA_EVENT_NOFIFY, g_camEvent); + stateMachine_ ->UpdateState(DCAMERA_STATE_INIT); + stateMachine_ ->UpdateState(DCAMERA_STATE_REGIST); + int32_t ret = stateMachine_ ->Execute(DCAMERA_EVENT_REGIST, event0); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_OPEN, event2); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_CLOSE, event3); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_NOFIFY, event9); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_UNREGIST, event1); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_source_state_machine_test_003 + * @tc.desc: Verify source open state. + * @tc.type: FUNC + * @tc.require: AR000GK6MD + */ +HWTEST_F(DCameraSourceStateMachineTest, dcamera_source_state_machine_test_003, TestSize.Level1) +{ + DCameraSourceEvent event0(*camDev_, DCAMERA_EVENT_REGIST, g_registParam); + DCameraSourceEvent event1(*camDev_, DCAMERA_EVENT_UNREGIST, g_registParam); + DCameraSourceEvent event2(*camDev_, DCAMERA_EVENT_OPEN, g_camIndex); + DCameraSourceEvent event3(*camDev_, DCAMERA_EVENT_CLOSE, g_camIndex); + DCameraSourceEvent event4(*camDev_, DCAMERA_EVENT_CONFIG_STREAMS, g_streamInfosSnap); + DCameraSourceEvent event5(*camDev_, DCAMERA_EVENT_RELEASE_STREAMS, g_streamIdSnap); + DCameraSourceEvent event8(*camDev_, DCAMERA_EVENT_UPDATE_SETTINGS, g_cameraSettingSnap); + DCameraSourceEvent event9(*camDev_, DCAMERA_EVENT_NOFIFY, g_camEvent); + stateMachine_ ->UpdateState(DCAMERA_STATE_INIT); + stateMachine_ ->UpdateState(DCAMERA_STATE_REGIST); + stateMachine_ ->UpdateState(DCAMERA_STATE_OPENED); + int32_t ret = stateMachine_ ->Execute(DCAMERA_EVENT_REGIST, event0); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_OPEN, event2); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_CONFIG_STREAMS, event4); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_RELEASE_STREAMS, event5); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_NOFIFY, event9); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_UPDATE_SETTINGS, event8); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_CLOSE, event3); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_UNREGIST, event1); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_source_state_machine_test_004 + * @tc.desc: Verify source config Stream state. + * @tc.type: FUNC + * @tc.require: AR000GK6ME + */ +HWTEST_F(DCameraSourceStateMachineTest, dcamera_source_state_machine_test_004, TestSize.Level1) +{ + DCameraSourceEvent event0(*camDev_, DCAMERA_EVENT_REGIST, g_registParam); + DCameraSourceEvent event1(*camDev_, DCAMERA_EVENT_UNREGIST, g_registParam); + DCameraSourceEvent event2(*camDev_, DCAMERA_EVENT_OPEN, g_camIndex); + DCameraSourceEvent event3(*camDev_, DCAMERA_EVENT_CLOSE, g_camIndex); + DCameraSourceEvent event4(*camDev_, DCAMERA_EVENT_CONFIG_STREAMS, g_streamInfosSnap); + DCameraSourceEvent event5(*camDev_, DCAMERA_EVENT_RELEASE_STREAMS, g_streamIdSnap); + DCameraSourceEvent event6(*camDev_, DCAMERA_EVENT_START_CAPTURE, g_captureInfoSnap); + DCameraSourceEvent event7(*camDev_, DCAMERA_EVENT_STOP_CAPTURE); + DCameraSourceEvent event8(*camDev_, DCAMERA_EVENT_UPDATE_SETTINGS, g_cameraSettingSnap); + DCameraSourceEvent event9(*camDev_, DCAMERA_EVENT_NOFIFY, g_camEvent); + stateMachine_ ->UpdateState(DCAMERA_STATE_INIT); + stateMachine_ ->UpdateState(DCAMERA_STATE_REGIST); + stateMachine_ ->UpdateState(DCAMERA_STATE_OPENED); + stateMachine_ ->UpdateState(DCAMERA_STATE_CONFIG_STREAM); + int32_t ret = stateMachine_ ->Execute(DCAMERA_EVENT_REGIST, event0); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_OPEN, event2); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_CONFIG_STREAMS, event4); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_START_CAPTURE, event6); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_NOFIFY, event9); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_UPDATE_SETTINGS, event8); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_STOP_CAPTURE, event7); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_RELEASE_STREAMS, event5); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_CLOSE, event3); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_UNREGIST, event1); + EXPECT_EQ(DCAMERA_OK, ret); +} + +/** + * @tc.name: dcamera_source_state_machine_test_005 + * @tc.desc: Verify source capture state. + * @tc.type: FUNC + * @tc.require: AR000GK6ME + */ +HWTEST_F(DCameraSourceStateMachineTest, dcamera_source_state_machine_test_005, TestSize.Level1) +{ + DCameraSourceEvent event0(*camDev_, DCAMERA_EVENT_REGIST, g_registParam); + DCameraSourceEvent event1(*camDev_, DCAMERA_EVENT_UNREGIST, g_registParam); + DCameraSourceEvent event2(*camDev_, DCAMERA_EVENT_OPEN, g_camIndex); + DCameraSourceEvent event3(*camDev_, DCAMERA_EVENT_CLOSE, g_camIndex); + DCameraSourceEvent event6(*camDev_, DCAMERA_EVENT_START_CAPTURE, g_captureInfoSnap); + DCameraSourceEvent event7(*camDev_, DCAMERA_EVENT_STOP_CAPTURE); + DCameraSourceEvent event8(*camDev_, DCAMERA_EVENT_UPDATE_SETTINGS, g_cameraSettingSnap); + DCameraSourceEvent event9(*camDev_, DCAMERA_EVENT_NOFIFY, g_camEvent); + stateMachine_ ->UpdateState(DCAMERA_STATE_INIT); + stateMachine_ ->UpdateState(DCAMERA_STATE_REGIST); + stateMachine_ ->UpdateState(DCAMERA_STATE_OPENED); + stateMachine_ ->UpdateState(DCAMERA_STATE_CONFIG_STREAM); + stateMachine_ ->UpdateState(DCAMERA_STATE_CAPTURE); + int32_t ret = stateMachine_ ->Execute(DCAMERA_EVENT_REGIST, event0); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_OPEN, event2); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_START_CAPTURE, event6); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_NOFIFY, event9); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_UPDATE_SETTINGS, event8); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_STOP_CAPTURE, event7); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_CLOSE, event3); + EXPECT_EQ(DCAMERA_OK, ret); + + ret = stateMachine_ ->Execute(DCAMERA_EVENT_UNREGIST, event1); + EXPECT_EQ(DCAMERA_OK, ret); +} +} +} \ No newline at end of file diff --git a/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/mock_dcamera_source_dev.h b/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/mock_dcamera_source_dev.h new file mode 100644 index 0000000000000000000000000000000000000000..d59341c03008a0bf0948ebc4fdd7a37f79d7424c --- /dev/null +++ b/services/cameraservice/sourceservice/test/unittest/common/distributedcameramgr/mock_dcamera_source_dev.h @@ -0,0 +1,84 @@ +/* + * 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_DISTRIBUTED_CAMERA_MOCKSOURCE_DEV_H +#define OHOS_DISTRIBUTED_CAMERA_MOCKSOURCE_DEV_H + +#include "dcamera_source_dev.h" + +#include "distributed_camera_errno.h" +#include "idistributed_camera_source.h" + +namespace OHOS { +namespace DistributedHardware { +class MockDCameraSourceDev : public DCameraSourceDev { +public: + MockDCameraSourceDev(std::string devId, std::string dhId) : DCameraSourceDev(devId, dhId, stateLisener_) {}; + ~MockDCameraSourceDev() = default; + + int32_t ExecuteRegister(std::shared_ptr& param) + { + return DCAMERA_OK; + } + int32_t ExecuteUnRegister(std::shared_ptr& param) + { + return DCAMERA_OK; + } + int32_t ExecuteOpenCamera() + { + return DCAMERA_OK; + } + int32_t ExecuteCloseCamera() + { + return DCAMERA_OK; + } + int32_t ExecuteConfigStreams(std::vector>& streamInfos) + { + return DCAMERA_OK; + } + int32_t ExecuteReleaseStreams(std::vector& streamIds, bool& isAllRelease) + { + return DCAMERA_OK; + } + int32_t ExecuteReleaseAllStreams() + { + return DCAMERA_OK; + } + int32_t ExecuteStartCapture(std::vector>& captureInfos) + { + return DCAMERA_OK; + } + int32_t ExecuteStopCapture() + { + return DCAMERA_OK; + } + int32_t ExecuteUpdateSettings(std::vector>& settings) + { + return DCAMERA_OK; + } + int32_t ExecuteCameraEventNotify(std::shared_ptr& events) + { + return DCAMERA_OK; + } + +private: + std::string devId_; + std::string dhId_; + std::shared_ptr stateLisener_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/channel/BUILD.gn b/services/channel/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fa955e46deb62fcba6fafc44161e4416181ac764 --- /dev/null +++ b/services/channel/BUILD.gn @@ -0,0 +1,62 @@ +# 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. + +import("//build/ohos.gni") +import("//build/ohos_var.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_channel") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include", + ] + + include_dirs += [ + "include", + "${common_path}/include/constants", + "${common_path}/include/utils", + ] + + sources = [ + "src/dcamera_channel_sink_impl.cpp", + "src/dcamera_channel_source_impl.cpp", + "src/dcamera_softbus_adapter.cpp", + "src/dcamera_softbus_session.cpp", + ] + + deps = [ + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "//utils/native/base:utils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dcamerachannel\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "eventhandler:libeventhandler", + "dsoftbus_standard:softbus_client", + "hiviewdfx_hilog_native:libhilog", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} \ No newline at end of file diff --git a/services/channel/include/dcamera_channel_sink_impl.h b/services/channel/include/dcamera_channel_sink_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..d276d119d3812e88e9d09aa7b412c8c6a4f74e52 --- /dev/null +++ b/services/channel/include/dcamera_channel_sink_impl.h @@ -0,0 +1,46 @@ +/* + * 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_DCAMERA_CHANNEL_SINK_IMPL_H +#define OHOS_DCAMERA_CHANNEL_SINK_IMPL_H + +#include "icamera_channel.h" + +#include "dcamera_softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraChannelSinkImpl : public ICameraChannel { +public: + DCameraChannelSinkImpl(); + ~DCameraChannelSinkImpl(); + int32_t OpenSession() override; + int32_t CloseSession() override; + int32_t CreateSession(std::vector& camIndexs, std::string sessionFlag, DCameraSessionMode sessionMode, + std::shared_ptr& listener) override; + int32_t ReleaseSession() override; + int32_t SendData(std::shared_ptr& buffer) override; + +private: + std::shared_ptr listener_; + std::vector camIndexs_; + std::shared_ptr softbusSession_; + std::string mySessionName_; + DCameraSessionMode mode_; + const std::string SESSION_HEAD = "DBinder.ohos.dhardware.dcamera_"; +}; +} +} +#endif \ No newline at end of file diff --git a/services/channel/include/dcamera_channel_source_impl.h b/services/channel/include/dcamera_channel_source_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..f12b5309aec6432f3b62a96a09192e63ca61af9f --- /dev/null +++ b/services/channel/include/dcamera_channel_source_impl.h @@ -0,0 +1,46 @@ +/* + * 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_DCAMERA_CHANNEL_SOURCE_IMPL_H +#define OHOS_DCAMERA_CHANNEL_SOURCE_IMPL_H + +#include "icamera_channel.h" + +#include "dcamera_softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraChannelSourceImpl : public ICameraChannel { +public: + DCameraChannelSourceImpl(); + ~DCameraChannelSourceImpl(); + int32_t OpenSession() override; + int32_t CloseSession() override; + int32_t CreateSession(std::vector& camIndexs, std::string sessionFlag, DCameraSessionMode sessionMode, + std::shared_ptr& listener) override; + int32_t ReleaseSession() override; + int32_t SendData(std::shared_ptr& buffer) override; + +private: + std::shared_ptr listener_; + std::vector camIndexs_; + std::vector> softbusSessions_; + std::string mySessionName_; + DCameraSessionMode mode_; + const std::string SESSION_HEAD = "DBinder.ohos.dhardware.dcamera_"; +}; +} +} +#endif \ No newline at end of file diff --git a/services/channel/include/dcamera_softbus_adapter.h b/services/channel/include/dcamera_softbus_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..79c396043452b028c5e6394a40d31044bea29267 --- /dev/null +++ b/services/channel/include/dcamera_softbus_adapter.h @@ -0,0 +1,86 @@ +/* + * 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_DCAMERA_SOFTBUS_ADAPTER_H +#define OHOS_DCAMERA_SOFTBUS_ADAPTER_H + +#include +#include +#include + +#include "session.h" +#include "single_instance.h" + +#include "dcamera_softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DCAMERA_CHANNLE_ROLE_SOURCE = 0, + DCAMERA_CHANNLE_ROLE_SINK = 1, +} DCAMERA_CHANNEL_ROLE; + +class DCameraSoftbusAdapter { +DECLARE_SINGLE_INSTANCE_BASE(DCameraSoftbusAdapter); +public: + int32_t CreateSoftbusSessionServer(std::string sessionName, DCAMERA_CHANNEL_ROLE role); + int32_t DestroySoftbusSessionServer(std::string sessionName); + int32_t OpenSoftbusSession(std::string mySessName, std::string peerSessName, int32_t sessionMode, + std::string peerDevId); + int32_t CloseSoftbusSession(int32_t sessionId); + int32_t SendSofbusBytes(int32_t sessionId, std::shared_ptr& buffer); + int32_t SendSofbusStream(int32_t sessionId, std::shared_ptr& buffer); + int32_t GetLocalNetworkId(std::string& myDevId); + + int32_t OnSourceSessionOpened(int32_t sessionId, int32_t result); + void OnSourceSessionClosed(int32_t sessionId); + void OnSourceBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + void OnSourceMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen); + void OnSourceStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param); + + int32_t OnSinkSessionOpened(int32_t sessionId, int32_t result); + void OnSinkSessionClosed(int32_t sessionId); + void OnSinkBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + void OnSinkMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen); + void OnSinkStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param); + +public: + std::map> sourceSessions_; + std::map> sinkSessions_; + +private: + DCameraSoftbusAdapter(); + ~DCameraSoftbusAdapter(); + + int32_t DCameraSoftbusSourceGetSession(int32_t sessionId, std::shared_ptr& session); + int32_t DCameraSoftbusSinkGetSession(int32_t sessionId, std::shared_ptr& session); + int32_t DCameraSoftbusGetSessionById(int32_t sessionId, std::shared_ptr& session); + +private: + std::mutex optLock_; + const string PKG_NAME = "DBinderBus_" + std::to_string(getpid()); + static const uint32_t DCAMERA_SESSION_NAME_MAX_LEN = 128; + map sessListeners_; + std::map sessionTotal_; + static const uint32_t DCAMERA_LINK_TYPE_MAX = 4; + static const uint32_t DCAMERA_LINK_TYPE_INDEX_2 = 2; + std::mutex idMapLock_; + std::map> sessionIdMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/channel/include/dcamera_softbus_session.h b/services/channel/include/dcamera_softbus_session.h new file mode 100644 index 0000000000000000000000000000000000000000..7d0934b0fd5908eb5e3946f16bac8b75fb5dbf41 --- /dev/null +++ b/services/channel/include/dcamera_softbus_session.h @@ -0,0 +1,120 @@ +/* + * 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_DCAMERA_SOFTBUS_SESSION_H +#define OHOS_DCAMERA_SOFTBUS_SESSION_H + +#include "event_handler.h" +#include + +#include "icamera_channel.h" +#include "icamera_channel_listener.h" + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DCAMERA_SOFTBUS_STATE_CLOSED = 0, + DCAMERA_SOFTBUS_STATE_OPENED = 1, +} DCameraSofbutState; + +class DCameraSoftbusSession { +public: + DCameraSoftbusSession(); + DCameraSoftbusSession(std::string myDevId, std::string mySessionName, std::string peerDevId, + std::string peerSessionName, std::shared_ptr listener, DCameraSessionMode mode); + ~DCameraSoftbusSession(); + int32_t OpenSession(); + int32_t CloseSession(); + int32_t OnSessionOpend(int32_t sessionId, int32_t result); + int32_t OnSessionClose(int32_t sessionId); + int32_t OnDataReceived(std::shared_ptr& buffer); + int32_t SendData(DCameraSessionMode mode, std::shared_ptr& buffer); + std::string GetPeerDevId(); + std::string GetPeerSessionName(); + std::string GetMySessionName(); + +private: + struct SessionDataHeader { + uint16_t version; + uint8_t fragFlag; + uint32_t dataType; + uint32_t seqNum; + uint32_t totalLen; + uint16_t subSeq; + uint32_t dataLen; + }; + + using DCameraSendFuc = int32_t (DCameraSoftbusSession::*)(std::shared_ptr& buffer); + int32_t SendBytes(std::shared_ptr& buffer); + int32_t SendStream(std::shared_ptr& buffer); + void DealRecvData(std::shared_ptr& buffer); + void PackRecvData(std::shared_ptr& buffer); + void AssembleNoFrag(std::shared_ptr& buffer, SessionDataHeader& headerPara); + void AssembleFrag(std::shared_ptr& buffer, SessionDataHeader& headerPara); + int32_t CheckUnPackBuffer(SessionDataHeader& headerPara); + void GetFragDataLen(uint8_t *ptrPacket, SessionDataHeader& headerPara); + int32_t UnPackSendData(std::shared_ptr& buffer, DCameraSendFuc memberFunc); + void MakeFragDataHeader(const SessionDataHeader& headPara, uint8_t *header, uint32_t len); + void PostData(std::shared_ptr& buffer); + uint16_t U16Get(const uint8_t *ptr); + uint32_t U32Get(const uint8_t *ptr); + void ResetAssembleFrag(); + + enum { + FRAG_NULL = 0, + FRAG_START, + FRAG_MID, + FRAG_END, + FRAG_START_END, + }; + + static const uint32_t BINARY_DATA_MAX_TOTAL_LEN = 100 * 1024 * 1024; + static const uint32_t BINARY_DATA_MAX_LEN = 1000 * 1024; + static const uint32_t BINARY_DATA_PACKET_MAX_LEN = 62 * 1024; + static const uint16_t PROTOCOL_VERSION = 1; + static const uint16_t HEADER_UINT8_NUM = 1; + static const uint16_t HEADER_UINT16_NUM = 2; + static const uint16_t HEADER_UINT32_NUM = 4; + static const uint16_t BINARY_HEADER_FRAG_LEN = 21; + + static const uint32_t BINARY_HEADER_FRAG_OFFSET = 2; + static const uint32_t BINARY_HEADER_DATATYPE_OFFSET = 3; + static const uint32_t BINARY_HEADER_SEQNUM_OFFSET = 7; + static const uint32_t BINARY_HEADER_TOTALLEN_OFFSET = 11; + static const uint32_t BINARY_HEADER_SUBSEQ_OFFSET = 15; + static const uint32_t BINARY_HEADER_DATALEN_OFFSET = 17; + + std::shared_ptr packBuffer_; + bool isWaiting_; + uint32_t nowSeq_; + uint32_t nowSubSeq_; + uint32_t offset_; + uint32_t totalLen_; + +private: + std::string myDevId_; + std::string mySessionName_; + std::string peerDevId_; + std::string peerSessionName_; + std::shared_ptr listener_; + int32_t sessionId_; + DCameraSofbutState state_; + DCameraSessionMode mode_; + std::map sendFuncMap_; + std::shared_ptr eventHandler_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/channel/include/icamera_channel.h b/services/channel/include/icamera_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..e05b7a9c975c6dc4da408e712afb7795b80b9af6 --- /dev/null +++ b/services/channel/include/icamera_channel.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_ICAMERA_CHANNEL_H +#define OHOS_ICAMERA_CHANNEL_H + +#include "icamera_channel_listener.h" +#include "data_buffer.h" +#include "dcamera_index.h" + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DCAMERA_SESSION_MODE_CTRL = 0, + DCAMERA_SESSION_MODE_VIDEO = 1, + DCAMERA_SESSION_MODE_JPEG = 2, +} DCameraSessionMode; + +class ICameraChannel { +public: + virtual ~ICameraChannel() = default; + + virtual int32_t OpenSession() = 0; + virtual int32_t CloseSession() = 0; + virtual int32_t CreateSession(std::vector& camIndexs, std::string sessionFlag, + DCameraSessionMode sessionMode, std::shared_ptr& listener) = 0; + virtual int32_t ReleaseSession(); + virtual int32_t SendData(std::shared_ptr& buffer) = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/channel/include/icamera_channel_listener.h b/services/channel/include/icamera_channel_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..a1cd225482d2886716a37765bcc67ced60a92014 --- /dev/null +++ b/services/channel/include/icamera_channel_listener.h @@ -0,0 +1,43 @@ +/* + * 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_ICAMERA_CHANNEL_LISTENER_H +#define OHOS_ICAMERA_CHANNEL_LISTENER_H + +#include +#include +#include + +#include "data_buffer.h" + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DCAMERA_CHANNEL_STATE_DISCONNECTED = 0, + DCAMERA_CHANNEL_STATE_CONNECTING = 1, + DCAMERA_CHANNEL_STATE_CONNECTED = 2, +} DCameraChannelState; + +class ICameraChannelListener { +public: + virtual ~ICameraChannelListener() = default; + + virtual void OnSessionState(int32_t state) = 0; + virtual void OnSessionError(int32_t eventType, int32_t eventReason, std::string detail) = 0; + virtual void OnDataReceived(std::vector>& buffers) = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/channel/src/dcamera_channel_sink_impl.cpp b/services/channel/src/dcamera_channel_sink_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..565c547365f073fabb4714a552dbf15dde26a3f1 --- /dev/null +++ b/services/channel/src/dcamera_channel_sink_impl.cpp @@ -0,0 +1,126 @@ +/* + * 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 "dcamera_channel_sink_impl.h" + +#include "dcamera_softbus_adapter.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraChannelSinkImpl::DCameraChannelSinkImpl() +{ + softbusSession_ = nullptr; +} + +DCameraChannelSinkImpl::~DCameraChannelSinkImpl() +{ +} + +int32_t DCameraChannelSinkImpl::OpenSession() +{ + DHLOGI("DCameraChannelSinkImpl OpenSession name: %s", mySessionName_.c_str()); + if (softbusSession_ == nullptr) { + DHLOGE("DCameraChannelSinkImpl OpenSession %s failed", mySessionName_.c_str()); + return DCAMERA_BAD_OPERATE; + } + int32_t ret = softbusSession_->OpenSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraChannelSinkImpl OpenSession %s ret: %d", mySessionName_.c_str(), ret); + } + + return ret; +} + +int32_t DCameraChannelSinkImpl::CloseSession() +{ + DHLOGI("DCameraChannelSinkImpl CloseSession name: %s", mySessionName_.c_str()); + if (softbusSession_ == nullptr) { + DHLOGE("DCameraChannelSinkImpl CloseSession %s failed", mySessionName_.c_str()); + return DCAMERA_BAD_OPERATE; + } + int32_t ret = softbusSession_->CloseSession(); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraChannelSinkImpl CloseSession %s ret: %d", mySessionName_.c_str(), ret); + } + + return ret; +} + +int32_t DCameraChannelSinkImpl::CreateSession(std::vector& camIndexs, std::string sessionFlag, + DCameraSessionMode sessionMode, std::shared_ptr& listener) +{ + if (camIndexs.size() > DCAMERA_MAX_NUM || listener == nullptr) { + return DCAMERA_BAD_VALUE; + } + if (softbusSession_ != nullptr) { + DHLOGI("DCameraChannelSinkImpl session has already create %s", sessionFlag.c_str()); + return DCAMERA_OK; + } + camIndexs_.assign(camIndexs.begin(), camIndexs.end()); + listener_ = listener; + mySessionName_ = SESSION_HEAD + camIndexs[0].dhId_ + std::string("_") + sessionFlag; + mode_ = sessionMode; + std::string myDevId; + DCameraSoftbusAdapter::GetInstance().GetLocalNetworkId(myDevId); + DHLOGI("DCameraChannelSinkImpl session create name: %s devId: %s", mySessionName_.c_str(), + GetAnonyString(myDevId).c_str()); + int32_t ret = DCameraSoftbusAdapter::GetInstance().CreateSoftbusSessionServer(mySessionName_, + DCAMERA_CHANNLE_ROLE_SINK); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraChannelSinkImpl CreateSession %s failed, ret: %d", mySessionName_.c_str(), ret); + return ret; + } + std::string peerDevId = camIndexs[0].devId_; + std::string peerSessionName = SESSION_HEAD + sessionFlag; + softbusSession_ = std::make_shared(myDevId, mySessionName_, peerDevId, peerSessionName, + listener, sessionMode); + DCameraSoftbusAdapter::GetInstance().sinkSessions_[mySessionName_] = softbusSession_; + return DCAMERA_OK; +} + +int32_t DCameraChannelSinkImpl::ReleaseSession() +{ + DHLOGI("DCameraChannelSinkImpl ReleaseSession name: %s", mySessionName_.c_str()); + if (softbusSession_ == nullptr) { + return DCAMERA_OK; + } + DCameraSoftbusAdapter::GetInstance().sourceSessions_.erase(softbusSession_->GetMySessionName()); + int32_t ret = DCameraSoftbusAdapter::GetInstance().DestroySoftbusSessionServer(softbusSession_->GetMySessionName()); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraChannelSinkImpl ReleaseSession %s failed, ret: %d", mySessionName_.c_str(), ret); + } + softbusSession_ = nullptr; + return ret; +} + +int32_t DCameraChannelSinkImpl::SendData(std::shared_ptr& buffer) +{ + if (softbusSession_ == nullptr) { + DHLOGE("DCameraChannelSinkImpl SendData %s failed", mySessionName_.c_str()); + return DCAMERA_BAD_OPERATE; + } + int32_t ret = softbusSession_->SendData(mode_, buffer); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraChannelSinkImpl SendData %s failed, ret: %d", mySessionName_.c_str(), ret); + } + return ret; +} +} +} \ No newline at end of file diff --git a/services/channel/src/dcamera_channel_source_impl.cpp b/services/channel/src/dcamera_channel_source_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3fb7115ec6e8fb0409714b21dddd5f7c64dbbe2 --- /dev/null +++ b/services/channel/src/dcamera_channel_source_impl.cpp @@ -0,0 +1,145 @@ +/* + * 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 "dcamera_channel_source_impl.h" + +#include "dcamera_softbus_adapter.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraChannelSourceImpl::DCameraChannelSourceImpl() +{ +} + +DCameraChannelSourceImpl::~DCameraChannelSourceImpl() +{ +} + +int32_t DCameraChannelSourceImpl::OpenSession() +{ + DHLOGI("DCameraChannelSourceImpl OpenSession name: %s", mySessionName_.c_str()); + if (softbusSessions_.empty()) { + DHLOGE("DCameraChannelSourceImpl OpenSession %s failed", mySessionName_.c_str()); + return DCAMERA_BAD_OPERATE; + } + int32_t ret = DCAMERA_OK; + for (auto iter = softbusSessions_.begin(); iter != softbusSessions_.end(); iter++) { + int32_t retOpen = (*iter)->OpenSession(); + if (retOpen != DCAMERA_OK) { + DHLOGE("DCameraChannelSourceImpl OpenSession %s failed, ret: %d", mySessionName_.c_str(), retOpen); + ret = DCAMERA_BAD_OPERATE; + break; + } + } + + if (ret != DCAMERA_OK) { + CloseSession(); + } + + return ret; +} + +int32_t DCameraChannelSourceImpl::CloseSession() +{ + DHLOGI("DCameraChannelSourceImpl CloseSession name: %s", mySessionName_.c_str()); + if (softbusSessions_.empty()) { + DHLOGE("DCameraChannelSourceImpl CloseSession %s failed", mySessionName_.c_str()); + return DCAMERA_BAD_OPERATE; + } + int32_t ret = DCAMERA_OK; + for (auto iter = softbusSessions_.begin(); iter != softbusSessions_.end(); iter++) { + int32_t retOpen = (*iter)->CloseSession(); + if (retOpen != DCAMERA_OK) { + DHLOGE("DCameraChannelSourceImpl CloseSession %s failed, ret: %d", mySessionName_.c_str(), retOpen); + ret = DCAMERA_BAD_OPERATE; + } + } + + return ret; +} + +int32_t DCameraChannelSourceImpl::CreateSession(std::vector& camIndexs, std::string sessionFlag, + DCameraSessionMode sessionMode, std::shared_ptr& listener) +{ + if (camIndexs.size() > DCAMERA_MAX_NUM || listener == nullptr) { + return DCAMERA_BAD_VALUE; + } + if (!softbusSessions_.empty()) { + DHLOGI("DCameraChannelSourceImpl session has already create %s", sessionFlag.c_str()); + return DCAMERA_OK; + } + camIndexs_.assign(camIndexs.begin(), camIndexs.end()); + listener_ = listener; + mySessionName_ = SESSION_HEAD + sessionFlag; + mode_ = sessionMode; + std::string myDevId; + DCameraSoftbusAdapter::GetInstance().GetLocalNetworkId(myDevId); + DHLOGI("DCameraChannelSourceImpl session create name: %s devId: %s", mySessionName_.c_str(), + GetAnonyString(myDevId).c_str()); + int32_t ret = DCameraSoftbusAdapter::GetInstance().CreateSoftbusSessionServer(mySessionName_, + DCAMERA_CHANNLE_ROLE_SOURCE); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraChannelSourceImpl CreateSession %s failed, ret: %d", mySessionName_.c_str(), ret); + return ret; + } + for (auto iter = camIndexs.begin(); iter != camIndexs.end(); iter++) { + std::string peerDevId = (*iter).devId_; + std::string peerSessionName = SESSION_HEAD + (*iter).dhId_ + std::string("_") + sessionFlag; + std::shared_ptr softbusSess = std::make_shared(myDevId, + mySessionName_, peerDevId, peerSessionName, listener, sessionMode); + softbusSessions_.push_back(softbusSess); + DCameraSoftbusAdapter::GetInstance().sourceSessions_[peerDevId + peerSessionName] = softbusSess; + } + return DCAMERA_OK; +} + +int32_t DCameraChannelSourceImpl::ReleaseSession() +{ + DHLOGI("DCameraChannelSourceImpl ReleaseSession name: %s", mySessionName_.c_str()); + for (auto iter = softbusSessions_.begin(); iter != softbusSessions_.end(); iter++) { + std::string sessKey = (*iter)->GetPeerDevId() + (*iter)->GetPeerSessionName(); + DCameraSoftbusAdapter::GetInstance().sourceSessions_.erase(sessKey); + } + std::vector>().swap(softbusSessions_); + int32_t ret = DCameraSoftbusAdapter::GetInstance().DestroySoftbusSessionServer(mySessionName_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraChannelSourceImpl ReleaseSession %s failed, ret: %d", mySessionName_.c_str(), ret); + } + return ret; +} + +int32_t DCameraChannelSourceImpl::SendData(std::shared_ptr& buffer) +{ + if (softbusSessions_.empty()) { + DHLOGE("DCameraChannelSourceImpl SendData %s failed", mySessionName_.c_str()); + return DCAMERA_BAD_OPERATE; + } + int32_t ret = DCAMERA_OK; + for (auto iter = softbusSessions_.begin(); iter != softbusSessions_.end(); iter++) { + int32_t retSend = (*iter)->SendData(mode_, buffer); + if (retSend != DCAMERA_OK) { + DHLOGE("DCameraChannelSourceImpl SendData %s failed, ret: %d", mySessionName_.c_str(), retSend); + ret = DCAMERA_BAD_OPERATE; + } + } + return ret; +} +} +} \ No newline at end of file diff --git a/services/channel/src/dcamera_softbus_adapter.cpp b/services/channel/src/dcamera_softbus_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f7bf79635dc7599a48584466541dcd9e5d091844 --- /dev/null +++ b/services/channel/src/dcamera_softbus_adapter.cpp @@ -0,0 +1,488 @@ +/* + * 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 "dcamera_softbus_adapter.h" + +#include + +#include "softbus_bus_center.h" +#include "softbus_common.h" + +#include "anonymous_string.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DCameraSoftbusAdapter); + +static int32_t DCameraSourceOnSessionOpend(int32_t sessionId, int32_t result) +{ + return DCameraSoftbusAdapter::GetInstance().OnSourceSessionOpened(sessionId, result); +} + +static void DCameraSourceOnSessionClosed(int32_t sessionId) +{ + DCameraSoftbusAdapter::GetInstance().OnSourceSessionClosed(sessionId); + return; +} + +static void DCameraSourceOnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + DCameraSoftbusAdapter::GetInstance().OnSourceBytesReceived(sessionId, data, dataLen); + return; +} + +static void DCameraSourceOnMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + DCameraSoftbusAdapter::GetInstance().OnSourceMessageReceived(sessionId, data, dataLen); + return; +} + +static void DCameraSourceOnStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param) +{ + DCameraSoftbusAdapter::GetInstance().OnSourceStreamReceived(sessionId, data, ext, param); + return; +} + +static int32_t DCameraSinkOnSessionOpend(int32_t sessionId, int32_t result) +{ + return DCameraSoftbusAdapter::GetInstance().OnSinkSessionOpened(sessionId, result); +} + +static void DCameraSinkOnSessionClosed(int32_t sessionId) +{ + DCameraSoftbusAdapter::GetInstance().OnSinkSessionClosed(sessionId); + return; +} + +static void DCameraSinkOnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + DCameraSoftbusAdapter::GetInstance().OnSinkBytesReceived(sessionId, data, dataLen); + return; +} + +static void DCameraSinkOnMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + DCameraSoftbusAdapter::GetInstance().OnSinkMessageReceived(sessionId, data, dataLen); + return; +} + +static void DCameraSinkOnStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param) +{ + DCameraSoftbusAdapter::GetInstance().OnSinkStreamReceived(sessionId, data, ext, param); + return; +} + +DCameraSoftbusAdapter::DCameraSoftbusAdapter() +{ + ISessionListener sourceListener; + sourceListener.OnSessionOpened = DCameraSourceOnSessionOpend; + sourceListener.OnSessionClosed = DCameraSourceOnSessionClosed; + sourceListener.OnBytesReceived = DCameraSourceOnBytesReceived; + sourceListener.OnMessageReceived = DCameraSourceOnMessageReceived; + sourceListener.OnStreamReceived = DCameraSourceOnStreamReceived; + sessListeners_[DCAMERA_CHANNLE_ROLE_SOURCE] = sourceListener; + + ISessionListener sinkListener; + sinkListener.OnSessionOpened = DCameraSinkOnSessionOpend; + sinkListener.OnSessionClosed = DCameraSinkOnSessionClosed; + sinkListener.OnBytesReceived = DCameraSinkOnBytesReceived; + sinkListener.OnMessageReceived = DCameraSinkOnMessageReceived; + sinkListener.OnStreamReceived = DCameraSinkOnStreamReceived; + sessListeners_[DCAMERA_CHANNLE_ROLE_SINK] = sinkListener; +} + +DCameraSoftbusAdapter::~DCameraSoftbusAdapter() +{ +} + +int32_t DCameraSoftbusAdapter::CreateSoftbusSessionServer(std::string sessionName, DCAMERA_CHANNEL_ROLE role) +{ + std::lock_guard autoLock(optLock_); + if (sessionTotal_.find(sessionName) != sessionTotal_.end()) { + sessionTotal_[sessionName]++; + DHLOGI("DCameraSoftbusAdapter sessionName already exist %s totalnum: %d", sessionName.c_str(), + sessionTotal_[sessionName]); + return DCAMERA_OK; + } + + int32_t ret = CreateSessionServer(PKG_NAME.c_str(), sessionName.c_str(), &sessListeners_[role]); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter CreateSessionServer failed, ret: %d", ret); + return ret; + } + sessionTotal_[sessionName]++; + DHLOGI("DCameraSoftbusAdapter sessionName create %s totalnum: %d", sessionName.c_str(), + sessionTotal_[sessionName]); + return DCAMERA_OK; +} + +int32_t DCameraSoftbusAdapter::DestroySoftbusSessionServer(std::string sessionName) +{ + std::lock_guard autoLock(optLock_); + if (sessionTotal_.find(sessionName) == sessionTotal_.end()) { + DHLOGI("DCameraSoftbusAdapter sessionName already destroy %s", sessionName.c_str()); + return DCAMERA_OK; + } + + sessionTotal_[sessionName]--; + DHLOGI("DCameraSoftbusAdapter sessionName destroy %s totalnum: %d", sessionName.c_str(), + sessionTotal_[sessionName]); + uint32_t total_ = sessionTotal_[sessionName]; + if (total_ == 0) { + RemoveSessionServer(PKG_NAME.c_str(), sessionName.c_str()); + sessionTotal_.erase(sessionName); + } + return DCAMERA_OK; +} + +int32_t DCameraSoftbusAdapter::OpenSoftbusSession(std::string mySessName, std::string peerSessName, + int32_t sessionMode, std::string peerDevId) +{ + uint32_t dataType = TYPE_STREAM; + uint32_t streamType = -1; + switch (sessionMode) { + case DCAMERA_SESSION_MODE_CTRL: { + dataType = TYPE_BYTES; + streamType = -1; + break; + } + case DCAMERA_SESSION_MODE_VIDEO: + case DCAMERA_SESSION_MODE_JPEG: { + dataType = TYPE_STREAM; + streamType = RAW_STREAM; + break; + } + default: + DHLOGE("DCameraSoftbusAdapter OpenSoftbusSession bad sessionMode %d", sessionMode); + return DCAMERA_BAD_VALUE; + } + SessionAttribute attr = { 0 }; + attr.dataType = static_cast(dataType); + attr.linkTypeNum = DCAMERA_LINK_TYPE_MAX; + LinkType linkTypeList[DCAMERA_LINK_TYPE_MAX] = { + LINK_TYPE_WIFI_P2P, + LINK_TYPE_WIFI_WLAN_5G, + LINK_TYPE_WIFI_WLAN_2G, + LINK_TYPE_BR, + }; + + if (dataType == TYPE_BYTES) { + linkTypeList[0] = LINK_TYPE_WIFI_WLAN_2G; + linkTypeList[DCAMERA_LINK_TYPE_INDEX_2] = LINK_TYPE_WIFI_P2P; + } + int32_t ret = memcpy_s(attr.linkType, DCAMERA_LINK_TYPE_MAX * sizeof(LinkType), linkTypeList, + DCAMERA_LINK_TYPE_MAX * sizeof(LinkType)); + if (ret != EOK) { + DHLOGE("DCameraSoftbusAdapter OpenSoftbusSession memcpy_s failed %d", ret); + return DCAMERA_BAD_VALUE; + } + attr.attr.streamAttr.streamType = (StreamType)streamType; + int32_t sessionId = OpenSession(mySessName.c_str(), peerSessName.c_str(), peerDevId.c_str(), "0", &attr); + if (sessionId < 0) { + DHLOGE("DCameraSoftbusAdapter OpenSoftbusSession failed %d", sessionId); + return DCAMERA_BAD_OPERATE; + } + return DCAMERA_OK; +} + +int32_t DCameraSoftbusAdapter::CloseSoftbusSession(int32_t sessionId) +{ + DHLOGI("close softbus sessionId: %d", sessionId); + CloseSession(sessionId); + { + std::lock_guard autoLock(idMapLock_); + sessionIdMap_.erase(sessionId); + } + DHLOGI("close softbus sessionId: %d end", sessionId); + return DCAMERA_OK; +} + +int32_t DCameraSoftbusAdapter::SendSofbusBytes(int32_t sessionId, std::shared_ptr& buffer) +{ + return SendBytes(sessionId, buffer->Data(), buffer->Size()); +} + +int32_t DCameraSoftbusAdapter::SendSofbusStream(int32_t sessionId, std::shared_ptr& buffer) +{ + StreamData streamData = { (char *)buffer->Data(), buffer->Size() }; + StreamData ext = { 0 }; + StreamFrameInfo param = { 0 }; + return SendStream(sessionId, &streamData, &ext, ¶m); +} + +int32_t DCameraSoftbusAdapter::DCameraSoftbusGetSessionById(int32_t sessionId, + std::shared_ptr& session) +{ + DHLOGI("get softbus session by sessionId: %d", sessionId); + std::lock_guard autoLock(idMapLock_); + auto iter = sessionIdMap_.find(sessionId); + if (iter == sessionIdMap_.end()) { + DHLOGE("get softbus session by id not find session %d", sessionId); + return DCAMERA_NOT_FOUND; + } + session = iter->second; + return DCAMERA_OK; +} + +int32_t DCameraSoftbusAdapter::DCameraSoftbusSourceGetSession(int32_t sessionId, + std::shared_ptr& session) +{ + char peerSessionName[DCAMERA_SESSION_NAME_MAX_LEN] = ""; + char peerDevId[NETWORK_ID_BUF_LEN] = ""; + int32_t ret = GetPeerSessionName(sessionId, peerSessionName, sizeof(peerSessionName)); + if (ret != DCAMERA_OK) { + DHLOGI("DCameraSoftbusAdapter DCameraSoftbusSourceGetSession sessionId: %d GetPeerSessionName failed: %d", + sessionId, ret); + return ret; + } + + ret = GetPeerDeviceId(sessionId, peerDevId, sizeof(peerDevId)); + if (ret != DCAMERA_OK) { + DHLOGI("DCameraSoftbusAdapter DCameraSoftbusSourceGetSession sessionId: %d GetPeerDeviceId failed: %d", + sessionId, ret); + return ret; + } + + auto iter = sourceSessions_.find(std::string(peerDevId) + std::string(peerSessionName)); + if (iter == sourceSessions_.end()) { + DHLOGE("DCameraSoftbusAdapter DCameraSoftbusSourceGetSession not find session %d", sessionId); + return DCAMERA_NOT_FOUND; + } + session = iter->second; + return DCAMERA_OK; +} + +int32_t DCameraSoftbusAdapter::OnSourceSessionOpened(int32_t sessionId, int32_t result) +{ + DHLOGI("DCameraSoftbusAdapter OnSourceSessionOpened sessionId: %d, result: %d", sessionId, result); + std::shared_ptr session = nullptr; + int32_t ret = DCameraSoftbusSourceGetSession(sessionId, session); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSourceSessionOpened not find session %d", sessionId); + return DCAMERA_NOT_FOUND; + } + + ret = session->OnSessionOpend(sessionId, result); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSourceSessionOpened failed %d sessionId: %d", ret, sessionId); + } else { + std::lock_guard autoLock(idMapLock_); + sessionIdMap_.emplace(sessionId, session); + } + DHLOGI("DCameraSoftbusAdapter OnSourceSessionOpened sessionId: %d, result: %d end", sessionId, result); + return ret; +} + +void DCameraSoftbusAdapter::OnSourceSessionClosed(int32_t sessionId) +{ + DHLOGI("DCameraSoftbusAdapter OnSourceSessionClosed sessionId: %d", sessionId); + std::shared_ptr session = nullptr; + int32_t ret = DCameraSoftbusGetSessionById(sessionId, session); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSourceSessionClosed not find session %d", sessionId); + return; + } + { + std::lock_guard autoLock(idMapLock_); + sessionIdMap_.erase(sessionId); + } + session->OnSessionClose(sessionId); + DHLOGI("DCameraSoftbusAdapter OnSourceSessionClosed sessionId: %d end", sessionId); + return; +} + +void DCameraSoftbusAdapter::OnSourceBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + if (dataLen == 0 || dataLen > DCAMERA_MAX_RECV_DATA_LEN || data == nullptr) { + DHLOGE("DCameraSoftbusAdapter OnSourceBytesReceived dataLen: %d, sessionId: %d", dataLen, sessionId); + return; + } + std::shared_ptr session = nullptr; + int32_t ret = DCameraSoftbusSourceGetSession(sessionId, session); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSourceBytesReceived not find session %d", sessionId); + return; + } + + std::shared_ptr buffer = std::make_shared(dataLen); + ret = memcpy_s(buffer->Data(), buffer->Capacity(), data, dataLen); + if (ret != EOK) { + DHLOGE("DCameraSoftbusAdapter OnSourceBytesReceived memcpy_s failed ret: %d", ret); + return; + } + session->OnDataReceived(buffer); + return; +} + +void DCameraSoftbusAdapter::OnSourceMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + return; +} + +void DCameraSoftbusAdapter::OnSourceStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param) +{ + int32_t dataLen = data->bufLen; + if (dataLen <= 0 || dataLen > (int32_t)DCAMERA_MAX_RECV_DATA_LEN || data == nullptr) { + DHLOGE("DCameraSoftbusAdapter OnSourceStreamReceived dataLen: %d, sessionId: %d", dataLen, sessionId); + return; + } + std::shared_ptr session = nullptr; + int32_t ret = DCameraSoftbusSourceGetSession(sessionId, session); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSourceStreamReceived not find session %d", sessionId); + return; + } + + std::shared_ptr buffer = std::make_shared(data->bufLen); + ret = memcpy_s(buffer->Data(), buffer->Capacity(), (uint8_t *)data->buf, data->bufLen); + if (ret != EOK) { + DHLOGE("DCameraSoftbusAdapter OnSourceStreamReceived memcpy_s failed ret: %d", ret); + return; + } + session->OnDataReceived(buffer); + return; +} + +int32_t DCameraSoftbusAdapter::DCameraSoftbusSinkGetSession(int32_t sessionId, + std::shared_ptr& session) +{ + char mySessionName[DCAMERA_SESSION_NAME_MAX_LEN] = ""; + int ret = GetMySessionName(sessionId, mySessionName, sizeof(mySessionName)); + if (ret != DCAMERA_OK) { + DHLOGI("DCameraSoftbusAdapter DCameraSoftbusSinkGetSession sessionId: %d GetPeerSessionName failed: %d", + sessionId, ret); + return ret; + } + + auto iter = sinkSessions_.find(std::string(mySessionName)); + if (iter == sinkSessions_.end()) { + DHLOGE("DCameraSoftbusAdapter DCameraSoftbusSinkGetSession not find session %d", sessionId); + return DCAMERA_NOT_FOUND; + } + session = iter->second; + return DCAMERA_OK; +} + +int32_t DCameraSoftbusAdapter::OnSinkSessionOpened(int32_t sessionId, int32_t result) +{ + DHLOGI("DCameraSoftbusAdapter OnSinkSessionOpened sessionId: %d, result: %d", sessionId, result); + std::shared_ptr session = nullptr; + int32_t ret = DCameraSoftbusSinkGetSession(sessionId, session); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSinkSessionOpened not find session %d", sessionId); + return DCAMERA_NOT_FOUND; + } + + ret = session->OnSessionOpend(sessionId, result); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSinkSessionOpened not find session %d", sessionId); + } else { + std::lock_guard autoLock(idMapLock_); + sessionIdMap_.emplace(sessionId, session); + } + DHLOGI("DCameraSoftbusAdapter OnSinkSessionOpened sessionId: %d, result: %d end", sessionId, result); + return ret; +} + +void DCameraSoftbusAdapter::OnSinkSessionClosed(int32_t sessionId) +{ + DHLOGI("DCameraSoftbusAdapter OnSinkSessionClosed sessionId: %d", sessionId); + std::shared_ptr session = nullptr; + int32_t ret = DCameraSoftbusGetSessionById(sessionId, session); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSinkSessionClosed not find session %d", sessionId); + return; + } + { + std::lock_guard autoLock(idMapLock_); + sessionIdMap_.erase(sessionId); + } + session->OnSessionClose(sessionId); + return; +} + +void DCameraSoftbusAdapter::OnSinkBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + if (dataLen == 0 || dataLen > DCAMERA_MAX_RECV_DATA_LEN || data == nullptr) { + DHLOGE("DCameraSoftbusAdapter OnSinkBytesReceived dataLen: %d, sessionId: %d", dataLen, sessionId); + return; + } + std::shared_ptr session = nullptr; + int32_t ret = DCameraSoftbusSinkGetSession(sessionId, session); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSinkBytesReceived not find session %d", sessionId); + return; + } + + std::shared_ptr buffer = std::make_shared(dataLen); + ret = memcpy_s(buffer->Data(), buffer->Capacity(), data, dataLen); + if (ret != EOK) { + DHLOGE("DCameraSoftbusAdapter OnSinkBytesReceived memcpy_s failed ret: %d", ret); + return; + } + session->OnDataReceived(buffer); + return; +} + +void DCameraSoftbusAdapter::OnSinkMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + return; +} + +void DCameraSoftbusAdapter::OnSinkStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param) +{ + int32_t dataLen = data->bufLen; + if (dataLen <= 0 || dataLen > (int32_t)DCAMERA_MAX_RECV_DATA_LEN || data == nullptr) { + DHLOGE("DCameraSoftbusAdapter OnSinkStreamReceived dataLen: %d sessionId: %d", dataLen, sessionId); + return; + } + std::shared_ptr session = nullptr; + int32_t ret = DCameraSoftbusSinkGetSession(sessionId, session); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter OnSinkStreamReceived not find session %d", sessionId); + return; + } + + std::shared_ptr buffer = std::make_shared(data->bufLen); + ret = memcpy_s(buffer->Data(), buffer->Capacity(), (uint8_t *)data->buf, data->bufLen); + if (ret != EOK) { + DHLOGE("DCameraSoftbusAdapter OnSinkStreamReceived memcpy_s failed ret: %d", ret); + return; + } + session->OnDataReceived(buffer); + return; +} + +int32_t DCameraSoftbusAdapter::GetLocalNetworkId(std::string& myDevId) +{ + NodeBasicInfo basicInfo = { { 0 } }; + int32_t ret = GetLocalNodeDeviceInfo(PKG_NAME.c_str(), &basicInfo); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusAdapter GetLocalNodeDeviceInfo failed ret: %d", ret); + return ret; + } + + myDevId = std::string(basicInfo.networkId); + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/channel/src/dcamera_softbus_session.cpp b/services/channel/src/dcamera_softbus_session.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4a562f4529005a1963da60b224b2e37dd51912e --- /dev/null +++ b/services/channel/src/dcamera_softbus_session.cpp @@ -0,0 +1,451 @@ +/* + * 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 "dcamera_softbus_session.h" + +#include + +#include "anonymous_string.h" +#include "dcamera_softbus_adapter.h" +#include "distributed_camera_constants.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +DCameraSoftbusSession::DCameraSoftbusSession() +{ + sessionId_ = -1; + state_ = DCAMERA_SOFTBUS_STATE_CLOSED; + mode_ = DCAMERA_SESSION_MODE_CTRL; + ResetAssembleFrag(); +} + +DCameraSoftbusSession::DCameraSoftbusSession(std::string myDevId, std::string mySessionName, std::string peerDevId, + std::string peerSessionName, std::shared_ptr listener, DCameraSessionMode mode) + : myDevId_(myDevId), mySessionName_(mySessionName), peerDevId_(peerDevId), peerSessionName_(peerSessionName), + listener_(listener), sessionId_(-1), state_(DCAMERA_SOFTBUS_STATE_CLOSED), mode_(mode) +{ + sendFuncMap_[DCAMERA_SESSION_MODE_CTRL] = &DCameraSoftbusSession::SendBytes; + sendFuncMap_[DCAMERA_SESSION_MODE_VIDEO] = &DCameraSoftbusSession::SendStream; + sendFuncMap_[DCAMERA_SESSION_MODE_JPEG] = &DCameraSoftbusSession::SendStream; + auto runner = AppExecFwk::EventRunner::Create(mySessionName); + eventHandler_ = std::make_shared(runner); + ResetAssembleFrag(); +} + +DCameraSoftbusSession::~DCameraSoftbusSession() +{ + if (sessionId_ != -1) { + int32_t ret = DCameraSoftbusAdapter::GetInstance().CloseSoftbusSession(sessionId_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusSession delete failed, ret: %d, sessId: %d peerDevId: %s peerSessionName: %s", ret, + sessionId_, GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + } + } + sendFuncMap_.clear(); + eventHandler_ = nullptr; +} + +int32_t DCameraSoftbusSession::OpenSession() +{ + DHLOGI("DCameraSoftbusSession OpenSession peerDevId: %s peerSessionName: %s", + GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + int32_t ret = DCameraSoftbusAdapter::GetInstance().OpenSoftbusSession(mySessionName_, peerSessionName_, mode_, + peerDevId_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusSession OpenSession failed, ret: %d, peerDevId: %s peerSessionName: %s", ret, + GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + return ret; + } + + listener_->OnSessionState(DCAMERA_CHANNEL_STATE_CONNECTING); + return DCAMERA_OK; +} + +int32_t DCameraSoftbusSession::CloseSession() +{ + DHLOGI("DCameraSoftbusSession CloseSession sessionId: %d peerDevId: %s peerSessionName: %s", sessionId_, + GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + if (sessionId_ == -1) { + DHLOGI("DCameraSoftbusSession CloseSession has already close peerDevId: %s peerSessionName: %s", + GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + return DCAMERA_OK; + } + int32_t ret = DCameraSoftbusAdapter::GetInstance().CloseSoftbusSession(sessionId_); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusSession CloseSession failed, ret: %d, peerDevId: %s peerSessionName: %s", ret, + GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + return ret; + } + + sessionId_ = -1; + state_ = DCAMERA_SOFTBUS_STATE_CLOSED; + return DCAMERA_OK; +} + +int32_t DCameraSoftbusSession::OnSessionOpend(int32_t sessionId, int32_t result) +{ + DHLOGI("DCameraSoftbusSession OnSessionOpend sessionId: %d result: %d peerDevId: %s peerSessionName: %s", + sessionId, result, GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + if (result != DCAMERA_OK) { + DHLOGE("DCameraSoftbusSession OnSessionOpend sessionId: %d result: %d peerDevId: %s peerSessionName: %s", + sessionId_, result, GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + listener_->OnSessionState(DCAMERA_CHANNEL_STATE_DISCONNECTED); + listener_->OnSessionError(DCAMERA_MESSAGE, DCAMERA_EVENT_OPEN_CHANNEL_ERROR, + std::string("softbus internal error")); + return result; + } + + sessionId_ = sessionId; + state_ = DCAMERA_SOFTBUS_STATE_OPENED; + listener_->OnSessionState(DCAMERA_CHANNEL_STATE_CONNECTED); + return DCAMERA_OK; +} + +int32_t DCameraSoftbusSession::OnSessionClose(int32_t sessionId) +{ + DHLOGI("DCameraSoftbusSession OnSessionClose sessionId: %d peerDevId: %s peerSessionName: %s", sessionId, + GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + sessionId_ = -1; + state_ = DCAMERA_SOFTBUS_STATE_CLOSED; + listener_->OnSessionState(DCAMERA_CHANNEL_STATE_DISCONNECTED); + return DCAMERA_OK; +} + +int32_t DCameraSoftbusSession::OnDataReceived(std::shared_ptr& buffer) +{ + auto recvDataFunc = [this, buffer]() mutable { + DealRecvData(buffer); + }; + if (eventHandler_ != nullptr) { + eventHandler_->PostTask(recvDataFunc); + } + return DCAMERA_OK; +} + +void DCameraSoftbusSession::DealRecvData(std::shared_ptr& buffer) +{ + if (mode_ == DCAMERA_SESSION_MODE_VIDEO) { + PostData(buffer); + return; + } + PackRecvData(buffer); + return; +} + +void DCameraSoftbusSession::PackRecvData(std::shared_ptr& buffer) +{ + if (buffer->Size() < BINARY_HEADER_FRAG_LEN) { + DHLOGE("DCameraSoftbusSession PackRecvData failed, size: %d, sess: %s peerSess: %s", + buffer->Size(), mySessionName_.c_str(), peerSessionName_.c_str()); + return; + } + uint8_t *ptrPacket = buffer->Data(); + SessionDataHeader headerPara; + GetFragDataLen(ptrPacket, headerPara); + if (buffer->Size() != (headerPara.dataLen + BINARY_HEADER_FRAG_LEN) || headerPara.dataLen > headerPara.totalLen || + headerPara.dataLen > BINARY_DATA_MAX_LEN || headerPara.totalLen > BINARY_DATA_MAX_TOTAL_LEN) { + DHLOGE("DCameraSoftbusSession PackRecvData failed, size: %d, dataLen: %d, totalLen: %d sess: %s peerSess: %s", + buffer->Size(), headerPara.dataLen, headerPara.totalLen, mySessionName_.c_str(), peerSessionName_.c_str()); + return; + } + + DHLOGD("DCameraSoftbusSession PackRecvData Assemble, size: %d, dataLen: %d, totalLen: %d sess: %s peerSess: %s", + buffer->Size(), headerPara.dataLen, headerPara.totalLen, mySessionName_.c_str(), peerSessionName_.c_str()); + if (headerPara.fragFlag == FRAG_START_END) { + AssembleNoFrag(buffer, headerPara); + } else { + AssembleFrag(buffer, headerPara); + } +} + +void DCameraSoftbusSession::AssembleNoFrag(std::shared_ptr& buffer, SessionDataHeader& headerPara) +{ + if (headerPara.dataLen != headerPara.totalLen) { + DHLOGE("DCameraSoftbusSession PackRecvData failed, dataLen: %d, totalLen: %d, sess: %s peerSess: %s", + headerPara.dataLen, headerPara.totalLen, mySessionName_.c_str(), peerSessionName_.c_str()); + return; + } + std::shared_ptr postData = std::make_shared(headerPara.dataLen); + int32_t ret = memcpy_s(postData->Data(), postData->Size(), buffer->Data() + BINARY_HEADER_FRAG_LEN, + buffer->Size() - BINARY_HEADER_FRAG_LEN); + if (ret != EOK) { + DHLOGE("DCameraSoftbusSession PackRecvData failed, ret: %d, sess: %s peerSess: %s", + ret, mySessionName_.c_str(), peerSessionName_.c_str()); + return; + } + PostData(postData); +} + +void DCameraSoftbusSession::AssembleFrag(std::shared_ptr& buffer, SessionDataHeader& headerPara) +{ + if (headerPara.fragFlag == FRAG_START) { + isWaiting_ = true; + nowSeq_ = headerPara.seqNum; + nowSubSeq_ = headerPara.subSeq; + offset_ = 0; + totalLen_ = headerPara.totalLen; + packBuffer_ = std::make_shared(headerPara.totalLen); + int32_t ret = memcpy_s(packBuffer_->Data(), packBuffer_->Size(), buffer->Data() + BINARY_HEADER_FRAG_LEN, + buffer->Size() - BINARY_HEADER_FRAG_LEN); + if (ret != EOK) { + DHLOGE("DCameraSoftbusSession AssembleFrag failed, ret: %d, sess: %s peerSess: %s", + ret, mySessionName_.c_str(), peerSessionName_.c_str()); + ResetAssembleFrag(); + return; + } + offset_ += headerPara.dataLen; + } + + if (headerPara.fragFlag == FRAG_MID || headerPara.fragFlag == FRAG_END) { + int32_t ret = CheckUnPackBuffer(headerPara); + if (ret != DCAMERA_OK) { + return; + } + + nowSubSeq_ = headerPara.subSeq; + ret = memcpy_s(packBuffer_->Data() + offset_, packBuffer_->Size() - offset_, + buffer->Data() + BINARY_HEADER_FRAG_LEN, buffer->Size() - BINARY_HEADER_FRAG_LEN); + if (ret != EOK) { + DHLOGE("DCameraSoftbusSession AssembleFrag failed, memcpy_s ret: %d, sess: %s peerSess: %s", + ret, mySessionName_.c_str(), peerSessionName_.c_str()); + ResetAssembleFrag(); + return; + } + offset_ += headerPara.dataLen; + } + + if (headerPara.fragFlag == FRAG_END) { + PostData(packBuffer_); + ResetAssembleFrag(); + } +} + +int32_t DCameraSoftbusSession::CheckUnPackBuffer(SessionDataHeader& headerPara) +{ + if (!isWaiting_) { + DHLOGE("DCameraSoftbusSession AssembleFrag failed, not start one, sess: %s peerSess: %s", + mySessionName_.c_str(), peerSessionName_.c_str()); + return DCAMERA_BAD_VALUE; + } + + if (nowSeq_ != headerPara.seqNum) { + DHLOGE("DCameraSoftbusSession AssembleFrag seq error nowSeq: %d actualSeq: %d, sess: %s peerSess: %s", + nowSeq_, headerPara.seqNum, mySessionName_.c_str(), peerSessionName_.c_str()); + return DCAMERA_BAD_VALUE; + } + + if (nowSubSeq_ + 1 != headerPara.subSeq) { + DHLOGE("DCameraSoftbusSession AssembleFrag subSeq error nowSeq: %d actualSeq: %d, sess: %s peerSess: %s", + nowSubSeq_, headerPara.subSeq, mySessionName_.c_str(), peerSessionName_.c_str()); + return DCAMERA_BAD_VALUE; + } + + if (totalLen_ < headerPara.dataLen + offset_) { + DHLOGE("DCameraSoftbusSession AssembleFrag len error cap: %d size: %d, dataLen: %d sess: %s peerSess: %s", + totalLen_, offset_, headerPara.dataLen, mySessionName_.c_str(), + peerSessionName_.c_str()); + return DCAMERA_BAD_VALUE; + } + return DCAMERA_OK; +} + +void DCameraSoftbusSession::ResetAssembleFrag() +{ + isWaiting_ = false; + nowSeq_ = 0; + nowSubSeq_ = 0; + offset_ = 0; + totalLen_ = 0; + packBuffer_ = nullptr; +} + +void DCameraSoftbusSession::PostData(std::shared_ptr& buffer) +{ + std::vector> buffers; + buffers.push_back(buffer); + listener_->OnDataReceived(buffers); +} + +void DCameraSoftbusSession::GetFragDataLen(uint8_t *ptrPacket, SessionDataHeader& headerPara) +{ + headerPara.version = U16Get(ptrPacket); + headerPara.fragFlag = ptrPacket[static_cast(BINARY_HEADER_FRAG_OFFSET)]; + headerPara.dataType = U32Get(ptrPacket + BINARY_HEADER_DATATYPE_OFFSET); + headerPara.seqNum = U32Get(ptrPacket + BINARY_HEADER_SEQNUM_OFFSET); + headerPara.totalLen = U32Get(ptrPacket + BINARY_HEADER_TOTALLEN_OFFSET); + headerPara.subSeq = U16Get(ptrPacket + BINARY_HEADER_SUBSEQ_OFFSET); + headerPara.dataLen = U32Get(ptrPacket + BINARY_HEADER_DATALEN_OFFSET); +} + +uint16_t DCameraSoftbusSession::U16Get(const uint8_t *ptr) +{ + return (ptr[0] << DCAMERA_SHIFT_8) | ptr[1]; +} + +uint32_t DCameraSoftbusSession::U32Get(const uint8_t *ptr) +{ + return (ptr[0] << DCAMERA_SHIFT_24) | (ptr[1] << DCAMERA_SHIFT_16) | (ptr[2] << DCAMERA_SHIFT_8) | ptr[3]; +} + +int32_t DCameraSoftbusSession::SendData(DCameraSessionMode mode, std::shared_ptr& buffer) +{ + auto itFunc = sendFuncMap_.find(mode); + if (itFunc == sendFuncMap_.end()) { + return DCAMERA_NOT_FOUND; + } + auto memberFunc = itFunc->second; + if (mode == DCAMERA_SESSION_MODE_VIDEO) { + return (this->*memberFunc)(buffer); + } + + return UnPackSendData(buffer, memberFunc); +} + +int32_t DCameraSoftbusSession::UnPackSendData(std::shared_ptr& buffer, DCameraSendFuc memberFunc) +{ + uint16_t subSeq = 0; + uint32_t seq = 0; + uint32_t totalLen = buffer->Size(); + SessionDataHeader headPara = { PROTOCOL_VERSION, FRAG_START, mode_, seq, totalLen, subSeq }; + + if (buffer->Size() <= BINARY_DATA_PACKET_MAX_LEN) { + headPara.fragFlag = FRAG_START_END; + headPara.dataLen = buffer->Size(); + std::shared_ptr unpackData = std::make_shared(buffer->Size() + BINARY_HEADER_FRAG_LEN); + MakeFragDataHeader(headPara, unpackData->Data(), BINARY_HEADER_FRAG_LEN); + int32_t ret = memcpy_s(unpackData->Data() + BINARY_HEADER_FRAG_LEN, unpackData->Size() - BINARY_HEADER_FRAG_LEN, + buffer->Data(), buffer->Size()); + if (ret != EOK) { + DHLOGE("DCameraSoftbusSession UnPackSendData START_END memcpy_s failed, ret: %d, sess: %s peerSess: %s", + ret, mySessionName_.c_str(), peerSessionName_.c_str()); + return ret; + } + return (this->*memberFunc)(unpackData); + } + + uint32_t offset = 0; + while (totalLen > offset) { + if (totalLen - offset > BINARY_DATA_PACKET_MAX_LEN) { + headPara.dataLen = BINARY_DATA_PACKET_MAX_LEN; + } else { + headPara.fragFlag = FRAG_END; + headPara.dataLen = totalLen - offset; + } + + std::shared_ptr unpackData = + std::make_shared(headPara.dataLen + BINARY_HEADER_FRAG_LEN); + MakeFragDataHeader(headPara, unpackData->Data(), BINARY_HEADER_FRAG_LEN); + int ret = memcpy_s(unpackData->Data() + BINARY_HEADER_FRAG_LEN, unpackData->Size() - BINARY_HEADER_FRAG_LEN, + buffer->Data() + offset, headPara.dataLen); + if (ret != EOK) { + DHLOGE("DCameraSoftbusSession UnPackSendData memcpy_s failed, ret: %d, sess: %s peerSess: %s", + ret, mySessionName_.c_str(), peerSessionName_.c_str()); + return ret; + } + ret = (this->*memberFunc)(unpackData); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusSession sendData failed, ret: %d, sess: %s peerSess: %s", + ret, mySessionName_.c_str(), peerSessionName_.c_str()); + return ret; + } + headPara.subSeq++; + headPara.fragFlag = FRAG_MID; + offset += headPara.dataLen; + } + return DCAMERA_OK; +} + +void DCameraSoftbusSession::MakeFragDataHeader(const SessionDataHeader& headPara, uint8_t *header, uint32_t len) +{ + uint32_t headerLen = sizeof(uint8_t) * HEADER_UINT8_NUM + sizeof(uint16_t) * HEADER_UINT16_NUM + + sizeof(uint32_t) * HEADER_UINT32_NUM; + if (headerLen > len) { + DHLOGE("MakeFragDataHeader %d over len %d", headerLen, len); + return; + } + uint32_t i = 0; + header[i++] = headPara.version >> DCAMERA_SHIFT_8; + header[i++] = headPara.version & UINT16_SHIFT_MASK_0; + header[i++] = headPara.fragFlag; + header[i++] = (headPara.dataType & UINT32_SHIFT_MASK_24) >> DCAMERA_SHIFT_24; + header[i++] = (headPara.dataType & UINT32_SHIFT_MASK_16) >> DCAMERA_SHIFT_16; + header[i++] = (headPara.dataType & UINT32_SHIFT_MASK_8) >> DCAMERA_SHIFT_8; + header[i++] = (headPara.dataType & UINT32_SHIFT_MASK_0); + header[i++] = (headPara.seqNum & UINT32_SHIFT_MASK_24) >> DCAMERA_SHIFT_24; + header[i++] = (headPara.seqNum & UINT32_SHIFT_MASK_16) >> DCAMERA_SHIFT_16; + header[i++] = (headPara.seqNum & UINT32_SHIFT_MASK_8) >> DCAMERA_SHIFT_8; + header[i++] = (headPara.seqNum & UINT32_SHIFT_MASK_0); + header[i++] = (headPara.totalLen & UINT32_SHIFT_MASK_24) >> DCAMERA_SHIFT_24; + header[i++] = (headPara.totalLen & UINT32_SHIFT_MASK_16) >> DCAMERA_SHIFT_16; + header[i++] = (headPara.totalLen & UINT32_SHIFT_MASK_8) >> DCAMERA_SHIFT_8; + header[i++] = (headPara.totalLen & UINT32_SHIFT_MASK_0); + header[i++] = headPara.subSeq >> DCAMERA_SHIFT_8; + header[i++] = headPara.subSeq & UINT16_SHIFT_MASK_0; + header[i++] = (headPara.dataLen & UINT32_SHIFT_MASK_24) >> DCAMERA_SHIFT_24; + header[i++] = (headPara.dataLen & UINT32_SHIFT_MASK_16) >> DCAMERA_SHIFT_16; + header[i++] = (headPara.dataLen & UINT32_SHIFT_MASK_8) >> DCAMERA_SHIFT_8; + header[i++] = (headPara.dataLen & UINT32_SHIFT_MASK_0); +} + +int32_t DCameraSoftbusSession::SendBytes(std::shared_ptr& buffer) +{ + if (state_ != DCAMERA_SOFTBUS_STATE_OPENED) { + DHLOGE("DCameraSoftbusSession SendBytes session state %d is not opened sessionId: %d peerDev: %s peerName: %s", + state_, sessionId_, GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + return DCAMERA_WRONG_STATE; + } + + int32_t ret = DCameraSoftbusAdapter::GetInstance().SendSofbusBytes(sessionId_, buffer); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusSession SendBytes sessionId: %d failed: %d peerDevId: %s peerSessionName: %s", sessionId_, + ret, GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + } + return ret; +} + +int32_t DCameraSoftbusSession::SendStream(std::shared_ptr& buffer) +{ + if (state_ != DCAMERA_SOFTBUS_STATE_OPENED) { + DHLOGE("DCameraSoftbusSession SendStream session state %d is not opened sessionId: %d peerDev: %s peerName: %s", + state_, sessionId_, GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + return DCAMERA_WRONG_STATE; + } + + int32_t ret = DCameraSoftbusAdapter::GetInstance().SendSofbusStream(sessionId_, buffer); + if (ret != DCAMERA_OK) { + DHLOGE("DCameraSoftbusSession SendStream sessionId: %d failed: %d peerDevId: %s peerSessionName: %s", + sessionId_, ret, GetAnonyString(peerDevId_).c_str(), GetAnonyString(peerSessionName_).c_str()); + } + return ret; +} + +std::string DCameraSoftbusSession::GetPeerDevId() +{ + return peerDevId_; +} + +std::string DCameraSoftbusSession::GetPeerSessionName() +{ + return peerSessionName_; +} + +std::string DCameraSoftbusSession::GetMySessionName() +{ + return mySessionName_; +} +} +} \ No newline at end of file diff --git a/services/data_process/BUILD.gn b/services/data_process/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a4aa82d71b277e46473a86451808fa79c9134321 --- /dev/null +++ b/services/data_process/BUILD.gn @@ -0,0 +1,81 @@ +# 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. + +import("//build/ohos.gni") +import("//build/ohos_var.gni") +import("//foundation/distributedhardware/distributedcamera/distributedcamera.gni") + +ohos_shared_library("distributed_camera_data_process") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "//foundation/graphic/standard/interfaces/innerkits/common", + "//foundation/graphic/standard/interfaces/innerkits/surface", + "//drivers/peripheral/display/interfaces/include", + "//foundation/multimedia/media_standard/interfaces/innerkits/native/media/include", + "${fwk_common_path}/log/include", + "${fwk_common_path}/utils/include", + "${fwk_utils_path}/include/log", + "${fwk_utils_path}/include/eventbus", + "${fwk_utils_path}/include", + ] + + include_dirs += [ + "include/interfaces", + "include/eventbus", + "include/pipeline", + "include/utils", + "include/pipeline_node/multimedia_codec", + "include/pipeline_node/colorspace_conversion", + "include/pipeline_node/fpscontroller", + "${common_path}/include/constants", + "${common_path}/include/utils", + "${innerkits_path}/native_cpp/camera_source/include", + ] + + sources = [ + "src/pipeline/dcamera_pipeline_sink.cpp", + "src/pipeline/dcamera_pipeline_source.cpp", + "src/pipeline/abstract_data_process.cpp", + "src/utils/image_common_type.cpp", + "src/pipeline_node/multimedia_codec/decode_data_process.cpp", + "src/pipeline_node/multimedia_codec/decode_video_callback.cpp", + "src/pipeline_node/multimedia_codec/encode_data_process.cpp", + "src/pipeline_node/multimedia_codec/encode_video_callback.cpp", + "src/pipeline_node/fpscontroller/fps_controller_process.cpp", + "src/pipeline_node/colorspace_conversion/convert_nv12_to_nv21.cpp", + ] + + deps = [ + "${fwk_utils_path}:distributedhardwareutils", + "${common_path}:distributed_camera_utils", + "//foundation/graphic/standard/frameworks/surface:surface", + "//utils/native/base:utils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"dcameradataproc\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "multimedia_media_standard:media_client", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_camera" +} \ No newline at end of file diff --git a/services/data_process/include/eventbus/dcamera_codec_event.h b/services/data_process/include/eventbus/dcamera_codec_event.h new file mode 100644 index 0000000000000000000000000000000000000000..3cb83d27fe8d11aae693c5e32feb3e3b0988b31c --- /dev/null +++ b/services/data_process/include/eventbus/dcamera_codec_event.h @@ -0,0 +1,90 @@ +/* + * 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_DCAMERA_CODEC_EVENT_H +#define OHOS_DCAMERA_CODEC_EVENT_H + +#include + +#include "event.h" +#include "data_buffer.h" +#include "image_common_type.h" + +namespace OHOS { +namespace DistributedHardware { +enum class VideoCodecAction : int32_t { + NO_ACTION = 0, + ACTION_ONCE_AGAIN = 1, +}; + +class CodecPacket { +public: + CodecPacket() : videoCodec_(VideoCodecType::NO_CODEC) {} + CodecPacket(VideoCodecType videoCodec, const std::vector>& multiDataBuffers) + : videoCodec_(videoCodec), multiDataBuffers_(multiDataBuffers) {} + ~CodecPacket() = default; + + void SetVideoCodecType(VideoCodecType videoCodec) + { + videoCodec_ = videoCodec; + } + + VideoCodecType GetVideoCodecType() const + { + return videoCodec_; + } + + void SetDataBuffers(std::vector>& multiDataBuffers) + { + multiDataBuffers_ = multiDataBuffers; + } + + std::vector> GetDataBuffers() const + { + return multiDataBuffers_; + } + +private: + VideoCodecType videoCodec_; + std::vector> multiDataBuffers_; +}; + +class DCameraCodecEvent : public Event { + TYPEINDENT(DCameraCodecEvent) +public: + DCameraCodecEvent(EventSender& sender, const std::shared_ptr& codecPacket) + : Event(sender), codecPacket_(codecPacket), action_(VideoCodecAction::NO_ACTION) {} + DCameraCodecEvent(EventSender& sender, const std::shared_ptr& codecPacket, + VideoCodecAction otherAction) + : Event(sender), codecPacket_(codecPacket), action_(otherAction) {} + ~DCameraCodecEvent() {} + + std::shared_ptr GetCodecPacket() const + { + return codecPacket_; + } + + VideoCodecAction GetAction() const + { + return action_; + } + +private: + std::shared_ptr codecPacket_; + VideoCodecAction action_; +}; +} +} +#endif diff --git a/services/data_process/include/eventbus/dcamera_pipeline_event.h b/services/data_process/include/eventbus/dcamera_pipeline_event.h new file mode 100644 index 0000000000000000000000000000000000000000..f01126f7ce7a9fe1b004261b601c62b5bd1ffccc --- /dev/null +++ b/services/data_process/include/eventbus/dcamera_pipeline_event.h @@ -0,0 +1,101 @@ +/* + * 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_DCAMERA_PIPELINE_EVENT_H +#define OHOS_DCAMERA_PIPELINE_EVENT_H + +#include + +#include "event.h" +#include "data_buffer.h" +#include "image_common_type.h" + +namespace OHOS { +namespace DistributedHardware { +enum class PipelineAction : int32_t { + NO_ACTION = 0, +}; + +class PipelineConfig { +public: + PipelineConfig() : pipelineType_(PipelineType::VIDEO) {} + PipelineConfig(PipelineType pipelineType, const std::string& pipelineOwner, + const std::vector>& multiDataBuffers) + : pipelineType_(pipelineType), pipelineOwner_(pipelineOwner), multiDataBuffers_(multiDataBuffers) {} + ~PipelineConfig() = default; + + void SetPipelineType(PipelineType pipelineType) + { + pipelineType_ = pipelineType; + } + + PipelineType GetPipelineType() const + { + return pipelineType_; + } + + void SetPipelineOwner(std::string pipelineOwner) + { + pipelineOwner_ = pipelineOwner; + } + + std::string GetPipelineOwner() const + { + return pipelineOwner_; + } + + void SetDataBuffers(std::vector>& multiDataBuffers) + { + multiDataBuffers_ = multiDataBuffers; + } + + std::vector> GetDataBuffers() const + { + return multiDataBuffers_; + } + +private: + PipelineType pipelineType_; + std::string pipelineOwner_; + std::vector> multiDataBuffers_; +}; + +class DCameraPipelineEvent : public Event { + TYPEINDENT(DCameraPipelineEvent) +public: + DCameraPipelineEvent(EventSender& sender, const std::shared_ptr& pipelineConfig) + : Event(sender), pipelineConfig_(pipelineConfig), action_(PipelineAction::NO_ACTION) {} + DCameraPipelineEvent(EventSender& sender, const std::shared_ptr& pipelineConfig, + PipelineAction otherAction) + : Event(sender), pipelineConfig_(pipelineConfig), action_(otherAction) {} + ~DCameraPipelineEvent() = default; + + std::shared_ptr GetPipelineConfig() const + { + return pipelineConfig_; + } + + PipelineAction GetAction() const + { + return action_; + } + +private: + std::shared_ptr pipelineConfig_ = nullptr; + PipelineAction action_; +}; +} +} +#endif diff --git a/services/data_process/include/interfaces/data_process_listener.h b/services/data_process/include/interfaces/data_process_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..15de4e72db18a94468d21fd4e04b6010d144cb70 --- /dev/null +++ b/services/data_process/include/interfaces/data_process_listener.h @@ -0,0 +1,38 @@ +/* + * 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_DATA_PROCESS_LISTENER_H +#define OHOS_DATA_PROCESS_LISTENER_H + +#include "data_buffer.h" + +namespace OHOS { +namespace DistributedHardware { +enum DataProcessErrorType : int32_t { + ERROR_PIPELINE_ENCODER = 0, + ERROR_PIPELINE_DECODER = -1, + ERROR_PIPELINE_EVENTBUS = -2, + ERROR_DISABLE_PROCESS = -3, +}; + +class DataProcessListener { +public: + virtual ~DataProcessListener() = default; + virtual void OnProcessedVideoBuffer(const std::shared_ptr& videoResult) = 0; + virtual void OnError(DataProcessErrorType errorType) = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/interfaces/idata_process_pipeline.h b/services/data_process/include/interfaces/idata_process_pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..9355c695fd0053b7679719460d1693558e1b4385 --- /dev/null +++ b/services/data_process/include/interfaces/idata_process_pipeline.h @@ -0,0 +1,40 @@ +/* + * 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_IDATA_PROCESS_PIPELINE_H +#define OHOS_IDATA_PROCESS_PIPELINE_H + +#include +#include + +#include "data_buffer.h" +#include "image_common_type.h" +#include "distributed_camera_errno.h" +#include "data_process_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class IDataProcessPipeline { +public: + virtual ~IDataProcessPipeline() = default; + + virtual int32_t CreateDataProcessPipeline(PipelineType piplineType, const VideoConfigParams& sourceConfig, + const VideoConfigParams& targetConfig, const std::shared_ptr& listener) = 0; + virtual int32_t ProcessData(std::vector>& dataBuffers) = 0; + virtual void DestroyDataProcessPipeline() = 0; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/pipeline/abstract_data_process.h b/services/data_process/include/pipeline/abstract_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..beed1821ce431c609f54c8d2229f3c1bdd812347 --- /dev/null +++ b/services/data_process/include/pipeline/abstract_data_process.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_ABSTRACT_DATA_PROCESS_H +#define OHOS_ABSTRACT_DATA_PROCESS_H + +#include +#include + +#include "data_buffer.h" +#include "image_common_type.h" +#include "distributed_camera_errno.h" + +namespace OHOS { +namespace DistributedHardware { +class AbstractDataProcess { +public: + virtual ~AbstractDataProcess() = default; + int32_t SetNextNode(std::shared_ptr& nextDataProcess); + void SetNodeRank(size_t curNodeRank); + + virtual int32_t InitNode() = 0; + virtual int32_t ProcessData(std::vector>& inputBuffers) = 0; + virtual void ReleaseProcessNode() = 0; + +protected: + std::shared_ptr nextDataProcess_ = nullptr; + size_t nodeRank_; +}; +} +} +#endif diff --git a/services/data_process/include/pipeline/dcamera_pipeline_sink.h b/services/data_process/include/pipeline/dcamera_pipeline_sink.h new file mode 100644 index 0000000000000000000000000000000000000000..b23e087014e91967fb546ce2bc44992671b33763 --- /dev/null +++ b/services/data_process/include/pipeline/dcamera_pipeline_sink.h @@ -0,0 +1,72 @@ +/* + * 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_DCAMERA_PIPELINE_SINK_H +#define OHOS_DCAMERA_PIPELINE_SINK_H + +#include +#include + +#include "event.h" +#include "event_bus.h" +#include "event_sender.h" +#include "eventbus_handler.h" + +#include "data_buffer.h" +#include "image_common_type.h" +#include "distributed_camera_errno.h" +#include "dcamera_pipeline_event.h" +#include "idata_process_pipeline.h" +#include "abstract_data_process.h" +#include "data_process_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class EncodeDataProcess; + +class DCameraPipelineSink : public IDataProcessPipeline, public std::enable_shared_from_this { +public: + ~DCameraPipelineSink(); + + int32_t CreateDataProcessPipeline(PipelineType piplineType, const VideoConfigParams& sourceConfig, + const VideoConfigParams& targetConfig, const std::shared_ptr& listener) override; + int32_t ProcessData(std::vector>& dataBuffers) override; + void DestroyDataProcessPipeline() override; + + void OnError(DataProcessErrorType errorType); + void OnProcessedVideoBuffer(const std::shared_ptr& videoResult); + +private: + bool IsInRange(const VideoConfigParams& curConfig); + int32_t InitDCameraPipNodes(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig); + +private: + const static std::string PIPELINE_OWNER; + const static uint32_t MAX_FRAME_RATE = 30; + const static uint32_t MIN_VIDEO_WIDTH = 320; + const static uint32_t MIN_VIDEO_HEIGHT = 240; + const static uint32_t MAX_VIDEO_WIDTH = 1920; + const static uint32_t MAX_VIDEO_HEIGHT = 1080; + + std::shared_ptr processListener_ = nullptr; + std::shared_ptr pipelineHead_ = nullptr; + + bool isProcess_ = false; + PipelineType piplineType_ = PipelineType::VIDEO; + std::vector> pipNodeRanks_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/pipeline/dcamera_pipeline_source.h b/services/data_process/include/pipeline/dcamera_pipeline_source.h new file mode 100644 index 0000000000000000000000000000000000000000..a8065f8617ef2c19c520e6caec9eb765598fc7a2 --- /dev/null +++ b/services/data_process/include/pipeline/dcamera_pipeline_source.h @@ -0,0 +1,76 @@ +/* + * 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_DCAMERA_PIPELINE_SOURCE_H +#define OHOS_DCAMERA_PIPELINE_SOURCE_H + +#include +#include + +#include "event.h" +#include "event_bus.h" +#include "event_sender.h" +#include "eventbus_handler.h" + +#include "data_buffer.h" +#include "image_common_type.h" +#include "distributed_camera_errno.h" +#include "dcamera_pipeline_event.h" +#include "idata_process_pipeline.h" +#include "abstract_data_process.h" +#include "data_process_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DecodeDataProcess; + +class DCameraPipelineSource : public EventSender, public EventBusHandler, + public IDataProcessPipeline, public std::enable_shared_from_this { +public: + ~DCameraPipelineSource(); + + int32_t CreateDataProcessPipeline(PipelineType piplineType, const VideoConfigParams& sourceConfig, + const VideoConfigParams& targetConfig, const std::shared_ptr& listener) override; + int32_t ProcessData(std::vector>& dataBuffers) override; + void DestroyDataProcessPipeline() override; + void OnEvent(DCameraPipelineEvent& ev) override; + + void OnError(DataProcessErrorType errorType); + void OnProcessedVideoBuffer(const std::shared_ptr& videoResult); + +private: + bool IsInRange(const VideoConfigParams& curConfig); + void InitDCameraPipEvent(); + int32_t InitDCameraPipNodes(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig); + +private: + const static std::string PIPELINE_OWNER; + const static uint32_t MAX_FRAME_RATE = 30; + const static uint32_t MIN_VIDEO_WIDTH = 320; + const static uint32_t MIN_VIDEO_HEIGHT = 240; + const static uint32_t MAX_VIDEO_WIDTH = 1920; + const static uint32_t MAX_VIDEO_HEIGHT = 1080; + + std::shared_ptr processListener_ = nullptr; + std::shared_ptr pipelineHead_ = nullptr; + std::shared_ptr eventBusSource_ = nullptr; + + bool isProcess_ = false; + PipelineType piplineType_ = PipelineType::VIDEO; + std::vector> pipNodeRanks_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/pipeline_node/colorspace_conversion/convert_nv12_to_nv21.h b/services/data_process/include/pipeline_node/colorspace_conversion/convert_nv12_to_nv21.h new file mode 100644 index 0000000000000000000000000000000000000000..bd0eba5b34bb3feafa633384c750211c5c4dc8bc --- /dev/null +++ b/services/data_process/include/pipeline_node/colorspace_conversion/convert_nv12_to_nv21.h @@ -0,0 +1,48 @@ +/* + * 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_CONVERT_NV12TONV21_H +#define OHOS_CONVERT_NV12TONV21_H + +#include "securec.h" +#include "data_buffer.h" +#include "image_common_type.h" + +namespace OHOS { +namespace DistributedHardware { +class ConvertNV12ToNV21 { +public: + ConvertNV12ToNV21() = default; + ~ConvertNV12ToNV21() = default; + std::shared_ptr ProcessData(const std::shared_ptr& srcBuf, + const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig); + +private: + bool IsConvertible(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig); + int32_t GetImageUnitInfo(ImageUnitInfo& imgInfo, const std::shared_ptr& imgBuf); + bool IsCorrectImageUnitInfo(const ImageUnitInfo& imgInfo); + int32_t CheckColorConvertInfo(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo); + void SeparateUVPlaneByRow(const uint8_t *srcUVPlane, uint8_t *dstUPlane, uint8_t *dstVPlane, + int32_t srcHalfWidth); + int32_t SeparateNV12UVPlane(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo); + void CombineUVPlaneByRow(const uint8_t *srcUPlane, const uint8_t *srcVPlane, uint8_t *dstUVPlane, + int32_t dstHalfWidth); + int32_t CombineNV12UVPlane(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo); + int32_t CopyYPlane(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo); + int32_t ColorConvertNV12ToNV21(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo); +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/pipeline_node/fpscontroller/fps_controller_process.h b/services/data_process/include/pipeline_node/fpscontroller/fps_controller_process.h new file mode 100644 index 0000000000000000000000000000000000000000..9e9fbbeb758a23d3c3456086a9120d4c058c8ae5 --- /dev/null +++ b/services/data_process/include/pipeline_node/fpscontroller/fps_controller_process.h @@ -0,0 +1,79 @@ +/* + * 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_FPS_CONTROLLER_PROCESS_H +#define OHOS_FPS_CONTROLLER_PROCESS_H + +#include +#include + +#include "abstract_data_process.h" +#include "dcamera_pipeline_source.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraPipelineSource; + +class FpsControllerProcess : public AbstractDataProcess { +public: + FpsControllerProcess(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig, + const std::weak_ptr& callbackPipSource) + : sourceConfig_(sourceConfig), targetConfig_(targetConfig), callbackPipelineSource_(callbackPipSource) {} + ~FpsControllerProcess(); + + int32_t InitNode() override; + int32_t ProcessData(std::vector>& inputBuffers) override; + void ReleaseProcessNode() override; + +private: + void UpdateFPSControllerInfo(int64_t nowMs); + void UpdateFrameRateCorrectionFactor(int64_t nowMs); + void UpdateIncomingFrameTimes(int64_t nowMs); + float CalculateFrameRate(int64_t nowMs); + bool IsDropFrame(float incomingFps); + bool ReduceFrameRateByUniformStrategy(int32_t incomingFps); + int32_t FpsControllerDone(std::vector> outputBuffers); + +private: + const static uint32_t MAX_TARGET_FRAME_RATE = 30; + const static int32_t VIDEO_FRAME_DROP_INTERVAL = 4; + const static int32_t MIN_INCOME_FRAME_NUM_COEFFICIENT = 3; + const static int32_t INCOME_FRAME_TIME_HISTORY_WINDOWS_SIZE = 60; + /* Receive video frame detect time windows */ + const static int32_t FRAME_HISTORY_TIME_WINDOWS_MS = 2000; + const static int64_t FRMAE_MAX_INTERVAL_TIME_WINDOW_MS = 700; + const static int32_t OVERSHOOT_MODIFY_COEFFICIENT = 3; + const static int32_t DOUBLE_MULTIPLE = 2; + + std::mutex mtx; + VideoConfigParams sourceConfig_; + VideoConfigParams targetConfig_; + std::weak_ptr callbackPipelineSource_; + bool isFpsControllerProcess_ = false; + bool isFirstFrame_ = false; + uint32_t targetFrameRate_ = 0; + int64_t lastFrameIncomeTimeMs_ = 0; + /* the time span between current and last frame */ + int64_t recentFrameTimeSpanMs_ = -1; + int32_t keepCorrectionCount_ = 0; + int32_t keepLessThanDoubleCount_ = 0; + int32_t keepMoreThanDoubleCount_ = 0; + float frameRateCorrectionFactor_ = 0.0; + /* modify the frame rate controller argument */ + int32_t frameRateOvershootMdf_ = 0; + int64_t incomingFrameTimesMs_[INCOME_FRAME_TIME_HISTORY_WINDOWS_SIZE]; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/pipeline_node/multimedia_codec/decode_data_process.h b/services/data_process/include/pipeline_node/multimedia_codec/decode_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..8843eaad67a2d6e287d5c1d3abf1295e8f09f86f --- /dev/null +++ b/services/data_process/include/pipeline_node/multimedia_codec/decode_data_process.h @@ -0,0 +1,146 @@ +/* + * 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_DECODE_DATA_PROCESS_H +#define OHOS_DECODE_DATA_PROCESS_H + +#include "securec.h" +#include +#include +#include +#include +#include + +#include "surface.h" +#include "media_errors.h" +#include "avcodec_common.h" +#include "format.h" +#include "avsharedmemory.h" +#include "avcodec_video_decoder.h" +#include "event.h" +#include "event_bus.h" +#include "event_sender.h" +#include "eventbus_handler.h" +#include "event_registration.h" + +#include "data_buffer.h" +#include "distributed_camera_errno.h" +#include "image_common_type.h" +#include "dcamera_codec_event.h" +#include "abstract_data_process.h" +#include "dcamera_pipeline_source.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraPipelineSource; +class DecodeVideoCallback; + +class DecodeDataProcess : public EventSender, public EventBusHandler, public AbstractDataProcess, + public std::enable_shared_from_this { +public: + DecodeDataProcess(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig, + const std::shared_ptr& eventBusPipeline, + const std::weak_ptr& callbackPipSource) + : sourceConfig_(sourceConfig), targetConfig_(targetConfig), eventBusPipeline_(eventBusPipeline), + callbackPipelineSource_(callbackPipSource) {} + ~DecodeDataProcess(); + + int32_t InitNode() override; + int32_t ProcessData(std::vector>& inputBuffers) override; + void ReleaseProcessNode() override; + void OnEvent(DCameraCodecEvent& ev) override; + + void OnError(); + void OnInputBufferAvailable(uint32_t index); + void OnOutputFormatChanged(const Media::Format &format); + void OnOutputBufferAvailable(uint32_t index, const Media::AVCodecBufferInfo& info, + const Media::AVCodecBufferFlag& flag); + void GetDecoderOutputBuffer(const sptr& surface); + VideoConfigParams GetSourceConfig() const; + VideoConfigParams GetTargetConfig() const; + +private: + bool IsInDecoderRange(const VideoConfigParams& curConfig); + bool IsConvertible(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig); + void InitCodecEvent(); + int32_t InitDecoder(); + int32_t InitDecoderMetadataFormat(); + int32_t SetDecoderOutputSurface(); + void ReleaseDecoder(); + int32_t FeedDecoderInputBuffer(); + int64_t GetDecoderTimeStamp(); + int32_t GetAlignedHeight(); + void CopyDecodedImage(const sptr& surBuf, int64_t timeStampUs, int32_t alignedWidth, + int32_t alignedHeight); + int32_t CopyYUVPlaneByRow(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo); + int32_t CheckCopyImageInfo(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo); + bool IsCorrectImageUnitInfo(const ImageUnitInfo& imgInfo); + void PostOutputDataBuffers(std::shared_ptr& outputBuffer); + int32_t DecodeDone(std::vector> outputBuffers); + +private: + const static int32_t VIDEO_DECODER_QUEUE_MAX = 1000; + const static int32_t MAX_YUV420_BUFFER_SIZE = 1920 * 1080 * 3 / 2 * 2; + const static uint32_t MAX_FRAME_RATE = 30; + const static uint32_t MIN_VIDEO_WIDTH = 320; + const static uint32_t MIN_VIDEO_HEIGHT = 240; + const static uint32_t MAX_VIDEO_WIDTH = 1920; + const static uint32_t MAX_VIDEO_HEIGHT = 1080; + const static int32_t FIRST_FRAME_INPUT_NUM = 2; + + std::mutex mtxDecoderState_; + std::mutex mtxHoldCount_; + VideoConfigParams sourceConfig_; + VideoConfigParams targetConfig_; + std::shared_ptr eventBusPipeline_; + std::weak_ptr callbackPipelineSource_; + std::shared_ptr eventBusDecode_ = nullptr; + std::shared_ptr eventBusRegHandleDecode_ = nullptr; + std::shared_ptr eventBusRegHandlePipeline2Decode_ = nullptr; + std::shared_ptr videoDecoder_ = nullptr; + std::shared_ptr decodeVideoCallback_ = nullptr; + sptr decodeConsumerSurface_ = nullptr; + sptr decodeProducerSurface_ = nullptr; + + bool isDecoderProcess_ = false; + int32_t waitDecoderOutputCount_ = 0; + int32_t alignedHeight_ = 0; + int64_t lastFeedDecoderInputBufferTimeUs_ = 0; + int64_t outputTimeStampUs_ = 0; + std::string processType_; + Media::Format metadataFormat_; + Media::Format decodeOutputFormat_; + Media::AVCodecBufferInfo outputInfo_; + std::queue> inputBuffersQueue_; + std::queue availableInputIndexsQueue_; +}; + +class DecodeSurfaceListener : public IBufferConsumerListener { +public: + DecodeSurfaceListener(sptr surface, std::weak_ptr decodeVideoNode) + : surface_(surface), decodeVideoNode_(decodeVideoNode) {} + ~DecodeSurfaceListener() = default; + + void OnBufferAvailable() override; + void SetSurface(const sptr& surface); + void SetDecodeVideoNode(const std::weak_ptr& decodeVideoNode); + +private: + sptr surface_; + std::weak_ptr decodeVideoNode_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/pipeline_node/multimedia_codec/decode_video_callback.h b/services/data_process/include/pipeline_node/multimedia_codec/decode_video_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..4749a8c8f14f542724832a000c8258c7586c8387 --- /dev/null +++ b/services/data_process/include/pipeline_node/multimedia_codec/decode_video_callback.h @@ -0,0 +1,45 @@ +/* + * 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_DECODE_VIDEO_CALLBACK_H +#define OHOS_DECODE_VIDEO_CALLBACK_H + +#include "media_errors.h" +#include "avcodec_common.h" +#include "format.h" + +#include "decode_data_process.h" + +namespace OHOS { +namespace DistributedHardware { +class DecodeDataProcess; + +class DecodeVideoCallback : public Media::AVCodecCallback { +public: + explicit DecodeVideoCallback(const std::weak_ptr& decodeVideoNode) + : decodeVideoNode_(decodeVideoNode) {} + ~DecodeVideoCallback() = default; + + void OnError(Media::AVCodecErrorType errorType, int32_t errorCode) override; + void OnInputBufferAvailable(uint32_t index) override; + void OnOutputFormatChanged(const Media::Format &format) override; + void OnOutputBufferAvailable(uint32_t index, Media::AVCodecBufferInfo info, + Media::AVCodecBufferFlag flag) override; +private: + std::weak_ptr decodeVideoNode_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/pipeline_node/multimedia_codec/encode_data_process.h b/services/data_process/include/pipeline_node/multimedia_codec/encode_data_process.h new file mode 100644 index 0000000000000000000000000000000000000000..ba265fa51c5cdcaaee04dc93a36801333dbad460 --- /dev/null +++ b/services/data_process/include/pipeline_node/multimedia_codec/encode_data_process.h @@ -0,0 +1,124 @@ +/* + * 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_ENCODE_DATA_PROCESS_H +#define OHOS_ENCODE_DATA_PROCESS_H + +#include "securec.h" +#include +#include +#include + +#include "surface.h" +#include "media_errors.h" +#include "avcodec_common.h" +#include "format.h" +#include "avsharedmemory.h" +#include "avcodec_video_encoder.h" + +#include "data_buffer.h" +#include "distributed_camera_errno.h" +#include "image_common_type.h" +#include "abstract_data_process.h" +#include "dcamera_pipeline_sink.h" + +namespace OHOS { +namespace DistributedHardware { +class DCameraPipelineSink; +class EncodeVideoCallback; + +class EncodeDataProcess : public AbstractDataProcess, public std::enable_shared_from_this { +public: + EncodeDataProcess(const VideoConfigParams &sourceConfig, const VideoConfigParams &targetConfig, + const std::weak_ptr& callbackPipSink) + : sourceConfig_(sourceConfig), targetConfig_(targetConfig), callbackPipelineSink_(callbackPipSink) {} + ~EncodeDataProcess(); + + int32_t InitNode() override; + int32_t ProcessData(std::vector>& inputBuffers) override; + void ReleaseProcessNode() override; + + void OnError(); + void OnInputBufferAvailable(uint32_t index); + void OnOutputFormatChanged(const Media::Format &format); + void OnOutputBufferAvailable(uint32_t index, Media::AVCodecBufferInfo info, Media::AVCodecBufferFlag flag); + VideoConfigParams GetSourceConfig() const; + VideoConfigParams GetTargetConfig() const; + +private: + bool IsInEncoderRange(const VideoConfigParams& curConfig); + bool IsConvertible(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig); + int32_t InitEncoder(); + int32_t InitEncoderMetadataFormat(); + int32_t InitEncoderBitrateFormat(); + int32_t FeedEncoderInputBuffer(std::shared_ptr& inputBuffer); + sptr GetEncoderInputSurfaceBuffer(); + int64_t GetEncoderTimeStamp(); + int32_t GetEncoderOutputBuffer(uint32_t index, Media::AVCodecBufferInfo info); + int32_t EncodeDone(std::vector> outputBuffers); + +private: + const static int32_t ENCODER_STRIDE_ALIGNMENT = 8; + const static int64_t NORM_YUV420_BUFFER_SIZE = 1920 * 1080 * 3 / 2; + const static uint32_t MAX_FRAME_RATE = 30; + const static uint32_t MIN_VIDEO_WIDTH = 320; + const static uint32_t MIN_VIDEO_HEIGHT = 240; + const static uint32_t MAX_VIDEO_WIDTH = 1920; + const static uint32_t MAX_VIDEO_HEIGHT = 1080; + const static int32_t IDR_FRAME_INTERVAL_MS = 300; + const static int32_t FIRST_FRAME_OUTPUT_NUM = 2; + + const static int64_t WIDTH_320_HEIGHT_240 = 320 * 240; + const static int64_t WIDTH_480_HEIGHT_360 = 480 * 360; + const static int64_t WIDTH_640_HEIGHT_360 = 640 * 360; + const static int64_t WIDTH_640_HEIGHT_480 = 640 * 480; + const static int64_t WIDTH_720_HEIGHT_540 = 720 * 540; + const static int64_t WIDTH_960_HEIGHT_540 = 960 * 540; + const static int64_t WIDTH_960_HEIGHT_720 = 960 * 720; + const static int64_t WIDTH_1280_HEIGHT_720 = 1280 * 720; + const static int64_t WIDTH_1440_HEIGHT_1080 = 1440 * 1080; + const static int64_t WIDTH_1920_HEIGHT_1080 = 1920 * 1080; + const static int32_t BITRATE_500000 = 500000; + const static int32_t BITRATE_1110000 = 1110000; + const static int32_t BITRATE_1500000 = 1500000; + const static int32_t BITRATE_1800000 = 1800000; + const static int32_t BITRATE_2100000 = 2100000; + const static int32_t BITRATE_2300000 = 2300000; + const static int32_t BITRATE_2800000 = 2800000; + const static int32_t BITRATE_3400000 = 3400000; + const static int32_t BITRATE_5000000 = 5000000; + const static int32_t BITRATE_6000000 = 6000000; + const static std::map ENCODER_BITRATE_TABLE; + + std::mutex mtxEncoderState_; + std::mutex mtxHoldCount_; + VideoConfigParams sourceConfig_; + VideoConfigParams targetConfig_; + std::weak_ptr callbackPipelineSink_; + std::shared_ptr videoEncoder_ = nullptr; + std::shared_ptr encodeVideoCallback_ = nullptr; + sptr encodeProducerSurface_ = nullptr; + + bool isEncoderProcess_ = false; + int32_t waitEncoderOutputCount_ = 0; + int64_t lastFeedEncoderInputBufferTimeUs_ = 0; + int64_t inputTimeStampUs_ = 0; + std::string processType_; + Media::Format metadataFormat_; + Media::Format encodeOutputFormat_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/pipeline_node/multimedia_codec/encode_video_callback.h b/services/data_process/include/pipeline_node/multimedia_codec/encode_video_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..c91055cc8ee8396bf38d708355f70f072a313a08 --- /dev/null +++ b/services/data_process/include/pipeline_node/multimedia_codec/encode_video_callback.h @@ -0,0 +1,45 @@ +/* + * 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_DECODE_VIDEO_CALLBACK_H +#define OHOS_DECODE_VIDEO_CALLBACK_H + +#include "media_errors.h" +#include "avcodec_common.h" +#include "format.h" + +#include "encode_data_process.h" + +namespace OHOS { +namespace DistributedHardware { +class EncodeDataProcess; + +class EncodeVideoCallback : public Media::AVCodecCallback { +public: + explicit EncodeVideoCallback(const std::weak_ptr& encodeVideoNode) + : encodeVideoNode_(encodeVideoNode) {} + ~EncodeVideoCallback() = default; + + void OnError(Media::AVCodecErrorType errorType, int32_t errorCode) override; + void OnInputBufferAvailable(uint32_t index) override; + void OnOutputFormatChanged(const Media::Format &format) override; + void OnOutputBufferAvailable(uint32_t index, Media::AVCodecBufferInfo info, + Media::AVCodecBufferFlag flag) override; +private: + std::weak_ptr encodeVideoNode_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/include/utils/image_common_type.h b/services/data_process/include/utils/image_common_type.h new file mode 100644 index 0000000000000000000000000000000000000000..9f692ea8e4693c40cc217191696db15495f7a5e5 --- /dev/null +++ b/services/data_process/include/utils/image_common_type.h @@ -0,0 +1,78 @@ +/* + * 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_IMAGE_COMMON_TYPE_H +#define OHOS_IMAGE_COMMON_TYPE_H + +#include + +namespace OHOS { +namespace DistributedHardware { +enum class PipelineType : int32_t { + VIDEO = 0, + PHOTO_JPEG, +}; + +enum class VideoCodecType : int32_t { + NO_CODEC = 0, + CODEC_H264, + CODEC_H265, +}; + +enum class Videoformat : int32_t { + YUVI420 = 0, + NV12, + NV21, +}; + +class VideoConfigParams { +public: + VideoConfigParams(VideoCodecType videoCodec, Videoformat pixelFormat, uint32_t frameRate, uint32_t width, + uint32_t height) + : videoCodec_(videoCodec), pixelFormat_(pixelFormat), frameRate_(frameRate), width_ (width), height_(height) + {} + ~VideoConfigParams() = default; + + void SetVideoCodecType(VideoCodecType videoCodec); + void SetVideoformat(Videoformat pixelFormat); + void SetFrameRate(uint32_t frameRate); + void SetWidthAndHeight(uint32_t width, uint32_t height); + VideoCodecType GetVideoCodecType() const; + Videoformat GetVideoformat() const; + uint32_t GetFrameRate() const; + uint32_t GetWidth() const; + uint32_t GetHeight() const; + +private: + VideoCodecType videoCodec_; + Videoformat pixelFormat_; + uint32_t frameRate_; + uint32_t width_; + uint32_t height_; +}; + +struct ImageUnitInfo { + Videoformat colorFormat; + int32_t width; + int32_t height; + int32_t alignedWidth; + int32_t alignedHeight; + size_t chromaOffset; + size_t imgSize; + uint8_t *imgData; +}; +} +} +#endif \ No newline at end of file diff --git a/services/data_process/src/pipeline/abstract_data_process.cpp b/services/data_process/src/pipeline/abstract_data_process.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfc7b793a970753a23c87de13d3c2d52395bf7c9 --- /dev/null +++ b/services/data_process/src/pipeline/abstract_data_process.cpp @@ -0,0 +1,37 @@ +/* + * 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 "abstract_data_process.h" + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t AbstractDataProcess::SetNextNode(std::shared_ptr& nextDataProcess) +{ + if (nextDataProcess == nullptr) { + DHLOGE("Next data process is invalid."); + return DCAMERA_BAD_VALUE; + } + nextDataProcess_ = nextDataProcess; + return DCAMERA_OK; +} + +void AbstractDataProcess::SetNodeRank(size_t curNodeRank) +{ + nodeRank_ = curNodeRank; +} +} +} \ No newline at end of file diff --git a/services/data_process/src/pipeline/dcamera_pipeline_sink.cpp b/services/data_process/src/pipeline/dcamera_pipeline_sink.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bda1da7ff7c7b70498e8e0104dc2aa87fbc883f5 --- /dev/null +++ b/services/data_process/src/pipeline/dcamera_pipeline_sink.cpp @@ -0,0 +1,176 @@ +/* + * 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 "dcamera_pipeline_sink.h" + +#include "distributed_hardware_log.h" + +#include "encode_data_process.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string DCameraPipelineSink::PIPELINE_OWNER = "Sink"; + +DCameraPipelineSink::~DCameraPipelineSink() +{ + if (isProcess_) { + DHLOGD("~DCameraPipelineSink : Destroy sink data process pipeline."); + DestroyDataProcessPipeline(); + } +} + +int32_t DCameraPipelineSink::CreateDataProcessPipeline(PipelineType piplineType, + const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig, + const std::shared_ptr& listener) +{ + DHLOGD("Create sink data process pipeline."); + switch (piplineType) { + case PipelineType::VIDEO: + if (!(IsInRange(sourceConfig) && IsInRange(targetConfig))) { + DHLOGE("Source config or target config of sink pipeline are invalid."); + return DCAMERA_BAD_VALUE; + } + break; + default: + DHLOGE("JPEG or other pipeline type are not supported in sink pipeline."); + return DCAMERA_NOT_FOUND; + } + if (listener == nullptr) { + DHLOGE("The process listener of sink pipeline is empty."); + return DCAMERA_BAD_VALUE; + } + if (pipelineHead_ != nullptr) { + DHLOGD("The sink pipeline already exists."); + return DCAMERA_OK; + } + + int32_t err = InitDCameraPipNodes(sourceConfig, targetConfig); + if (err != DCAMERA_OK) { + DestroyDataProcessPipeline(); + return err; + } + piplineType_ = piplineType; + processListener_ = listener; + isProcess_ = true; + return DCAMERA_OK; +} + +bool DCameraPipelineSink::IsInRange(const VideoConfigParams& curConfig) +{ + return (curConfig.GetFrameRate() <= MAX_FRAME_RATE || curConfig.GetWidth() >= MIN_VIDEO_WIDTH || + curConfig.GetWidth() <= MAX_VIDEO_WIDTH || curConfig.GetHeight() >= MIN_VIDEO_HEIGHT || + curConfig.GetHeight() <= MAX_VIDEO_HEIGHT); +} + +int32_t DCameraPipelineSink::InitDCameraPipNodes(const VideoConfigParams& sourceConfig, + const VideoConfigParams& targetConfig) +{ + DHLOGD("Init sink DCamera pipeline Nodes."); + if (piplineType_ == PipelineType::PHOTO_JPEG) { + DHLOGE("JPEG data process is not supported."); + return DCAMERA_NOT_FOUND; + } + + pipNodeRanks_.push_back(std::make_shared(sourceConfig, targetConfig, shared_from_this())); + if (pipNodeRanks_.size() == 0) { + DHLOGD("Creating an empty sink pipeline."); + pipelineHead_ = nullptr; + return DCAMERA_BAD_VALUE; + } + for (size_t i = 0; i < pipNodeRanks_.size(); i++) { + pipNodeRanks_[i]->SetNodeRank(i); + int32_t err = pipNodeRanks_[i]->InitNode(); + if (err != DCAMERA_OK) { + DHLOGE("Init sink DCamera pipeline Node [%d] failed.", i); + return DCAMERA_INIT_ERR; + } + if (i == 0) { + continue; + } + err = pipNodeRanks_[i - 1]->SetNextNode(pipNodeRanks_[i]); + if (err != DCAMERA_OK) { + DHLOGE("Set the next node of Node [%d] failed in sink pipeline.", i - 1); + return DCAMERA_INIT_ERR; + } + } + DHLOGD("All nodes have been linked in sink pipeline."); + pipelineHead_ = pipNodeRanks_[0]; + return DCAMERA_OK; +} + +int32_t DCameraPipelineSink::ProcessData(std::vector>& dataBuffers) +{ + DHLOGD("Process data buffers in sink pipeline."); + if (piplineType_ == PipelineType::PHOTO_JPEG) { + DHLOGE("JPEG data process is not supported in sink pipeline."); + return DCAMERA_NOT_FOUND; + } + if (pipelineHead_ == nullptr) { + DHLOGE("The current sink pipeline node is empty. Processing failed."); + return DCAMERA_INIT_ERR; + } + if (dataBuffers.empty()) { + DHLOGE("Sink Pipeline Input Data buffers is null."); + return DCAMERA_BAD_VALUE; + } + if (!isProcess_) { + DHLOGE("Sink pipeline node occurred error or start destroy."); + return DCAMERA_DISABLE_PROCESS; + } + + int32_t err = pipelineHead_->ProcessData(dataBuffers); + if (err != DCAMERA_OK) { + DHLOGE("Sink plpeline process data buffers fail."); + } + return err; +} + +void DCameraPipelineSink::DestroyDataProcessPipeline() +{ + DHLOGD("Destroy sink data process pipeline start."); + isProcess_ = false; + if (pipelineHead_ != nullptr) { + pipelineHead_->ReleaseProcessNode(); + pipelineHead_ = nullptr; + } + + pipNodeRanks_.clear(); + piplineType_ = PipelineType::VIDEO; + processListener_ = nullptr; + DHLOGD("Destroy sink data process pipeline end."); +} + +void DCameraPipelineSink::OnError(DataProcessErrorType errorType) +{ + DHLOGE("A runtime error occurred in sink pipeline."); + isProcess_ = false; + if (processListener_ == nullptr) { + DHLOGE("The process listener of sink pipeline is empty."); + return; + } + processListener_->OnError(errorType); +} + +void DCameraPipelineSink::OnProcessedVideoBuffer(const std::shared_ptr& videoResult) +{ + DHLOGD("Sink pipeline output the processed video buffer."); + if (processListener_ == nullptr) { + DHLOGE("The process listener of sink pipeline is empty."); + return; + } + processListener_->OnProcessedVideoBuffer(videoResult); +} +} +} \ No newline at end of file diff --git a/services/data_process/src/pipeline/dcamera_pipeline_source.cpp b/services/data_process/src/pipeline/dcamera_pipeline_source.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5aa728f99760f83269e18caa9a0717101381316b --- /dev/null +++ b/services/data_process/src/pipeline/dcamera_pipeline_source.cpp @@ -0,0 +1,209 @@ +/* + * 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 "dcamera_pipeline_source.h" + +#include "distributed_hardware_log.h" + +#include "decode_data_process.h" +#include "fps_controller_process.h" + +namespace OHOS { +namespace DistributedHardware { +const std::string DCameraPipelineSource::PIPELINE_OWNER = "Source"; + +DCameraPipelineSource::~DCameraPipelineSource() +{ + if (isProcess_) { + DHLOGD("~DCameraPipelineSource : Destroy source data process pipeline."); + DestroyDataProcessPipeline(); + } +} + +int32_t DCameraPipelineSource::CreateDataProcessPipeline(PipelineType piplineType, + const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig, + const std::shared_ptr& listener) +{ + DHLOGD("Create source data process pipeline."); + switch (piplineType) { + case PipelineType::VIDEO: + if (!(IsInRange(sourceConfig) && IsInRange(targetConfig))) { + DHLOGE("Source config or target config of source pipeline are invalid."); + return DCAMERA_BAD_VALUE; + } + break; + default: + DHLOGE("JPEG or other pipeline type are not supported in source pipeline."); + return DCAMERA_NOT_FOUND; + } + if (listener == nullptr) { + DHLOGE("The process listener of source pipeline is empty."); + return DCAMERA_BAD_VALUE; + } + + if (pipelineHead_ != nullptr) { + DHLOGD("The source pipeline already exists."); + return DCAMERA_OK; + } + + InitDCameraPipEvent(); + int32_t err = InitDCameraPipNodes(sourceConfig, targetConfig); + if (err != DCAMERA_OK) { + DestroyDataProcessPipeline(); + return err; + } + piplineType_ = piplineType; + processListener_ = listener; + isProcess_ = true; + return DCAMERA_OK; +} + +bool DCameraPipelineSource::IsInRange(const VideoConfigParams& curConfig) +{ + return (curConfig.GetFrameRate() <= MAX_FRAME_RATE || curConfig.GetWidth() >= MIN_VIDEO_WIDTH || + curConfig.GetWidth() <= MAX_VIDEO_WIDTH || curConfig.GetHeight() >= MIN_VIDEO_HEIGHT || + curConfig.GetHeight() <= MAX_VIDEO_HEIGHT); +} + +void DCameraPipelineSource::InitDCameraPipEvent() +{ + DHLOGD("Init source DCamera pipeline event to asynchronously process data."); + eventBusSource_ = std::make_shared(); + DCameraPipelineEvent pipelineEvent(*this, std::make_shared()); + eventBusSource_->AddHandler(pipelineEvent.GetType(), *this); +} + +int32_t DCameraPipelineSource::InitDCameraPipNodes(const VideoConfigParams& sourceConfig, + const VideoConfigParams& targetConfig) +{ + DHLOGD("Init source DCamera pipeline Nodes."); + if (piplineType_ == PipelineType::PHOTO_JPEG) { + DHLOGE("JPEG data process is not supported."); + return DCAMERA_NOT_FOUND; + } + if (eventBusSource_ == nullptr) { + DHLOGE("eventBusSource is nullptr."); + return DCAMERA_BAD_VALUE; + } + pipNodeRanks_.push_back(std::make_shared(sourceConfig, targetConfig, + eventBusSource_, shared_from_this())); + if (pipNodeRanks_.size() == 0) { + DHLOGD("Creating an empty source pipeline."); + pipelineHead_ = nullptr; + return DCAMERA_BAD_VALUE; + } + for (size_t i = 0; i < pipNodeRanks_.size(); i++) { + pipNodeRanks_[i]->SetNodeRank(i); + int32_t err = pipNodeRanks_[i]->InitNode(); + if (err != DCAMERA_OK) { + DHLOGE("Init source DCamera pipeline Node [%d] failed.", i); + return DCAMERA_INIT_ERR; + } + if (i == 0) { + continue; + } + err = pipNodeRanks_[i - 1]->SetNextNode(pipNodeRanks_[i]); + if (err != DCAMERA_OK) { + DHLOGE("Set the next node of Node [%d] failed in source pipeline.", i - 1); + return DCAMERA_INIT_ERR; + } + } + DHLOGD("All nodes have been linked in source pipeline."); + pipelineHead_ = pipNodeRanks_[0]; + return DCAMERA_OK; +} + +int32_t DCameraPipelineSource::ProcessData(std::vector>& dataBuffers) +{ + DHLOGD("Process data buffers in source pipeline."); + if (piplineType_ == PipelineType::PHOTO_JPEG) { + DHLOGE("JPEG data process is not supported in source pipeline."); + return DCAMERA_NOT_FOUND; + } + if (pipelineHead_ == nullptr) { + DHLOGE("The current source pipeline node is empty. Processing failed."); + return DCAMERA_INIT_ERR; + } + if (dataBuffers.empty()) { + DHLOGE("Source Pipeline Input data buffers is empty."); + return DCAMERA_BAD_VALUE; + } + if (!isProcess_) { + DHLOGE("Source Pipeline node occurred error or start destroy."); + return DCAMERA_DISABLE_PROCESS; + } + + DHLOGD("Send asynchronous event to process data in source pipeline."); + std::shared_ptr pipConfigSource = std::make_shared(piplineType_, + PIPELINE_OWNER, dataBuffers); + DCameraPipelineEvent dCamPipelineEvent(*this, pipConfigSource); + if (eventBusSource_ == nullptr) { + DHLOGE("eventBusSource_ is nullptr."); + return DCAMERA_BAD_VALUE; + } + eventBusSource_->PostEvent(dCamPipelineEvent, POSTMODE::POST_ASYNC); + return DCAMERA_OK; +} + +void DCameraPipelineSource::DestroyDataProcessPipeline() +{ + DHLOGD("Destroy source data process pipeline start."); + isProcess_ = false; + if (pipelineHead_ != nullptr) { + pipelineHead_->ReleaseProcessNode(); + pipelineHead_ = nullptr; + } + eventBusSource_ = nullptr; + processListener_ = nullptr; + pipNodeRanks_.clear(); + piplineType_ = PipelineType::VIDEO; + DHLOGD("Destroy source data process pipeline end."); +} + +void DCameraPipelineSource::OnEvent(DCameraPipelineEvent& ev) +{ + DHLOGD("Receive asynchronous event then start process data in source pipeline."); + std::shared_ptr pipelineConfig = ev.GetPipelineConfig(); + std::vector> inputBuffers = pipelineConfig->GetDataBuffers(); + if (inputBuffers.empty()) { + DHLOGE("Receiving process data buffers is empty in source pipeline."); + OnError(ERROR_PIPELINE_EVENTBUS); + return; + } + pipelineHead_->ProcessData(inputBuffers); +} + +void DCameraPipelineSource::OnError(DataProcessErrorType errorType) +{ + DHLOGE("A runtime error occurred in the source pipeline."); + isProcess_ = false; + if (processListener_ == nullptr) { + DHLOGE("The process listener of source pipeline is empty."); + return; + } + processListener_->OnError(errorType); +} + +void DCameraPipelineSource::OnProcessedVideoBuffer(const std::shared_ptr& videoResult) +{ + DHLOGD("Source pipeline output the processed video buffer."); + if (processListener_ == nullptr) { + DHLOGE("The process listener of source pipeline is empty."); + return; + } + processListener_->OnProcessedVideoBuffer(videoResult); +} +} +} \ No newline at end of file diff --git a/services/data_process/src/pipeline_node/colorspace_conversion/convert_nv12_to_nv21.cpp b/services/data_process/src/pipeline_node/colorspace_conversion/convert_nv12_to_nv21.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b79083121b90602552c16fef4f4b28df4ef29551 --- /dev/null +++ b/services/data_process/src/pipeline_node/colorspace_conversion/convert_nv12_to_nv21.cpp @@ -0,0 +1,364 @@ +/* + * 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 "convert_nv12_to_nv21.h" + +#include "distributed_hardware_log.h" + +#include "distributed_camera_errno.h" + +namespace OHOS { +namespace DistributedHardware { +bool ConvertNV12ToNV21::IsConvertible(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig) +{ + return (sourceConfig.GetVideoformat() == Videoformat::NV12 && targetConfig.GetVideoformat() == Videoformat::NV21 && + sourceConfig.GetWidth() == targetConfig.GetWidth() && sourceConfig.GetHeight() == targetConfig.GetHeight()); +} + +int32_t ConvertNV12ToNV21::GetImageUnitInfo(ImageUnitInfo& imgInfo, const std::shared_ptr& imgBuf) +{ + if (imgBuf == nullptr) { + DHLOGE("GetImageUnitInfo failed, imgBuf is nullptr."); + return DCAMERA_BAD_VALUE; + } + + bool findErr = true; + int32_t colorFormat = 0; + findErr = findErr && imgBuf->FindInt32("Videoformat", colorFormat); + if (!findErr) { + DHLOGE("GetImageUnitInfo failed, Videoformat is null."); + return DCAMERA_NOT_FOUND; + } + if (colorFormat != static_cast(Videoformat::YUVI420) && + colorFormat != static_cast(Videoformat::NV12) && + colorFormat != static_cast(Videoformat::NV21)) { + DHLOGE("GetImageUnitInfo failed, colorFormat %d are not supported.", colorFormat); + return DCAMERA_NOT_FOUND; + } + imgInfo.colorFormat = static_cast(colorFormat); + findErr = findErr && imgBuf->FindInt32("width", imgInfo.width); + findErr = findErr && imgBuf->FindInt32("height", imgInfo.height); + findErr = findErr && imgBuf->FindInt32("alignedWidth", imgInfo.alignedWidth); + findErr = findErr && imgBuf->FindInt32("alignedHeight", imgInfo.alignedHeight); + if (!findErr) { + DHLOGE("GetImageUnitInfo failed, width %d, height %d, alignedWidth %d, alignedHeight %d.", + imgInfo.width, imgInfo.height, imgInfo.alignedWidth, imgInfo.alignedHeight); + return DCAMERA_NOT_FOUND; + } + + imgInfo.chromaOffset = static_cast(imgInfo.alignedWidth * imgInfo.alignedHeight); + imgInfo.imgSize = imgBuf->Size(); + imgInfo.imgData = imgBuf->Data(); + if (imgInfo.imgData == nullptr) { + DHLOGE("Get the imgData of the imgBuf failed."); + return DCAMERA_BAD_VALUE; + } + DHLOGD("imgBuf info : Videoformat %d, alignedWidth %d, alignedHeight %d, width %d, height %d, chromaOffset %d, " + + "imgSize %d.", imgInfo.colorFormat, imgInfo.width, imgInfo.height, imgInfo.alignedWidth, + imgInfo.alignedHeight, imgInfo.chromaOffset, imgInfo.imgSize); + return DCAMERA_OK; +} + +bool ConvertNV12ToNV21::IsCorrectImageUnitInfo(const ImageUnitInfo& imgInfo) +{ + int32_t y2UvRatio = 2; + int32_t bytesPerPixel = 3; + size_t expectedImgSize = static_cast(imgInfo.alignedWidth * imgInfo.alignedHeight * + bytesPerPixel / y2UvRatio); + size_t expectedChromaOffset = static_cast(imgInfo.alignedWidth * imgInfo.alignedHeight); + return (imgInfo.width <= imgInfo.alignedWidth && imgInfo.height <= imgInfo.alignedHeight && + imgInfo.imgSize >= expectedImgSize && imgInfo.chromaOffset == expectedChromaOffset); +} + +int32_t ConvertNV12ToNV21::CheckColorConvertInfo(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo) +{ + if (srcImgInfo.imgData == nullptr || dstImgInfo.imgData == nullptr) { + DHLOGE("The imgData of srcImgInfo or the imgData of dstImgInfo are null!"); + return DCAMERA_BAD_VALUE; + } + if (srcImgInfo.colorFormat != Videoformat::NV12 && dstImgInfo.colorFormat != Videoformat::NV21) { + DHLOGE("CopyInfo error : srcImgInfo colorFormat %d, dstImgInfo colorFormat %d.", + srcImgInfo.colorFormat, dstImgInfo.colorFormat); + return DCAMERA_BAD_VALUE; + } + + if (!IsCorrectImageUnitInfo(srcImgInfo)) { + DHLOGE("srcImginfo fail: width %d, height %d, alignedWidth %d, alignedHeight %d, chromaOffset %lld, " + + "imgSize %lld.", srcImgInfo.width, srcImgInfo.height, srcImgInfo.alignedWidth, srcImgInfo.alignedHeight, + srcImgInfo.chromaOffset, srcImgInfo.imgSize); + return DCAMERA_BAD_VALUE; + } + if (!IsCorrectImageUnitInfo(dstImgInfo)) { + DHLOGE("dstImginfo fail: width %d, height %d, alignedWidth %d, alignedHeight %d, chromaOffset %lld, " + + "imgSize %lld.", dstImgInfo.width, dstImgInfo.height, dstImgInfo.alignedWidth, dstImgInfo.alignedHeight, + dstImgInfo.chromaOffset, dstImgInfo.imgSize); + return DCAMERA_BAD_VALUE; + } + + if (dstImgInfo.width > srcImgInfo.alignedWidth || dstImgInfo.height > srcImgInfo.alignedHeight) { + DHLOGE("Comparison ImgInfo fail: dstwidth %d, dstheight %d, srcAlignedWidth %d, srcAlignedHeight %d.", + dstImgInfo.width, dstImgInfo.height, srcImgInfo.alignedWidth, srcImgInfo.alignedHeight); + return DCAMERA_BAD_VALUE; + } + return DCAMERA_OK; +} + +/** +* @brief Separate a row of srcUVPlane into half a row of dstUPlane and half a row of dstVPlane. For example, +* converts the UVPlane memory arrangement of NV12 to the UV memory arrangement of YUVI420. Note that the +* stride and width of the dstImage must be the same. +*/ +void ConvertNV12ToNV21::SeparateUVPlaneByRow(const uint8_t *srcUVPlane, uint8_t *dstUPlane, uint8_t *dstVPlane, + int32_t srcHalfWidth) +{ + int32_t memoryOffset0 = 0; + int32_t memoryOffset1 = 1; + int32_t memoryOffset2 = 2; + int32_t memoryOffset3 = 3; + int32_t perSeparatebytes = 4; + for (int32_t x = 0; x < srcHalfWidth - 1; x += memoryOffset2) { + dstUPlane[x] = srcUVPlane[memoryOffset0]; + dstUPlane[x + memoryOffset1] = srcUVPlane[memoryOffset2]; + dstVPlane[x] = srcUVPlane[memoryOffset1]; + dstVPlane[x + memoryOffset1] = srcUVPlane[memoryOffset3]; + srcUVPlane += perSeparatebytes; + } + if (static_cast(srcHalfWidth) & 1) { + dstUPlane[srcHalfWidth - 1] = srcUVPlane[memoryOffset0]; + dstVPlane[srcHalfWidth - 1] = srcUVPlane[memoryOffset1]; + } +} + +int32_t ConvertNV12ToNV21::SeparateNV12UVPlane(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo) +{ + int32_t ret = CheckColorConvertInfo(srcImgInfo, dstImgInfo); + if (ret != DCAMERA_OK) { + DHLOGE("ColorConvert : CheckColorConvertInfo failed."); + return ret; + } + + int32_t y2UvRatio = 2; + uint8_t *srcUVPlane = srcImgInfo.imgData + srcImgInfo.chromaOffset; + int32_t srcUVStride = srcImgInfo.alignedWidth; + uint8_t *dstUPlane = dstImgInfo.imgData + dstImgInfo.chromaOffset; + int32_t dstUStride = dstImgInfo.alignedWidth / y2UvRatio; + uint8_t *dstVPlane = dstUPlane + (dstImgInfo.chromaOffset / y2UvRatio) / y2UvRatio; + int32_t dstVStride = dstImgInfo.alignedWidth / y2UvRatio; + int32_t width = srcImgInfo.width / y2UvRatio; + int32_t height = srcImgInfo.height / y2UvRatio; + DHLOGD("srcUVStride %d, dstUStride %d, dstVStride %d, src half width %d, src half height %d.", + srcUVStride, dstUStride, dstVStride, width, height); + + /* Negative height means invert the image. */ + if (height < 0) { + height = -height; + dstUPlane = dstUPlane + (height - 1) * dstUStride; + dstVPlane = dstVPlane + (height - 1) * dstVStride; + dstUStride = -dstUStride; + dstVStride = -dstVStride; + } + /* No black border of srcImage and dstImage, and the strides of srcImage and dstImage are equal. */ + if (srcUVStride == width * y2UvRatio && dstUStride == width && dstVStride == width) { + SeparateUVPlaneByRow(srcUVPlane, dstUPlane, dstVPlane, width * height); + return DCAMERA_OK; + } + /* Black borders exist in srcImage or dstImage. */ + for (int32_t y = 0; y < height; ++y) { + SeparateUVPlaneByRow(srcUVPlane, dstUPlane, dstVPlane, width); + dstUPlane += dstUStride; + dstVPlane += dstVStride; + srcUVPlane += srcUVStride; + } + return DCAMERA_OK; +} + +/** +* @brief Combine half a row of srcUPlane and half a row of srcVPlane into a row of dstUVPlane. For example, +* converts the UVPlane memory arrangement of YUVI420 to the UV memory arrangement of NV12. Note that the +* stride and width of the srcImage must be the same. +*/ +void ConvertNV12ToNV21::CombineUVPlaneByRow(const uint8_t *srcUPlane, const uint8_t *srcVPlane, uint8_t *dstUVPlane, + int32_t dstHalfWidth) +{ + int32_t memoryOffset0 = 0; + int32_t memoryOffset1 = 1; + int32_t memoryOffset2 = 2; + int32_t memoryOffset3 = 3; + int32_t perCombinebytes = 4; + for (int32_t x = 0; x < dstHalfWidth - 1; x += memoryOffset2) { + dstUVPlane[memoryOffset0] = srcUPlane[x]; + dstUVPlane[memoryOffset1] = srcVPlane[x]; + dstUVPlane[memoryOffset2] = srcUPlane[x + memoryOffset1]; + dstUVPlane[memoryOffset3] = srcVPlane[x + memoryOffset1]; + dstUVPlane += perCombinebytes; + } + if (static_cast(dstHalfWidth) & 1) { + dstUVPlane[memoryOffset0] = srcUPlane[dstHalfWidth - 1]; + dstUVPlane[memoryOffset1] = srcVPlane[dstHalfWidth - 1]; + } +} + +int32_t ConvertNV12ToNV21::CombineNV12UVPlane(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo) +{ + int32_t ret = CheckColorConvertInfo(srcImgInfo, dstImgInfo); + if (ret != DCAMERA_OK) { + DHLOGE("ColorConvert : CheckColorConvertInfo failed."); + return ret; + } + + int32_t y2UvRatio = 2; + uint8_t *srcVPlane = srcImgInfo.imgData + srcImgInfo.chromaOffset; + int32_t srcVStride = srcImgInfo.alignedWidth / y2UvRatio; + uint8_t *srcUPlane = srcVPlane + (srcImgInfo.chromaOffset / y2UvRatio) / y2UvRatio; + int32_t srcUStride = srcImgInfo.alignedWidth / y2UvRatio; + uint8_t *dstUVPlane = dstImgInfo.imgData + dstImgInfo.chromaOffset; + int32_t dstUVStride = dstImgInfo.alignedWidth; + int32_t width = dstImgInfo.width / y2UvRatio; + int32_t height = dstImgInfo.height / y2UvRatio; + DHLOGD("srcUStride %d, srcVStride %d, dstUVStride %d, dst half width %d, dst half height %d.", + srcUStride, srcVStride, dstUVStride, width, height); + + /* Negative height means invert the image. */ + if (height < 0) { + height = -height; + dstUVPlane = dstUVPlane + (height - 1) * dstUVStride; + dstUVStride = -dstUVStride; + } + /* No black border of srcImage and dstImage, and the strides of srcImage and dstImage are equal. */ + if (srcUStride == width && srcVStride == width && dstUVStride == width * y2UvRatio) { + CombineUVPlaneByRow(srcUPlane, srcVPlane, dstUVPlane, width * height); + return DCAMERA_OK; + } + /* Black borders exist in srcImage or dstImage. */ + for (int32_t y = 0; y < height; ++y) { + CombineUVPlaneByRow(srcUPlane, srcVPlane, dstUVPlane, width); + srcUPlane += srcUStride; + srcVPlane += srcVStride; + dstUVPlane += dstUVStride; + } + return DCAMERA_OK; +} + +int32_t ConvertNV12ToNV21::CopyYPlane(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo) +{ + int32_t ret = CheckColorConvertInfo(srcImgInfo, dstImgInfo); + if (ret != DCAMERA_OK) { + DHLOGE("ColorConvert : CheckColorConvertInfo failed."); + return ret; + } + + errno_t err = EOK; + size_t totalCopyYPlaneSize = dstImgInfo.alignedWidth * dstImgInfo.height; + if (srcImgInfo.alignedWidth == dstImgInfo.width && dstImgInfo.alignedWidth == dstImgInfo.width) { + /* No black border of srcImage and dstImage, and the strides of srcImage and dstImage are equal. */ + err = memcpy_s(dstImgInfo.imgData, totalCopyYPlaneSize, srcImgInfo.imgData, totalCopyYPlaneSize); + if (err != EOK) { + DHLOGE("ColorConvert : memcpy_s CopyYPlaner failed by Coalesce rows."); + return DCAMERA_MEMORY_OPT_ERROR; + } + } else { + /* Black borders exist in srcImage or dstImage. */ + int32_t srcDataOffset = 0; + int32_t dstDataOffset = 0; + for (int32_t yh = 0; yh < dstImgInfo.height; yh++) { + DHLOGE("ColorConvert : memcpy_s Line[%d] source buffer failed.", yh); + err = memcpy_s(dstImgInfo.imgData + dstDataOffset, totalCopyYPlaneSize - dstDataOffset, + srcImgInfo.imgData + srcDataOffset, dstImgInfo.width); + if (err != EOK) { + DHLOGE("memcpy_s YPlane in line[%d] failed.", yh); + return DCAMERA_MEMORY_OPT_ERROR; + } + dstDataOffset += dstImgInfo.alignedWidth; + srcDataOffset += srcImgInfo.alignedWidth; + } + DHLOGD("ColorConvert :get valid yplane OK, srcImgInfo: alignedWidth %d, width %d, height %d. " + + "dstImgInfo: alignedWidth %d, width %d, height %d. dstDataOffset %d, srcDataOffset %d.", + srcImgInfo.alignedWidth, srcImgInfo.width, srcImgInfo.height, dstImgInfo.alignedWidth, + dstImgInfo.width, dstImgInfo.height, dstDataOffset, srcDataOffset); + } + return DCAMERA_OK; +} + +int32_t ConvertNV12ToNV21::ColorConvertNV12ToNV21(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo) +{ + int32_t err = CheckColorConvertInfo(srcImgInfo, dstImgInfo); + if (err != DCAMERA_OK) { + DHLOGE("ColorConvertNV12ToNV21 : CheckColorConvertInfo failed."); + return err; + } + err = CopyYPlane(srcImgInfo, dstImgInfo); + if (err != DCAMERA_OK) { + DHLOGE("ColorConvertNV12ToNV21 : CopyYPlane failed."); + return err; + } + + std::shared_ptr tempPlaneYUV = std::make_shared(dstImgInfo.imgSize); + ImageUnitInfo tempImgInfo = dstImgInfo; + tempImgInfo.imgData = tempPlaneYUV->Data(); + SeparateNV12UVPlane(srcImgInfo, tempImgInfo); + CombineNV12UVPlane(tempImgInfo, dstImgInfo); + return DCAMERA_OK; +} + +std::shared_ptr ConvertNV12ToNV21::ProcessData(const std::shared_ptr& srcBuf, + const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig) +{ + if (srcBuf == nullptr) { + DHLOGE("ColorConvertProcessData : srcBuf is null."); + return nullptr; + } + if (!IsConvertible(sourceConfig, targetConfig)) { + DHLOGE("ColorConvertProcessData : Only supported convert videoformat NV12 to NV21."); + DHLOGE("sourceConfig: Videoformat %d Width %d, Height %d, targetConfig: Videoformat %d Width %d, Height %d.", + sourceConfig.GetVideoformat(), sourceConfig.GetWidth(), sourceConfig.GetHeight(), + targetConfig.GetVideoformat(), targetConfig.GetWidth(), targetConfig.GetHeight()); + return nullptr; + } + int64_t timeStamp = 0; + if (!(srcBuf->FindInt64("timeUs", timeStamp))) { + DHLOGE("ColorConvertProcessData : Find srcBuf timeStamp failed."); + return nullptr; + } + + ImageUnitInfo srcImgInfo {Videoformat::YUVI420, 0, 0, 0, 0, 0, 0, nullptr}; + if (GetImageUnitInfo(srcImgInfo, srcBuf) != DCAMERA_OK) { + DHLOGE("ColorConvertProcessData : Get srcImgInfo failed."); + return nullptr; + } + int32_t y2UvRatio = 2; + int32_t bytesPerPixel = 3; + size_t dstBufsize = sourceConfig.GetWidth() * sourceConfig.GetHeight() * bytesPerPixel / y2UvRatio; + std::shared_ptr dstBuf = std::make_shared(dstBufsize); + ImageUnitInfo dstImgInfo = { targetConfig.GetVideoformat(), static_cast(sourceConfig.GetWidth()), + static_cast(sourceConfig.GetHeight()), static_cast(sourceConfig.GetWidth()), + static_cast(sourceConfig.GetHeight()), sourceConfig.GetWidth() * sourceConfig.GetHeight(), + dstBuf->Size(), dstBuf->Data() }; + int32_t err = ColorConvertNV12ToNV21(srcImgInfo, dstImgInfo); + if (err != DCAMERA_OK) { + return nullptr; + } + dstBuf->SetInt64("timeUs", timeStamp); + dstBuf->SetInt32("Videoformat", static_cast(targetConfig.GetVideoformat())); + dstBuf->SetInt32("alignedWidth", static_cast(sourceConfig.GetWidth())); + dstBuf->SetInt32("alignedHeight", static_cast(sourceConfig.GetHeight())); + dstBuf->SetInt32("width", static_cast(sourceConfig.GetWidth())); + dstBuf->SetInt32("height", static_cast(sourceConfig.GetHeight())); + DHLOGD("ColorConvert end, dstBuf Videoformat %d, width %d, height %d, alignedWidth %d, alignedHeight %d, " + + "ImgSize%d, timeUs %lld.", targetConfig.GetVideoformat(), sourceConfig.GetWidth(), sourceConfig.GetHeight(), + sourceConfig.GetWidth(), sourceConfig.GetHeight(), dstBuf->Size(), timeStamp); + return dstBuf; +} +} +} \ No newline at end of file diff --git a/services/data_process/src/pipeline_node/fpscontroller/fps_controller_process.cpp b/services/data_process/src/pipeline_node/fpscontroller/fps_controller_process.cpp new file mode 100644 index 0000000000000000000000000000000000000000..090aa045ab9d63aa57ff2b59bcbbe319f55c971d --- /dev/null +++ b/services/data_process/src/pipeline_node/fpscontroller/fps_controller_process.cpp @@ -0,0 +1,331 @@ +/* + * 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 "fps_controller_process.h" + +#include "dcamera_utils_tools.h" +#include "distributed_camera_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +FpsControllerProcess::~FpsControllerProcess() +{ + if (isFpsControllerProcess_) { + DHLOGD("~DecodeDataProcess : ReleaseProcessNode."); + ReleaseProcessNode(); + } +} + +int32_t FpsControllerProcess::InitNode() +{ + if (targetConfig_.GetFrameRate() > MAX_TARGET_FRAME_RATE) { + DHLOGE("The target framerate : %d is greater than the max framerate : %d.", + targetConfig_.GetFrameRate(), MAX_TARGET_FRAME_RATE); + return DCAMERA_BAD_TYPE; + } + targetFrameRate_ = targetConfig_.GetFrameRate(); + isFpsControllerProcess_ = true; + return DCAMERA_OK; +} + +void FpsControllerProcess::ReleaseProcessNode() +{ + DHLOGD("Start release [%d] node : FPS controller.", nodeRank_); + if (nextDataProcess_ != nullptr) { + nextDataProcess_->ReleaseProcessNode(); + } + + isFpsControllerProcess_ = false; + isFirstFrame_ = false; + targetFrameRate_ = 0; + lastFrameIncomeTimeMs_ = 0; + recentFrameTimeSpanMs_ = -1; + keepCorrectionCount_ = 0; + keepLessThanDoubleCount_ = 0; + keepMoreThanDoubleCount_ = 0; + frameRateCorrectionFactor_ = 0.0; + frameRateOvershootMdf_ = 0; + for (int i = 0; i < INCOME_FRAME_TIME_HISTORY_WINDOWS_SIZE; i++) { + incomingFrameTimesMs_[i] = 0; + } +} + +int32_t FpsControllerProcess::ProcessData(std::vector>& inputBuffers) +{ + if (inputBuffers.empty()) { + DHLOGE("Data buffers is null."); + return DCAMERA_BAD_TYPE; + } + if (!isFpsControllerProcess_) { + DHLOGE("Decoder node occurred error."); + return DCAMERA_DISABLE_PROCESS; + } + int64_t timeStampUs = 0; + if (!inputBuffers[0]->FindInt64("timeUs", timeStampUs)) { + DHLOGE("Find decoder output timestamp fail."); + return DCAMERA_BAD_TYPE; + } + + std::lock_guard lck (mtx); + int64_t nowTimeMs = GetNowTimeStampMs(); + UpdateFPSControllerInfo(nowTimeMs); + + float curFrameRate = CalculateFrameRate(nowTimeMs); + if (IsDropFrame(curFrameRate)) { + DHLOGD("frame control, currect frameRate %u, targetRate %u, drop it", curFrameRate, targetFrameRate_); + return DCAMERA_OK; + } + + DHLOGD("frame control render PushVideoFrame, frame info width %d height %d, timeStampUs %lld, fps %d", + sourceConfig_.GetWidth(), sourceConfig_.GetHeight(), (long long)timeStampUs, curFrameRate); + return FpsControllerDone(inputBuffers); +} + +void FpsControllerProcess::UpdateFPSControllerInfo(int64_t nowMs) +{ + DHLOGD("Frame control, update control info."); + if (targetFrameRate_ <= 0) { + DHLOGD("Frame control, targetFrameRate_ : %d", targetFrameRate_); + return; + } + + isFirstFrame_ = false; + if (lastFrameIncomeTimeMs_ == 0) { + DHLOGD("Frame control, income fisrt frame."); + isFirstFrame_ = true; + } + lastFrameIncomeTimeMs_ = nowMs; + recentFrameTimeSpanMs_ = nowMs - lastFrameIncomeTimeMs_; + DHLOGD("Frame control, lastFrameIncomeTimeMs_ %lld, receive Frame after last frame(ms): %lld", + (long long)lastFrameIncomeTimeMs_, (long long)recentFrameTimeSpanMs_); + UpdateIncomingFrameTimes(nowMs); + UpdateFrameRateCorrectionFactor(nowMs); + return; +} + +void FpsControllerProcess::UpdateFrameRateCorrectionFactor(int64_t nowMs) +{ + DHLOGD("Frame control, update FPS correction factor."); + if (targetFrameRate_ <= 0) { + DHLOGD("Frame control, targetFrameRate_ : %d", targetFrameRate_); + return; + } + if (isFirstFrame_) { + DHLOGD("No frame rate correction factor when the first frame."); + return; + } + + const float minDropFrmValue = 0.5; + const float maxDropFrmValue = 1.0; + const float msPerSecond = 1000; + const float maxInstantaneousFrameRateCoefficient = 1.1; + float maxInstantaneousFrameRateThreshold = targetFrameRate_ * maxInstantaneousFrameRateCoefficient; + float instantaneousFrameRate = msPerSecond / recentFrameTimeSpanMs_; + if (instantaneousFrameRate < 0) { + instantaneousFrameRate = -instantaneousFrameRate; + } + if (instantaneousFrameRate <= maxInstantaneousFrameRateThreshold) { + frameRateCorrectionFactor_ = minDropFrmValue; + } else { + if (keepCorrectionCount_ >= VIDEO_FRAME_DROP_INTERVAL) { + frameRateCorrectionFactor_ = maxDropFrmValue; + keepCorrectionCount_ = 0; + } else { + frameRateCorrectionFactor_ = 0; + keepCorrectionCount_++; + } + DHLOGD("Frame control, instantaneousFrameRate %.3f is more than maxInstantaneousFrameRateThreshold %.3f, " + + "keepCorrectionCount %d", instantaneousFrameRate, maxInstantaneousFrameRateThreshold, + keepCorrectionCount_); + } + + DHLOGD("Frame control, targetFramerate %d, maxInstantaneousFrameRateThreshold %.3f," + + "instantaneousFrameRate %.3f, frameRateCorrectionFactor %.3f", targetFrameRate_, + maxInstantaneousFrameRateThreshold, instantaneousFrameRate, frameRateCorrectionFactor_); + return; +} + +void FpsControllerProcess::UpdateIncomingFrameTimes(int64_t nowMs) +{ + DHLOGD("Frame control, update incoming frame times array."); + if (targetFrameRate_ <= 0) { + DHLOGD("Frame control, targetFrameRate_ : %d", targetFrameRate_); + return; + } + if (isFirstFrame_) { + incomingFrameTimesMs_[0] = nowMs; + return; + } + + int64_t intervalNewAndFirst = nowMs - incomingFrameTimesMs_[0]; + if (intervalNewAndFirst < 0) { + intervalNewAndFirst = -intervalNewAndFirst; + } + if (intervalNewAndFirst > FRMAE_MAX_INTERVAL_TIME_WINDOW_MS) { + DHLOGD("frame control, nowMs: %lld mIncomingFrameT[0]: %lld intervalNewAndFirst: %lld", + (long long)nowMs, (long long)incomingFrameTimesMs_[0], (long long)intervalNewAndFirst); + for (int i = 0; i < INCOME_FRAME_TIME_HISTORY_WINDOWS_SIZE; i++) { + incomingFrameTimesMs_[i] = 0; + } + } else { + DHLOGD("frame control shift, nowMs: %lld mIncomingFrameT[0]: %lld intervalNewAndFirst: %lld", + (long long)nowMs, (long long)incomingFrameTimesMs_[0], (long long)intervalNewAndFirst); + const int32_t windowLeftNum = 2; + for (int i = (INCOME_FRAME_TIME_HISTORY_WINDOWS_SIZE - windowLeftNum); i >= 0; --i) { + incomingFrameTimesMs_[i + 1] = incomingFrameTimesMs_[i]; + } + } + incomingFrameTimesMs_[0] = nowMs; + return; +} + +float FpsControllerProcess::CalculateFrameRate(int64_t nowMs) +{ + DHLOGD("Frame control, calculate frame rate."); + if (targetFrameRate_ <= 0) { + DHLOGE("Frame control, targetFrameRate_ : %d", targetFrameRate_); + return 0.0; + } + + int32_t num = 0; + int32_t validFramesNumber = 0; + if (nowMs < 0) { + nowMs = -nowMs; + } + for (; num < INCOME_FRAME_TIME_HISTORY_WINDOWS_SIZE; num++) { + if (incomingFrameTimesMs_[num] <= 0 || nowMs - incomingFrameTimesMs_[num] > FRAME_HISTORY_TIME_WINDOWS_MS) { + break; + } else { + validFramesNumber++; + } + } + + const float msPerSecond = 1000; + const int32_t minValidCalculatedFrameRatesNum = 2; + int32_t minIncomingFrameNum = static_cast(targetFrameRate_) / MIN_INCOME_FRAME_NUM_COEFFICIENT; + if (validFramesNumber > minIncomingFrameNum && validFramesNumber > minValidCalculatedFrameRatesNum) { + int64_t validTotalTimeDifference = (nowMs - incomingFrameTimesMs_[num - 1]); + if (validTotalTimeDifference < 0) { + validTotalTimeDifference = -validTotalTimeDifference; + } + if (validTotalTimeDifference > 0) { + return validFramesNumber * msPerSecond / validTotalTimeDifference + frameRateCorrectionFactor_; + } + } + return static_cast(validFramesNumber); +} + +bool FpsControllerProcess::IsDropFrame(float incomingFps) +{ + DHLOGD("Frame control, IsDropFrame"); + if (targetFrameRate_ == 0) { + DHLOGD("target fps is 0, drop all frame."); + return true; + } + if (incomingFps <= 0) { + DHLOGD("incoming fps not more than 0, not drop"); + return false; + } + const int32_t incomingFrmRate = static_cast(incomingFps); + if (incomingFrmRate > static_cast(targetFrameRate_)) { + DHLOGD("incoming fps not more than targetFrameRate_, not drop"); + return false; + } + bool isDrop = ReduceFrameRateByUniformStrategy(incomingFrmRate); + DHLOGD("drop frame result: %s", isDrop ? "drop" : "no drop"); + return isDrop; +} + +bool FpsControllerProcess::ReduceFrameRateByUniformStrategy(int32_t incomingFrmRate) +{ + DHLOGD("Frame control, reduce frame rate by uniform rate strategy"); + if (incomingFrmRate > static_cast(targetFrameRate_)) { + DHLOGD("incoming fps not more than targetFrameRate_, not drop"); + return false; + } + + /* + * When the actual incoming frame rate correction value is greater than the target frame + * rate, the incoming frames are reduced uniformly. + */ + bool isDrop = false; + int32_t overshoot = frameRateOvershootMdf_ + (incomingFrmRate - targetFrameRate_); + if (overshoot < 0) { + overshoot = 0; + frameRateOvershootMdf_ = 0; + } + if (overshoot && DOUBLE_MULTIPLE * overshoot < incomingFrmRate) { + /* + * When the actual input frame rate is less than or equal to twice the target frame rate, + * one frame is droped every (incomingFrmRate / overshoot) frames. + */ + if (keepMoreThanDoubleCount_) { + keepMoreThanDoubleCount_ = 0; + return true; + } + const int32_t dropVar = incomingFrmRate / overshoot; + if (keepLessThanDoubleCount_ >= dropVar) { + isDrop = true; + frameRateOvershootMdf_ = -(incomingFrmRate % overshoot) / OVERSHOOT_MODIFY_COEFFICIENT; + keepLessThanDoubleCount_ = 1; + } else { + keepLessThanDoubleCount_++; + } + } else { + /* + * When the actual frame rate is more than twice the target frame rate or the overshoot is + * equal to 0, one frame is reserved every (overshoot / targetFrameRate_) frames. + */ + keepLessThanDoubleCount_ = 0; + const int32_t dropVar = overshoot / targetFrameRate_; + if (keepMoreThanDoubleCount_ < dropVar) { + isDrop = true; + keepMoreThanDoubleCount_++; + } else { + frameRateOvershootMdf_ = overshoot % static_cast(targetFrameRate_); + isDrop = false; + keepMoreThanDoubleCount_ = 0; + } + } + return isDrop; +} + +int32_t FpsControllerProcess::FpsControllerDone(std::vector> outputBuffers) +{ + if (outputBuffers.empty()) { + DHLOGE("The received data buffers is empty."); + return DCAMERA_BAD_VALUE; + } + + if (nextDataProcess_ != nullptr) { + DHLOGD("Send to the next node of the FpsController for processing."); + int32_t err = nextDataProcess_->ProcessData(outputBuffers); + if (err != DCAMERA_OK) { + DHLOGE("Someone node after the FpsController processes fail."); + } + return err; + } + DHLOGD("The current node is the last node, and Output the processed video buffer"); + std::shared_ptr targetPipelineSource = callbackPipelineSource_.lock(); + if (targetPipelineSource == nullptr) { + DHLOGE("callbackPipelineSource_ is nullptr."); + return DCAMERA_BAD_VALUE; + } + targetPipelineSource->OnProcessedVideoBuffer(outputBuffers[0]); + return DCAMERA_OK; +} +} +} \ No newline at end of file diff --git a/services/data_process/src/pipeline_node/multimedia_codec/decode_data_process.cpp b/services/data_process/src/pipeline_node/multimedia_codec/decode_data_process.cpp new file mode 100644 index 0000000000000000000000000000000000000000..488dec5bf9580e5f4bfea1b593b854b0356cc4d8 --- /dev/null +++ b/services/data_process/src/pipeline_node/multimedia_codec/decode_data_process.cpp @@ -0,0 +1,700 @@ +/* + * 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 "decode_data_process.h" + +#include "distributed_hardware_log.h" +#include "graphic_common_c.h" + +#include "convert_nv12_to_nv21.h" +#include "dcamera_utils_tools.h" +#include "decode_video_callback.h" + +namespace OHOS { +namespace DistributedHardware { +DecodeDataProcess::~DecodeDataProcess() +{ + if (isDecoderProcess_) { + DHLOGD("~DecodeDataProcess : ReleaseProcessNode."); + ReleaseProcessNode(); + } +} + +int32_t DecodeDataProcess::InitNode() +{ + DHLOGD("Init DCamera DecodeNode start."); + if (!(IsInDecoderRange(sourceConfig_) && IsInDecoderRange(targetConfig_))) { + DHLOGE("Source config or target config are invalid."); + return DCAMERA_BAD_VALUE; + } + if (!IsConvertible(sourceConfig_, targetConfig_)) { + DHLOGE("The DecodeNode can't convert %d to %d.", sourceConfig_.GetVideoCodecType(), + targetConfig_.GetVideoCodecType()); + return DCAMERA_BAD_TYPE; + } + if (sourceConfig_.GetVideoCodecType() == targetConfig_.GetVideoCodecType()) { + DHLOGD("Disable DecodeNode. The target video codec type %d is the same as the source video codec type %d.", + sourceConfig_.GetVideoCodecType(), targetConfig_.GetVideoCodecType()); + return DCAMERA_OK; + } + + InitCodecEvent(); + int32_t err = InitDecoder(); + if (err != DCAMERA_OK) { + DHLOGE("Init video decoder fail."); + ReleaseProcessNode(); + return err; + } + alignedHeight_ = GetAlignedHeight(); + isDecoderProcess_ = true; + return DCAMERA_OK; +} + +int32_t DecodeDataProcess::GetAlignedHeight() +{ + int32_t alignedBits = 32; + int32_t alignedHeight = static_cast(sourceConfig_.GetHeight()); + if (alignedHeight % alignedBits != 0) { + alignedHeight = ((alignedHeight / alignedBits) + 1) * alignedBits; + } + return alignedHeight; +} + +bool DecodeDataProcess::IsInDecoderRange(const VideoConfigParams& curConfig) +{ + return (curConfig.GetWidth() >= MIN_VIDEO_WIDTH || curConfig.GetWidth() <= MAX_VIDEO_WIDTH || + curConfig.GetHeight() >= MIN_VIDEO_HEIGHT || curConfig.GetHeight() <= MAX_VIDEO_HEIGHT || + curConfig.GetFrameRate() <= MAX_FRAME_RATE); +} + +bool DecodeDataProcess::IsConvertible(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig) +{ + return (sourceConfig.GetVideoCodecType() == targetConfig.GetVideoCodecType() || + targetConfig.GetVideoCodecType() == VideoCodecType::NO_CODEC); +} + +void DecodeDataProcess::InitCodecEvent() +{ + DHLOGD("Init DecodeNode eventBus, and add handler for it."); + eventBusDecode_ = std::make_shared(); + DCameraCodecEvent codecEvent(*this, std::make_shared()); + eventBusRegHandleDecode_ = eventBusDecode_->AddHandler(codecEvent.GetType(), *this); + + DHLOGD("Add handler for DCamera pipeline eventBus."); + eventBusRegHandlePipeline2Decode_ = eventBusPipeline_->AddHandler(codecEvent.GetType(), *this); +} + +int32_t DecodeDataProcess::InitDecoder() +{ + DHLOGD("Init video decoder."); + int32_t err = InitDecoderMetadataFormat(); + if (err != DCAMERA_OK) { + DHLOGE("Init video decoder metadata format fail."); + return err; + } + + videoDecoder_ = Media::VideoDecoderFactory::CreateByName("OMX_hisi_video_decoder_avc"); + if (videoDecoder_ == nullptr) { + DHLOGE("Create video decoder failed."); + return DCAMERA_INIT_ERR; + } + decodeVideoCallback_ = std::make_shared(shared_from_this()); + int32_t retVal = videoDecoder_->SetCallback(decodeVideoCallback_); + if (retVal != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Set video decoder callback failed."); + return DCAMERA_INIT_ERR; + } + retVal = videoDecoder_->Configure(metadataFormat_); + if (retVal != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Set video decoder metadata format failed."); + return DCAMERA_INIT_ERR; + } + retVal = SetDecoderOutputSurface(); + if (retVal != DCAMERA_OK) { + DHLOGE("Set decoder output surface fail."); + return retVal; + } + + retVal = videoDecoder_->Prepare(); + if (retVal != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Video decoder prepare failed."); + return DCAMERA_INIT_ERR; + } + retVal = videoDecoder_->Start(); + if (retVal != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Video decoder start failed."); + return DCAMERA_INIT_ERR; + } + return DCAMERA_OK; +} + +int32_t DecodeDataProcess::InitDecoderMetadataFormat() +{ + DHLOGD("Init video decoder metadata format."); + switch (sourceConfig_.GetVideoCodecType()) { + case VideoCodecType::CODEC_H264: + processType_ = "video/avc"; + metadataFormat_.PutStringValue("codec_mime", processType_); + break; + case VideoCodecType::CODEC_H265: + processType_ = "video/hevc"; + metadataFormat_.PutStringValue("codec_mime", processType_); + break; + default: + DHLOGE("The current codec type does not support decoding."); + return DCAMERA_NOT_FOUND; + } + metadataFormat_.PutIntValue("pixel_format", Media::VideoPixelFormat::NV12); + metadataFormat_.PutIntValue("max_input_size", MAX_YUV420_BUFFER_SIZE); + metadataFormat_.PutIntValue("width", (int32_t)sourceConfig_.GetWidth()); + metadataFormat_.PutIntValue("height", (int32_t)sourceConfig_.GetHeight()); + metadataFormat_.PutIntValue("frame_rate", MAX_FRAME_RATE); + return DCAMERA_OK; +} + +int32_t DecodeDataProcess::SetDecoderOutputSurface() +{ + DHLOGD("Set the video decoder output surface."); + if (videoDecoder_ == nullptr) { + DHLOGE("The video decoder is null."); + return DCAMERA_BAD_VALUE; + } + + decodeConsumerSurface_ = Surface::CreateSurfaceAsConsumer(); + if (decodeConsumerSurface_ == nullptr) { + DHLOGE("Creat the decode consumer surface fail."); + return DCAMERA_INIT_ERR; + } + decodeConsumerSurface_->SetDefaultWidthAndHeight((int32_t)sourceConfig_.GetWidth(), + (int32_t)sourceConfig_.GetHeight()); + sptr decodeSurfaceListener_ = new DecodeSurfaceListener(decodeConsumerSurface_, + shared_from_this()); + if (decodeConsumerSurface_->RegisterConsumerListener(decodeSurfaceListener_) != + SURFACE_ERROR_OK) { + DHLOGE("Register consumer listener fail."); + return DCAMERA_INIT_ERR; + } + + sptr surfaceProducer = decodeConsumerSurface_->GetProducer(); + if (surfaceProducer == nullptr) { + DHLOGE("Get the surface producer of the decode consumer surface fail."); + return DCAMERA_INIT_ERR; + } + decodeProducerSurface_ = Surface::CreateSurfaceAsProducer(surfaceProducer); + if (decodeProducerSurface_ == nullptr) { + DHLOGE("Creat the decode producer surface of the decode consumer surface fail."); + return DCAMERA_INIT_ERR; + } + + DHLOGD("Set the producer surface to video decoder output surface."); + int32_t err = videoDecoder_->SetOutputSurface(decodeProducerSurface_); + if (err != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Set decoder output surface fail."); + return DCAMERA_INIT_ERR; + } + return DCAMERA_OK; +} + +void DecodeDataProcess::ReleaseProcessNode() +{ + DHLOGD("Start release [%d] node : DecodeNode.", nodeRank_); + isDecoderProcess_ = false; + if (nextDataProcess_ != nullptr) { + nextDataProcess_->ReleaseProcessNode(); + } + if (eventBusDecode_ != nullptr && eventBusPipeline_ != nullptr) { + DHLOGD("Start release DecodeNode eventBusDecode_ and eventBusPipeline_."); + DCameraCodecEvent codecEvent(*this, std::make_shared()); + eventBusDecode_->RemoveHandler(codecEvent.GetType(), eventBusRegHandleDecode_); + eventBusDecode_ = nullptr; + eventBusPipeline_->RemoveHandler(codecEvent.GetType(), eventBusRegHandlePipeline2Decode_); + eventBusPipeline_ = nullptr; + } + + { + std::lock_guard lck(mtxDecoderState_); + if (videoDecoder_ != nullptr) { + DHLOGD("Start release videoDecoder."); + videoDecoder_->Flush(); + videoDecoder_->Stop(); + videoDecoder_->Release(); + decodeConsumerSurface_ = nullptr; + decodeProducerSurface_ = nullptr; + videoDecoder_ = nullptr; + decodeVideoCallback_ = nullptr; + } + } + + processType_ = ""; + std::queue> emptyBuffersQueue; + inputBuffersQueue_.swap(emptyBuffersQueue); + std::queue emptyIndexsQueue; + availableInputIndexsQueue_.swap(emptyIndexsQueue); + waitDecoderOutputCount_ = 0; + lastFeedDecoderInputBufferTimeUs_ = 0; + outputTimeStampUs_ = 0; + alignedHeight_ = 0; + DHLOGD("Release [%d] node : DecodeNode end.", nodeRank_); +} + +int32_t DecodeDataProcess::ProcessData(std::vector>& inputBuffers) +{ + DHLOGD("Process data in DecodeDataProcess."); + if (inputBuffers.empty()) { + DHLOGE("The input data buffers is empty."); + return DCAMERA_BAD_VALUE; + } + if (sourceConfig_.GetVideoCodecType() == targetConfig_.GetVideoCodecType()) { + DHLOGD("The target VideoCodecType : %d is the same as the source VideoCodecType : %d.", + sourceConfig_.GetVideoCodecType(), targetConfig_.GetVideoCodecType()); + return DecodeDone(inputBuffers); + } + + if (videoDecoder_ == nullptr) { + DHLOGE("The video decoder does not exist before decoding data."); + return DCAMERA_INIT_ERR; + } + if (inputBuffersQueue_.size() > VIDEO_DECODER_QUEUE_MAX) { + DHLOGE("video decoder input buffers queue over flow."); + return DCAMERA_INDEX_OVERFLOW; + } + if (inputBuffers[0]->Size() > MAX_YUV420_BUFFER_SIZE) { + DHLOGE("DecodeNode input buffer size %d error.", inputBuffers[0]->Size()); + return DCAMERA_MEMORY_OPT_ERROR; + } + if (!isDecoderProcess_) { + DHLOGE("Decoder node occurred error or start release."); + return DCAMERA_DISABLE_PROCESS; + } + inputBuffersQueue_.push(inputBuffers[0]); + DHLOGD("Push inputBuffer sucess. BufSize %d, QueueSize %d.", inputBuffers[0]->Size(), inputBuffersQueue_.size()); + int32_t err = FeedDecoderInputBuffer(); + if (err != DCAMERA_OK) { + int32_t sleepTimeUs = 5000; + std::this_thread::sleep_for(std::chrono::microseconds(sleepTimeUs)); + DHLOGD("Feed decoder input buffer fail. Try FeedDecoderInputBuffer again."); + std::shared_ptr reFeedInputPacket = std::make_shared(); + reFeedInputPacket->SetVideoCodecType(sourceConfig_.GetVideoCodecType()); + DCameraCodecEvent dCamCodecEv(*this, reFeedInputPacket, VideoCodecAction::ACTION_ONCE_AGAIN); + if (eventBusPipeline_ == nullptr) { + DHLOGE("eventBusPipeline_ is nullptr."); + return DCAMERA_BAD_VALUE; + } + eventBusPipeline_->PostEvent(dCamCodecEv, POSTMODE::POST_ASYNC); + } + return DCAMERA_OK; +} + +int32_t DecodeDataProcess::FeedDecoderInputBuffer() +{ + DHLOGD("Feed decoder input buffer."); + while ((!inputBuffersQueue_.empty()) && (isDecoderProcess_)) { + std::shared_ptr buffer = inputBuffersQueue_.front(); + if (buffer == nullptr || availableInputIndexsQueue_.empty()) { + DHLOGE("inputBuffersQueue size %d, availableInputIndexsQueue size %d.", + inputBuffersQueue_.size(), availableInputIndexsQueue_.size()); + return DCAMERA_BAD_VALUE; + } + + { + std::lock_guard lck(mtxDecoderState_); + if (videoDecoder_ == nullptr) { + DHLOGE("The video decoder does not exist before GetInputBuffer."); + return DCAMERA_OK; + } + uint32_t index = availableInputIndexsQueue_.front(); + std::shared_ptr sharedMemoryInput = videoDecoder_->GetInputBuffer(index); + if (sharedMemoryInput == nullptr) { + DHLOGE("Failed to obtain the input shared memory corresponding to the [%d] index.", index); + return DCAMERA_BAD_VALUE; + } + size_t inputMemoDataSize = static_cast(sharedMemoryInput->GetSize()); + errno_t err = memcpy_s(sharedMemoryInput->GetBase(), inputMemoDataSize, buffer->Data(), buffer->Size()); + if (err != EOK) { + DHLOGE("memcpy_s buffer failed."); + return DCAMERA_MEMORY_OPT_ERROR; + } + int64_t timeUs = GetDecoderTimeStamp(); + DHLOGD("Decoder input buffer size %d, timeStamp %lld.", buffer->Size(), (long long)timeUs); + Media::AVCodecBufferInfo bufferInfo {timeUs, static_cast(buffer->Size()), 0}; + int32_t ret = videoDecoder_->QueueInputBuffer(index, bufferInfo, + Media::AVCODEC_BUFFER_FLAG_NONE); + if (ret != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("queue Input buffer failed."); + return DCAMERA_BAD_OPERATE; + } + } + + inputBuffersQueue_.pop(); + DHLOGD("Push inputBuffer sucess. inputBuffersQueue size is %d.", inputBuffersQueue_.size()); + + { + std::lock_guard lck(mtxHoldCount_); + availableInputIndexsQueue_.pop(); + waitDecoderOutputCount_++; + DHLOGD("Wait decoder output frames number is %d.", waitDecoderOutputCount_); + } + } + return DCAMERA_OK; +} + +int64_t DecodeDataProcess::GetDecoderTimeStamp() +{ + int64_t TimeDifferenceStampUs = 0; + int64_t nowTimeUs = GetNowTimeStampUs(); + if (lastFeedDecoderInputBufferTimeUs_ == 0) { + lastFeedDecoderInputBufferTimeUs_ = nowTimeUs; + return TimeDifferenceStampUs; + } + TimeDifferenceStampUs = nowTimeUs - lastFeedDecoderInputBufferTimeUs_; + lastFeedDecoderInputBufferTimeUs_ = nowTimeUs; + return TimeDifferenceStampUs; +} + +void DecodeDataProcess::GetDecoderOutputBuffer(const sptr& surface) +{ + DHLOGD("Get decoder output buffer."); + if (surface == nullptr) { + DHLOGE("Get decode consumer surface failed."); + return; + } + Rect damage = {0, 0, 0, 0}; + int32_t acquireFence = 0; + int64_t timeStampUs = 0; + sptr surfaceBuffer = nullptr; + GSError ret = surface->AcquireBuffer(surfaceBuffer, acquireFence, timeStampUs, damage); + if (ret != GSERROR_OK || surfaceBuffer == nullptr) { + DHLOGE("Acquire surface buffer failed!"); + return; + } + int32_t alignedWidth = surfaceBuffer->GetStride(); + int32_t alignedHeight = alignedHeight_; + DHLOGD("OutputBuffer alignedWidth %d, alignedHeight %d, TimeUs %lld.", alignedWidth, alignedHeight, timeStampUs); + CopyDecodedImage(surfaceBuffer, timeStampUs, alignedWidth, alignedHeight); + surface->ReleaseBuffer(surfaceBuffer, -1); + outputTimeStampUs_ = timeStampUs; + { + std::lock_guard lck(mtxHoldCount_); + if (waitDecoderOutputCount_ <= 0) { + DHLOGE("The waitDecoderOutputCount_ = %d.", waitDecoderOutputCount_); + } + if (outputTimeStampUs_ == 0) { + waitDecoderOutputCount_ -= FIRST_FRAME_INPUT_NUM; + } else { + waitDecoderOutputCount_--; + } + DHLOGD("Wait decoder output frames number is %d.", waitDecoderOutputCount_); + } +} + +void DecodeDataProcess::CopyDecodedImage(const sptr& surBuf, int64_t timeStampUs, int32_t alignedWidth, + int32_t alignedHeight) +{ + if (surBuf == nullptr) { + DHLOGE("surface buffer is null!"); + return; + } + int32_t y2UvRatio = 2; + int32_t bytesPerPixel = 3; + size_t validDecodedImageAlignedSize = static_cast(alignedWidth * alignedHeight * + bytesPerPixel / y2UvRatio); + size_t validDecodedImageSize = static_cast(sourceConfig_.GetWidth() * sourceConfig_.GetHeight() * + bytesPerPixel / y2UvRatio); + size_t surfaceBufSize = static_cast(surBuf->GetSize()); + if (validDecodedImageAlignedSize > surfaceBufSize || validDecodedImageAlignedSize < validDecodedImageSize) { + DHLOGE("Buffer size error, validDecodedImageSize %d, validDecodedImageAlignedSize %d, surBufSize %d.", + validDecodedImageSize, validDecodedImageAlignedSize, surBuf->GetSize()); + return; + } + std::shared_ptr bufferOutput = std::make_shared(validDecodedImageSize); + uint8_t *addr = static_cast(surBuf->GetVirAddr()); + if (alignedWidth == static_cast(sourceConfig_.GetWidth()) && + alignedHeight == static_cast(sourceConfig_.GetHeight())) { + errno_t err = memcpy_s(bufferOutput->Data(), bufferOutput->Size(), addr, validDecodedImageSize); + if (err != EOK) { + DHLOGE("memcpy_s surface buffer failed."); + return; + } + } else { + ImageUnitInfo srcImgInfo = { sourceConfig_.GetVideoformat(), static_cast(sourceConfig_.GetWidth()), + static_cast(sourceConfig_.GetHeight()), alignedWidth, alignedHeight, + static_cast(alignedWidth * alignedHeight), surfaceBufSize, addr }; + ImageUnitInfo dstImgInfo = { sourceConfig_.GetVideoformat(), static_cast(sourceConfig_.GetWidth()), + static_cast(sourceConfig_.GetHeight()), static_cast(sourceConfig_.GetWidth()), + static_cast(sourceConfig_.GetHeight()), sourceConfig_.GetWidth() * sourceConfig_.GetHeight(), + bufferOutput->Size(), bufferOutput->Data() }; + int32_t retRow = CopyYUVPlaneByRow(srcImgInfo, dstImgInfo); + if (retRow != DCAMERA_OK) { + DHLOGE("memcpy_s surface buffer failed."); + return; + } + } + bufferOutput->SetInt64("timeUs", timeStampUs); + bufferOutput->SetInt32("Videoformat", static_cast(sourceConfig_.GetVideoformat())); + bufferOutput->SetInt32("alignedWidth", static_cast(sourceConfig_.GetWidth())); + bufferOutput->SetInt32("alignedHeight", static_cast(sourceConfig_.GetHeight())); + bufferOutput->SetInt32("width", static_cast(sourceConfig_.GetWidth())); + bufferOutput->SetInt32("height", static_cast(sourceConfig_.GetHeight())); + PostOutputDataBuffers(bufferOutput); +} + +int32_t DecodeDataProcess::CopyYUVPlaneByRow(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo) +{ + int32_t ret = CheckCopyImageInfo(srcImgInfo, dstImgInfo); + if (ret != DCAMERA_OK) { + DHLOGE("Check CopyImageUnitInfo failed."); + return ret; + } + errno_t err = EOK; + int32_t srcDataOffset = 0; + int32_t dstDataOffset = 0; + for (int32_t yh = 0; yh < dstImgInfo.height; yh++) { + err = memcpy_s(dstImgInfo.imgData + dstDataOffset, dstImgInfo.chromaOffset - dstDataOffset, + srcImgInfo.imgData + srcDataOffset, dstImgInfo.width); + if (err != EOK) { + DHLOGE("memcpy_s YPlane in line[%d] failed.", yh); + return DCAMERA_MEMORY_OPT_ERROR; + } + dstDataOffset += dstImgInfo.alignedWidth; + srcDataOffset += srcImgInfo.alignedWidth; + } + DHLOGD("Copy Yplane end, dstDataOffset %d, srcDataOffset %d, validYPlaneSize %d.", + dstDataOffset, srcDataOffset, dstImgInfo.chromaOffset); + + int32_t y2UvRatio = 2; + dstDataOffset = dstImgInfo.chromaOffset; + srcDataOffset = srcImgInfo.chromaOffset; + for (int32_t uvh = 0; uvh < dstImgInfo.height / y2UvRatio; uvh++) { + err = memcpy_s(dstImgInfo.imgData + dstDataOffset, dstImgInfo.imgSize - dstDataOffset, + srcImgInfo.imgData + srcDataOffset, dstImgInfo.width); + if (err != EOK) { + DHLOGE("memcpy_s UVPlane in line[%d] failed.", uvh); + return DCAMERA_MEMORY_OPT_ERROR; + } + dstDataOffset += dstImgInfo.alignedWidth; + srcDataOffset += srcImgInfo.alignedWidth; + } + DHLOGD("Copy UVplane end, dstDataOffset %d, srcDataOffset %d.", dstDataOffset, srcDataOffset); + return DCAMERA_OK; +} + +int32_t DecodeDataProcess::CheckCopyImageInfo(const ImageUnitInfo& srcImgInfo, const ImageUnitInfo& dstImgInfo) +{ + if (srcImgInfo.imgData == nullptr || dstImgInfo.imgData == nullptr) { + DHLOGE("The imgData of srcImgInfo or the imgData of dstImgInfo are null!"); + return DCAMERA_BAD_VALUE; + } + if (srcImgInfo.colorFormat != dstImgInfo.colorFormat) { + DHLOGE("CopyInfo error : srcImgInfo colorFormat %d, dstImgInfo colorFormat %d.", + srcImgInfo.colorFormat, dstImgInfo.colorFormat); + return DCAMERA_BAD_VALUE; + } + + if (!IsCorrectImageUnitInfo(srcImgInfo)) { + DHLOGE("srcImginfo fail: width %d, height %d, alignedWidth %d, alignedHeight %d, chromaOffset %lld, " + + "imgSize %lld.", srcImgInfo.width, srcImgInfo.height, srcImgInfo.alignedWidth, srcImgInfo.alignedHeight, + srcImgInfo.chromaOffset, srcImgInfo.imgSize); + return DCAMERA_BAD_VALUE; + } + if (!IsCorrectImageUnitInfo(dstImgInfo)) { + DHLOGE("dstImginfo fail: width %d, height %d, alignedWidth %d, alignedHeight %d, chromaOffset %lld, " + + "imgSize %lld.", dstImgInfo.width, dstImgInfo.height, dstImgInfo.alignedWidth, dstImgInfo.alignedHeight, + dstImgInfo.chromaOffset, dstImgInfo.imgSize); + return DCAMERA_BAD_VALUE; + } + + if (dstImgInfo.width > srcImgInfo.alignedWidth || dstImgInfo.height > srcImgInfo.alignedHeight) { + DHLOGE("Comparison ImgInfo fail: dstwidth %d, dstheight %d, srcAlignedWidth %d, srcAlignedHeight %d.", + dstImgInfo.width, dstImgInfo.height, srcImgInfo.alignedWidth, srcImgInfo.alignedHeight); + return DCAMERA_BAD_VALUE; + } + return DCAMERA_OK; +} + +bool DecodeDataProcess::IsCorrectImageUnitInfo(const ImageUnitInfo& imgInfo) +{ + int32_t y2UvRatio = 2; + int32_t bytesPerPixel = 3; + size_t expectedImgSize = static_cast(imgInfo.alignedWidth * imgInfo.alignedHeight * + bytesPerPixel / y2UvRatio); + size_t expectedChromaOffset = static_cast(imgInfo.alignedWidth * imgInfo.alignedHeight); + return (imgInfo.width <= imgInfo.alignedWidth && imgInfo.height <= imgInfo.alignedHeight && + imgInfo.imgSize >= expectedImgSize && imgInfo.chromaOffset == expectedChromaOffset); +} + +void DecodeDataProcess::PostOutputDataBuffers(std::shared_ptr& outputBuffer) +{ + if (eventBusDecode_ == nullptr || outputBuffer == nullptr) { + DHLOGE("eventBusDecode_ or outputBuffer is null."); + return; + } + std::vector> multiDataBuffers; + multiDataBuffers.push_back(outputBuffer); + std::shared_ptr transNextNodePacket = std::make_shared(VideoCodecType::NO_CODEC, + multiDataBuffers); + DCameraCodecEvent dCamCodecEv(*this, transNextNodePacket, VideoCodecAction::NO_ACTION); + eventBusDecode_->PostEvent(dCamCodecEv, POSTMODE::POST_ASYNC); + DHLOGD("Send video decoder output asynchronous DCameraCodecEvents success."); +} + +int32_t DecodeDataProcess::DecodeDone(std::vector> outputBuffers) +{ + DHLOGD("Decoder Done."); + if (outputBuffers.empty()) { + DHLOGE("The received data buffers is empty."); + return DCAMERA_BAD_VALUE; + } + + if (nextDataProcess_ != nullptr) { + DHLOGD("Send to the next node of the decoder for processing."); + int32_t err = nextDataProcess_->ProcessData(outputBuffers); + if (err != DCAMERA_OK) { + DHLOGE("Someone node after the decoder processes fail."); + } + return err; + } + DHLOGD("The current node is the last node, and Output the processed video buffer"); + std::shared_ptr targetPipelineSource = callbackPipelineSource_.lock(); + if (targetPipelineSource == nullptr) { + DHLOGE("callbackPipelineSource_ is nullptr."); + return DCAMERA_BAD_VALUE; + } + targetPipelineSource->OnProcessedVideoBuffer(outputBuffers[0]); + return DCAMERA_OK; +} + +void DecodeDataProcess::OnEvent(DCameraCodecEvent& ev) +{ + DHLOGD("Receiving asynchronous DCameraCodecEvents."); + std::shared_ptr receivedCodecPacket = ev.GetCodecPacket(); + VideoCodecAction action = ev.GetAction(); + switch (action) { + case VideoCodecAction::NO_ACTION: { + if (receivedCodecPacket == nullptr) { + DHLOGE("the received codecPacket of action [%d] is null.", action); + OnError(); + return; + } + + std::shared_ptr colorConverter = std::make_shared(); + VideoConfigParams decodedConfig(VideoCodecType::NO_CODEC, Videoformat::NV12, sourceConfig_.GetFrameRate(), + sourceConfig_.GetWidth(), sourceConfig_.GetHeight()); + std::vector> nv21DataBuffers; + std::shared_ptr nv21Image = colorConverter->ProcessData( + receivedCodecPacket->GetDataBuffers()[0], decodedConfig, targetConfig_); + nv21DataBuffers.push_back(nv21Image); + + DecodeDone(nv21DataBuffers); + break; + } + case VideoCodecAction::ACTION_ONCE_AGAIN: + DHLOGD("Try FeedDecoderInputBuffer again."); + FeedDecoderInputBuffer(); + return; + default: + DHLOGD("The action : %d is not supported.", action); + return; + } +} + +void DecodeDataProcess::OnError() +{ + DHLOGD("DecodeDataProcess : OnError."); + isDecoderProcess_ = false; + videoDecoder_->Stop(); + std::shared_ptr targetPipelineSource = callbackPipelineSource_.lock(); + if (targetPipelineSource == nullptr) { + DHLOGE("callbackPipelineSource_ is nullptr."); + return; + } + targetPipelineSource->OnError(DataProcessErrorType::ERROR_PIPELINE_DECODER); +} + +void DecodeDataProcess::OnInputBufferAvailable(uint32_t index) +{ + DHLOGD("DecodeDataProcess::OnInputBufferAvailable"); + std::lock_guard lck(mtxHoldCount_); + if (availableInputIndexsQueue_.size() > VIDEO_DECODER_QUEUE_MAX) { + DHLOGE("Video decoder available indexs queue overflow."); + return; + } + DHLOGD("Video decoder available indexs queue push index [%d].", index); + availableInputIndexsQueue_.push(index); +} + +void DecodeDataProcess::OnOutputFormatChanged(const Media::Format &format) +{ + if (decodeOutputFormat_.GetFormatMap().empty()) { + DHLOGE("The first changed video decoder output format is null."); + return; + } + decodeOutputFormat_ = format; +} + +void DecodeDataProcess::OnOutputBufferAvailable(uint32_t index, const Media::AVCodecBufferInfo& info, + const Media::AVCodecBufferFlag& flag) +{ + if (!isDecoderProcess_) { + DHLOGE("Decoder node occurred error or start release."); + return; + } + DHLOGD("Video decode buffer info: presentation TimeUs %lld, size %d, offset %d, flag %d", + info.presentationTimeUs, info.size, info.offset, flag); + outputInfo_ = info; + { + std::lock_guard lck(mtxDecoderState_); + if (videoDecoder_ == nullptr) { + DHLOGE("The video decoder does not exist before decoding data."); + return; + } + int32_t errRelease = videoDecoder_->ReleaseOutputBuffer(index, true); + if (errRelease != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("The video decoder output decoded data to surface fail, index : [%d].", index); + } + } +} + +VideoConfigParams DecodeDataProcess::GetSourceConfig() const +{ + return sourceConfig_; +} + +VideoConfigParams DecodeDataProcess::GetTargetConfig() const +{ + return targetConfig_; +} + +void DecodeSurfaceListener::OnBufferAvailable() +{ + DHLOGD("DecodeSurfaceListener : OnBufferAvailable."); + std::shared_ptr targetDecoderNode = decodeVideoNode_.lock(); + if (targetDecoderNode == nullptr) { + DHLOGE("decodeVideoNode_ is nullptr."); + return; + } + targetDecoderNode->GetDecoderOutputBuffer(surface_); +} + +void DecodeSurfaceListener::SetSurface(const sptr& surface) +{ + surface_ = surface; +} + +void DecodeSurfaceListener::SetDecodeVideoNode(const std::weak_ptr& decodeVideoNode) +{ + decodeVideoNode_ = decodeVideoNode; +} +} +} \ No newline at end of file diff --git a/services/data_process/src/pipeline_node/multimedia_codec/decode_video_callback.cpp b/services/data_process/src/pipeline_node/multimedia_codec/decode_video_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..401f367244d5d108f4479df7853751cb734b9729 --- /dev/null +++ b/services/data_process/src/pipeline_node/multimedia_codec/decode_video_callback.cpp @@ -0,0 +1,67 @@ +/* + * 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 + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +void DecodeVideoCallback::OnError(Media::AVCodecErrorType errorType, int32_t errorCode) +{ + DHLOGE("DecodeVideoCallback : OnError. Error type: %d . Error code: %d ", errorType, errorCode); + std::shared_ptr targetDecoderNode = decodeVideoNode_.lock(); + if (targetDecoderNode == nullptr) { + DHLOGE("decodeVideoNode_ is nullptr."); + return; + } + targetDecoderNode->OnError(); +} + +void DecodeVideoCallback::OnInputBufferAvailable(uint32_t index) +{ + DHLOGD("DecodeVideoCallback : OnInputBufferAvailable."); + std::shared_ptr targetDecoderNode = decodeVideoNode_.lock(); + if (targetDecoderNode == nullptr) { + DHLOGE("decodeVideoNode_ is nullptr."); + return; + } + targetDecoderNode->OnInputBufferAvailable(index); +} + +void DecodeVideoCallback::OnOutputFormatChanged(const Media::Format &format) +{ + DHLOGD("DecodeVideoCallback : OnOutputFormatChanged."); + std::shared_ptr targetDecoderNode = decodeVideoNode_.lock(); + if (targetDecoderNode == nullptr) { + DHLOGE("decodeVideoNode_ is nullptr."); + return; + } + targetDecoderNode->OnOutputFormatChanged(format); +} + +void DecodeVideoCallback::OnOutputBufferAvailable(uint32_t index, Media::AVCodecBufferInfo info, + Media::AVCodecBufferFlag flag) +{ + DHLOGD("DecodeVideoCallback : OnOutputBufferAvailable. Only relaese buffer when using surface output."); + std::shared_ptr targetDecoderNode = decodeVideoNode_.lock(); + if (targetDecoderNode == nullptr) { + DHLOGE("decodeVideoNode_ is nullptr."); + return; + } + targetDecoderNode->OnOutputBufferAvailable(index, info, flag); +} +} +} \ No newline at end of file diff --git a/services/data_process/src/pipeline_node/multimedia_codec/encode_data_process.cpp b/services/data_process/src/pipeline_node/multimedia_codec/encode_data_process.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5d9c92a79ac1eedac7bef09c6627cfaf7da27a1 --- /dev/null +++ b/services/data_process/src/pipeline_node/multimedia_codec/encode_data_process.cpp @@ -0,0 +1,498 @@ +/* + * 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 "encode_data_process.h" + +#include + +#include "display_type.h" +#include "distributed_hardware_log.h" +#include "graphic_common_c.h" + +#include "dcamera_utils_tools.h" +#include "encode_video_callback.h" + +#ifndef DH_LOG_TAG +#define DH_LOG_TAG "DCDP_NODE_ENCODEC" +#endif + +namespace OHOS { +namespace DistributedHardware { +const std::map EncodeDataProcess::ENCODER_BITRATE_TABLE = { + std::map::value_type(WIDTH_320_HEIGHT_240, BITRATE_500000), + std::map::value_type(WIDTH_480_HEIGHT_360, BITRATE_1110000), + std::map::value_type(WIDTH_640_HEIGHT_360, BITRATE_1500000), + std::map::value_type(WIDTH_640_HEIGHT_480, BITRATE_1800000), + std::map::value_type(WIDTH_720_HEIGHT_540, BITRATE_2100000), + std::map::value_type(WIDTH_960_HEIGHT_540, BITRATE_2300000), + std::map::value_type(WIDTH_960_HEIGHT_720, BITRATE_2800000), + std::map::value_type(WIDTH_1280_HEIGHT_720, BITRATE_3400000), + std::map::value_type(WIDTH_1440_HEIGHT_1080, BITRATE_5000000), + std::map::value_type(WIDTH_1920_HEIGHT_1080, BITRATE_6000000), +}; + +EncodeDataProcess::~EncodeDataProcess() +{ + if (isEncoderProcess_) { + DHLOGD("~EncodeDataProcess : ReleaseProcessNode."); + ReleaseProcessNode(); + } +} + +int32_t EncodeDataProcess::InitNode() +{ + DHLOGD("Init DCamera EncodeNode start."); + if (!(IsInEncoderRange(sourceConfig_) && IsInEncoderRange(targetConfig_))) { + DHLOGE("Source config or target config are invalid."); + return DCAMERA_BAD_VALUE; + } + if (!IsConvertible(sourceConfig_, targetConfig_)) { + DHLOGE("The EncodeNode cannot convert source VideoCodecType %d to target VideoCodecType %d.", + sourceConfig_.GetVideoCodecType(), targetConfig_.GetVideoCodecType()); + return DCAMERA_BAD_TYPE; + } + if (sourceConfig_.GetVideoCodecType() == targetConfig_.GetVideoCodecType()) { + DHLOGD("Disable EncodeNode. The target VideoCodecType %d is the same as the source VideoCodecType %d.", + sourceConfig_.GetVideoCodecType(), targetConfig_.GetVideoCodecType()); + return DCAMERA_OK; + } + + int32_t err = InitEncoder(); + if (err != DCAMERA_OK) { + DHLOGE("Init video encoder fail."); + ReleaseProcessNode(); + return err; + } + isEncoderProcess_ = true; + return DCAMERA_OK; +} + +bool EncodeDataProcess::IsInEncoderRange(const VideoConfigParams& curConfig) +{ + return (curConfig.GetWidth() >= MIN_VIDEO_WIDTH || curConfig.GetWidth() <= MAX_VIDEO_WIDTH || + curConfig.GetHeight() >= MIN_VIDEO_HEIGHT || curConfig.GetHeight() <= MAX_VIDEO_HEIGHT || + curConfig.GetFrameRate() <= MAX_FRAME_RATE); +} + +bool EncodeDataProcess::IsConvertible(const VideoConfigParams& sourceConfig, const VideoConfigParams& targetConfig) +{ + return (sourceConfig.GetVideoCodecType() == targetConfig.GetVideoCodecType() || + sourceConfig.GetVideoCodecType() == VideoCodecType::NO_CODEC); +} + +int32_t EncodeDataProcess::InitEncoder() +{ + DHLOGD("Init video encoder."); + int32_t err = InitEncoderMetadataFormat(); + if (err != DCAMERA_OK) { + DHLOGE("Init video encoder metadata format fail."); + return err; + } + err = InitEncoderBitrateFormat(); + if (err != DCAMERA_OK) { + DHLOGE("Init video encoder bitrate format fail."); + return err; + } + + videoEncoder_ = Media::VideoEncoderFactory::CreateByMime(processType_); + if (videoEncoder_ == nullptr) { + DHLOGE("Create video encoder failed."); + return DCAMERA_INIT_ERR; + } + encodeVideoCallback_ = std::make_shared(shared_from_this()); + int32_t retVal = videoEncoder_->SetCallback(encodeVideoCallback_); + if (retVal != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Set video encoder callback failed."); + return DCAMERA_INIT_ERR; + } + retVal = videoEncoder_->Configure(metadataFormat_); + if (retVal != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Set video encoder metadata format failed."); + return DCAMERA_INIT_ERR; + } + encodeProducerSurface_ = videoEncoder_->CreateInputSurface(); + if (encodeProducerSurface_ == nullptr) { + DHLOGE("Get video encoder producer surface failed."); + return DCAMERA_INIT_ERR; + } + retVal = videoEncoder_->Prepare(); + if (retVal != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Video encoder prepare failed."); + return DCAMERA_INIT_ERR; + } + retVal = videoEncoder_->Start(); + if (retVal != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("Video encoder start failed."); + return DCAMERA_INIT_ERR; + } + return DCAMERA_OK; +} + +int32_t EncodeDataProcess::InitEncoderMetadataFormat() +{ + DHLOGD("Init video encoder metadata format."); + switch (targetConfig_.GetVideoCodecType()) { + case VideoCodecType::CODEC_H264: + processType_ = "video/avc"; + metadataFormat_.PutStringValue("codec_mime", processType_); + metadataFormat_.PutIntValue("codec_profile", Media::AVCProfile::AVC_PROFILE_BASELINE); + break; + case VideoCodecType::CODEC_H265: + processType_ = "video/hevc"; + metadataFormat_.PutStringValue("codec_mime", processType_); + metadataFormat_.PutIntValue("codec_profile", Media::HEVCProfile::HEVC_PROFILE_MAIN); + break; + default: + DHLOGE("The current codec type does not support encoding."); + return DCAMERA_NOT_FOUND; + } + switch (sourceConfig_.GetVideoformat()) { + case Videoformat::YUVI420: + metadataFormat_.PutIntValue("pixel_format", Media::VideoPixelFormat::YUVI420); + break; + case Videoformat::NV12: + metadataFormat_.PutIntValue("pixel_format", Media::VideoPixelFormat::NV12); + break; + case Videoformat::NV21: + metadataFormat_.PutIntValue("pixel_format", Media::VideoPixelFormat::NV21); + break; + default: + DHLOGE("The current pixel format does not support encoding."); + return DCAMERA_NOT_FOUND; + } + + metadataFormat_.PutLongValue("max_input_size", NORM_YUV420_BUFFER_SIZE); + metadataFormat_.PutIntValue("width", (int32_t)sourceConfig_.GetWidth()); + metadataFormat_.PutIntValue("height", (int32_t)sourceConfig_.GetHeight()); + metadataFormat_.PutIntValue("frame_rate", MAX_FRAME_RATE); + return DCAMERA_OK; +} + +int32_t EncodeDataProcess::InitEncoderBitrateFormat() +{ + DHLOGD("Init video encoder bitrate format."); + if (!(IsInEncoderRange(sourceConfig_) && IsInEncoderRange(targetConfig_))) { + DHLOGE("Source config or target config are invalid."); + return DCAMERA_BAD_VALUE; + } + metadataFormat_.PutIntValue("i_frame_interval", IDR_FRAME_INTERVAL_MS); + metadataFormat_.PutIntValue("video_encode_bitrate_mode", Media::VideoEncodeBitrateMode::VBR); + + if (ENCODER_BITRATE_TABLE.empty()) { + DHLOGD("ENCODER_BITRATE_TABLE is null, use the default bitrate of the encoder."); + return DCAMERA_OK; + } + int64_t pixelformat = static_cast(sourceConfig_.GetWidth() * sourceConfig_.GetHeight()); + int32_t matchedBitrate = BITRATE_6000000; + int64_t minPixelformatDiff = WIDTH_1920_HEIGHT_1080 - pixelformat; + for (auto it = ENCODER_BITRATE_TABLE.begin(); it != ENCODER_BITRATE_TABLE.end(); it++) { + int64_t pixelformatDiff = abs(pixelformat - it->first); + if (pixelformatDiff == 0) { + matchedBitrate = it->second; + break; + } + if (minPixelformatDiff >= pixelformatDiff) { + minPixelformatDiff = pixelformatDiff; + matchedBitrate = it->second; + } + } + DHLOGD("Source config: width : %d, height : %d, matched bitrate %d.", sourceConfig_.GetWidth(), + sourceConfig_.GetHeight(), matchedBitrate); + metadataFormat_.PutIntValue("bitrate", matchedBitrate); + return DCAMERA_OK; +} + +void EncodeDataProcess::ReleaseProcessNode() +{ + DHLOGD("Start release [%d] node : EncodeNode.", nodeRank_); + isEncoderProcess_ = false; + if (nextDataProcess_ != nullptr) { + nextDataProcess_->ReleaseProcessNode(); + } + + { + std::lock_guard lck(mtxEncoderState_); + if (videoEncoder_ != nullptr) { + DHLOGD("Start release videoEncoder."); + videoEncoder_->Flush(); + videoEncoder_->Stop(); + videoEncoder_->Release(); + encodeProducerSurface_ = nullptr; + videoEncoder_ = nullptr; + encodeVideoCallback_ = nullptr; + } + } + + waitEncoderOutputCount_ = 0; + lastFeedEncoderInputBufferTimeUs_ = 0; + inputTimeStampUs_ = 0; + processType_ = ""; + DHLOGD("Release [%d] node : EncodeNode end.", nodeRank_); +} + +int32_t EncodeDataProcess::ProcessData(std::vector>& inputBuffers) +{ + DHLOGD("Process data in EncodeDataProcess."); + if (inputBuffers.empty()) { + DHLOGE("The input data buffers is empty."); + return DCAMERA_BAD_VALUE; + } + if (sourceConfig_.GetVideoCodecType() == targetConfig_.GetVideoCodecType()) { + DHLOGD("The target VideoCodecType : %d is the same as the source VideoCodecType : %d.", + sourceConfig_.GetVideoCodecType(), targetConfig_.GetVideoCodecType()); + return EncodeDone(inputBuffers); + } + + if (videoEncoder_ == nullptr) { + DHLOGE("The video encoder does not exist before encoding data."); + return DCAMERA_INIT_ERR; + } + if (inputBuffers[0]->Size() > NORM_YUV420_BUFFER_SIZE) { + DHLOGE("EncodeNode input buffer size %d error.", inputBuffers[0]->Size()); + return DCAMERA_MEMORY_OPT_ERROR; + } + if (!isEncoderProcess_) { + DHLOGE("EncodeNode occurred error or start release."); + return DCAMERA_DISABLE_PROCESS; + } + int32_t err = FeedEncoderInputBuffer(inputBuffers[0]); + if (err != DCAMERA_OK) { + DHLOGE("Feed encoder input Buffer fail."); + return err; + } + { + std::lock_guard lck(mtxHoldCount_); + if (inputTimeStampUs_ == 0) { + waitEncoderOutputCount_ += FIRST_FRAME_OUTPUT_NUM; + } else { + waitEncoderOutputCount_++; + } + DHLOGD("Wait encoder output frames number is %d.", waitEncoderOutputCount_); + } + return DCAMERA_OK; +} + +int32_t EncodeDataProcess::FeedEncoderInputBuffer(std::shared_ptr& inputBuffer) +{ + std::lock_guard lck(mtxEncoderState_); + DHLOGD("Feed encoder input buffer, buffer size %d.", inputBuffer->Size()); + if (encodeProducerSurface_ == nullptr) { + DHLOGE("Get encoder input producer surface failed."); + return DCAMERA_INIT_ERR; + } + sptr surfacebuffer = GetEncoderInputSurfaceBuffer(); + if (surfacebuffer == nullptr) { + DHLOGE("Get encoder input producer surface buffer failed."); + return DCAMERA_BAD_OPERATE; + } + uint8_t *addr = static_cast(surfacebuffer->GetVirAddr()); + if (addr == nullptr) { + DHLOGE("SurfaceBuffer address is nullptr"); + encodeProducerSurface_->CancelBuffer(surfacebuffer); + return DCAMERA_BAD_OPERATE; + } + size_t size = static_cast(surfacebuffer->GetSize()); + errno_t err = memcpy_s(addr, size, inputBuffer->Data(), inputBuffer->Size()); + if (err != EOK) { + DHLOGE("memcpy_s encoder input producer surface buffer failed."); + return DCAMERA_MEMORY_OPT_ERROR; + } + inputTimeStampUs_ = GetEncoderTimeStamp(); + DHLOGD("Encoder input buffer size %d, timeStamp %lld.", inputBuffer->Size(), (long long)inputTimeStampUs_); + surfacebuffer->ExtraSet("timeStamp", inputTimeStampUs_); + BufferFlushConfig flushConfig = { {0, 0, sourceConfig_.GetWidth(), sourceConfig_.GetHeight()}, 0}; + SurfaceError ret = encodeProducerSurface_->FlushBuffer(surfacebuffer, -1, flushConfig); + if (ret != SURFACE_ERROR_OK) { + DHLOGE("Flush encoder input producer surface buffer failed."); + return DCAMERA_BAD_OPERATE; + } + return DCAMERA_OK; +} + +sptr EncodeDataProcess::GetEncoderInputSurfaceBuffer() +{ + BufferRequestConfig requestConfig; + requestConfig.width = static_cast(sourceConfig_.GetWidth()); + requestConfig.height = static_cast(sourceConfig_.GetHeight()); + requestConfig.usage = HBM_USE_CPU_READ | HBM_USE_CPU_WRITE | HBM_USE_MEM_DMA; + requestConfig.timeout = 0; + requestConfig.strideAlignment = ENCODER_STRIDE_ALIGNMENT; + switch (sourceConfig_.GetVideoformat()) { + case Videoformat::YUVI420: + requestConfig.format = PixelFormat::PIXEL_FMT_YCBCR_420_P; + break; + case Videoformat::NV12: + requestConfig.format = PixelFormat::PIXEL_FMT_YCBCR_420_SP; + break; + case Videoformat::NV21: + requestConfig.format = PixelFormat::PIXEL_FMT_YCRCB_420_SP; + break; + default: + DHLOGE("The current pixel format does not support encoding."); + return nullptr; + } + sptr surfacebuffer = nullptr; + int32_t flushFence = -1; + GSError err = encodeProducerSurface_->RequestBuffer(surfacebuffer, flushFence, requestConfig); + if (err != GSERROR_OK || surfacebuffer == nullptr) { + DHLOGE("Request encoder input producer surface buffer failed, error code: %d.", err); + } + return surfacebuffer; +} + +int64_t EncodeDataProcess::GetEncoderTimeStamp() +{ + int64_t TimeDifferenceStampUs = 0; + const int64_t nsPerUs = 1000L; + int64_t nowTimeUs = GetNowTimeStampUs() * nsPerUs; + if (lastFeedEncoderInputBufferTimeUs_ == 0) { + lastFeedEncoderInputBufferTimeUs_ = nowTimeUs; + return TimeDifferenceStampUs; + } + TimeDifferenceStampUs = nowTimeUs - lastFeedEncoderInputBufferTimeUs_; + lastFeedEncoderInputBufferTimeUs_ = nowTimeUs; + return TimeDifferenceStampUs; +} + +int32_t EncodeDataProcess::GetEncoderOutputBuffer(uint32_t index, Media::AVCodecBufferInfo info) +{ + DHLOGD("Get encoder output buffer."); + if (videoEncoder_ == nullptr) { + DHLOGE("The video encoder does not exist before output encoded data."); + return DCAMERA_BAD_VALUE; + } + std::shared_ptr sharedMemoryOutput = videoEncoder_->GetOutputBuffer(index); + if (sharedMemoryOutput == nullptr) { + DHLOGE("Failed to get the output shared memory, index : %d", index); + return DCAMERA_BAD_OPERATE; + } + + if (info.size <= 0) { + DHLOGE("AVCodecBufferInfo error, buffer size : %d", info.size); + return DCAMERA_BAD_VALUE; + } + + size_t outputMemoDataSize = static_cast(info.size); + DHLOGD("Encoder output buffer size : %d", outputMemoDataSize); + std::shared_ptr bufferOutput = std::make_shared(outputMemoDataSize); + errno_t err = memcpy_s(bufferOutput->Data(), bufferOutput->Size(), + sharedMemoryOutput->GetBase(), outputMemoDataSize); + if (err != EOK) { + DHLOGE("memcpy_s buffer failed."); + return DCAMERA_MEMORY_OPT_ERROR; + } + bufferOutput->SetInt64("timeUs", info.presentationTimeUs); + + std::vector> nextInputBuffers; + nextInputBuffers.push_back(bufferOutput); + return EncodeDone(nextInputBuffers); +} + +int32_t EncodeDataProcess::EncodeDone(std::vector> outputBuffers) +{ + DHLOGD("Encoder done."); + if (outputBuffers.empty()) { + DHLOGE("The received data buffers is empty."); + return DCAMERA_BAD_VALUE; + } + + if (nextDataProcess_ != nullptr) { + DHLOGD("Send to the next node of the encoder for processing."); + int32_t err = nextDataProcess_->ProcessData(outputBuffers); + if (err != DCAMERA_OK) { + DHLOGE("Someone node after the encoder processes fail."); + } + return err; + } + DHLOGD("The current node is the last node, and Output the processed video buffer"); + std::shared_ptr targetPipelineSink = callbackPipelineSink_.lock(); + if (targetPipelineSink == nullptr) { + DHLOGE("callbackPipelineSink_ is nullptr."); + return DCAMERA_BAD_VALUE; + } + targetPipelineSink->OnProcessedVideoBuffer(outputBuffers[0]); + return DCAMERA_OK; +} + +void EncodeDataProcess::OnError() +{ + DHLOGD("EncodeDataProcess : OnError."); + isEncoderProcess_ = false; + videoEncoder_->Flush(); + videoEncoder_->Stop(); + std::shared_ptr targetPipelineSink = callbackPipelineSink_.lock(); + if (targetPipelineSink == nullptr) { + DHLOGE("callbackPipelineSink_ is nullptr."); + return; + } + targetPipelineSink->OnError(DataProcessErrorType::ERROR_PIPELINE_ENCODER); +} + +void EncodeDataProcess::OnInputBufferAvailable(uint32_t index) +{ + DHLOGD("The available input buffer index : %d. No operation when using surface input.", index); +} + +void EncodeDataProcess::OnOutputFormatChanged(const Media::Format &format) +{ + if (encodeOutputFormat_.GetFormatMap().empty()) { + DHLOGE("The first changed video encoder output format is null."); + return; + } + encodeOutputFormat_ = format; +} + +void EncodeDataProcess::OnOutputBufferAvailable(uint32_t index, Media::AVCodecBufferInfo info, + Media::AVCodecBufferFlag flag) +{ + if (!isEncoderProcess_) { + DHLOGE("EncodeNode occurred error or start release."); + return; + } + DHLOGD("Video encode buffer info: presentation TimeUs %lld, size %d, offset %d, flag %d", + info.presentationTimeUs, info.size, info.offset, flag); + int32_t err = GetEncoderOutputBuffer(index, info); + if (err != DCAMERA_OK) { + DHLOGE("Get encode output Buffer fail."); + return; + } + { + std::lock_guard lck(mtxHoldCount_); + if (waitEncoderOutputCount_ <= 0) { + DHLOGE("The waitEncoderOutputCount_ = %d.", waitEncoderOutputCount_); + } + waitEncoderOutputCount_--; + DHLOGD("Wait encoder output frames number is %d.", waitEncoderOutputCount_); + } + if (videoEncoder_ == nullptr) { + DHLOGE("The video encoder does not exist before release output buffer index."); + return; + } + int32_t errRelease = videoEncoder_->ReleaseOutputBuffer(index); + if (errRelease != Media::MediaServiceErrCode::MSERR_OK) { + DHLOGE("The video encoder release output buffer fail, index : [%d].", index); + } +} +VideoConfigParams EncodeDataProcess::GetSourceConfig() const +{ + return sourceConfig_; +} + +VideoConfigParams EncodeDataProcess::GetTargetConfig() const +{ + return targetConfig_; +} +} +} \ No newline at end of file diff --git a/services/data_process/src/pipeline_node/multimedia_codec/encode_video_callback.cpp b/services/data_process/src/pipeline_node/multimedia_codec/encode_video_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27b05a22544a0d61d99796e7f5ef5fe0a478c3d2 --- /dev/null +++ b/services/data_process/src/pipeline_node/multimedia_codec/encode_video_callback.cpp @@ -0,0 +1,66 @@ +/* + * 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 + +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +void EncodeVideoCallback::OnError(Media::AVCodecErrorType errorType, int32_t errorCode) +{ + DHLOGD("EncodeVideoCallback : OnError. Error type: %d . Error code: %d ", errorType, errorCode); + std::shared_ptr targetEncoderNode = encodeVideoNode_.lock(); + if (targetEncoderNode == nullptr) { + DHLOGE("encodeVideoNode_ is nullptr."); + return; + } + targetEncoderNode->OnError(); +} + +void EncodeVideoCallback::OnInputBufferAvailable(uint32_t index) +{ + DHLOGD("EncodeVideoCallback : OnInputBufferAvailable. No operation when using surface input."); + std::shared_ptr targetEncoderNode = encodeVideoNode_.lock(); + if (targetEncoderNode == nullptr) { + DHLOGE("encodeVideoNode_ is nullptr."); + return; + } + targetEncoderNode->OnInputBufferAvailable(index); +} + +void EncodeVideoCallback::OnOutputFormatChanged(const Media::Format &format) +{ + DHLOGD("EncodeVideoCallback : OnOutputFormatChanged."); + std::shared_ptr targetEncoderNode = encodeVideoNode_.lock(); + if (targetEncoderNode == nullptr) { + DHLOGE("encodeVideoNode_ is nullptr."); + return; + } + targetEncoderNode->OnOutputFormatChanged(format); +} + +void EncodeVideoCallback::OnOutputBufferAvailable(uint32_t index, Media::AVCodecBufferInfo info, + Media::AVCodecBufferFlag flag) +{ + DHLOGD("EncodeVideoCallback : OnOutputBufferAvailable."); + std::shared_ptr targetEncoderNode = encodeVideoNode_.lock(); + if (targetEncoderNode == nullptr) { + DHLOGE("encodeVideoNode_ is nullptr."); + return; + } + targetEncoderNode->OnOutputBufferAvailable(index, info, flag); +} +} +} \ No newline at end of file diff --git a/services/data_process/src/utils/image_common_type.cpp b/services/data_process/src/utils/image_common_type.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c96dee454ad265b0271b9a03c65eca3ef5cab5a --- /dev/null +++ b/services/data_process/src/utils/image_common_type.cpp @@ -0,0 +1,66 @@ +/* + * 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 "image_common_type.h" + +namespace OHOS { +namespace DistributedHardware { +void VideoConfigParams::SetVideoCodecType(VideoCodecType videoCodec) +{ + videoCodec_ = videoCodec; +} + +void VideoConfigParams::SetVideoformat(Videoformat pixelFormat) +{ + pixelFormat_ = pixelFormat; +} + +void VideoConfigParams::SetFrameRate(uint32_t frameRate) +{ + frameRate_ = frameRate; +} + +void VideoConfigParams::SetWidthAndHeight(uint32_t width, uint32_t height) +{ + width_ = width; + height_ = height; +} + +VideoCodecType VideoConfigParams::GetVideoCodecType() const +{ + return videoCodec_; +} + +Videoformat VideoConfigParams::GetVideoformat() const +{ + return pixelFormat_; +} + +uint32_t VideoConfigParams::GetFrameRate() const +{ + return frameRate_; +} + +uint32_t VideoConfigParams::GetWidth() const +{ + return width_; +} + +uint32_t VideoConfigParams::GetHeight() const +{ + return height_; +} +} +} \ No newline at end of file