1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "test_common.h"
17 #include <cinttypes>
18 #include <cstdio>
19 #include <fcntl.h>
20 #include <securec.h>
21 #include <sys/time.h>
22 #include <unistd.h>
23 #include "camera_output_capability.h"
24 #include "camera_util.h"
25 #include "camera_log.h"
26 
27 namespace OHOS {
28 namespace CameraStandard {
GetCameraMetadataFormat(CameraFormat format)29 camera_format_t TestUtils::GetCameraMetadataFormat(CameraFormat format)
30 {
31     camera_format_t metaFormat = OHOS_CAMERA_FORMAT_YCRCB_420_SP;
32     const std::unordered_map<CameraFormat, camera_format_t> mapToMetadataFormat = {
33         {CAMERA_FORMAT_YUV_420_SP, OHOS_CAMERA_FORMAT_YCRCB_420_SP},
34         {CAMERA_FORMAT_JPEG, OHOS_CAMERA_FORMAT_JPEG},
35         {CAMERA_FORMAT_RGBA_8888, OHOS_CAMERA_FORMAT_RGBA_8888},
36         {CAMERA_FORMAT_YCBCR_420_888, OHOS_CAMERA_FORMAT_YCBCR_420_888}
37     };
38     auto itr = mapToMetadataFormat.find(format);
39     if (itr != mapToMetadataFormat.end()) {
40         metaFormat = itr->second;
41     }
42     return metaFormat;
43 }
GetCurrentLocalTimeStamp()44 uint64_t TestUtils::GetCurrentLocalTimeStamp()
45 {
46     std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp =
47         std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
48     auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
49     return tmp.count();
50 }
51 
SaveYUV(const char * buffer,int32_t size,SurfaceType type)52 int32_t TestUtils::SaveYUV(const char* buffer, int32_t size, SurfaceType type)
53 {
54     char path[PATH_MAX] = {0};
55     int32_t retVal;
56     CHECK_ERROR_RETURN_RET_LOG((buffer == nullptr) || (size == 0), -1, "buffer is null or size is 0");
57     MEDIA_DEBUG_LOG("TestUtils::SaveYUV(), type: %{public}d", type);
58     if (type == SurfaceType::PREVIEW) {
59         (void)system("mkdir -p /data/media/preview");
60         retVal = sprintf_s(path, sizeof(path) / sizeof(path[0]), "/data/media/preview/%s_%lld.yuv", "preview",
61                            GetCurrentLocalTimeStamp());
62         CHECK_ERROR_RETURN_RET_LOG(retVal < 0, -1, "Path Assignment failed");
63     } else if (type == SurfaceType::PHOTO) {
64         (void)system("mkdir -p /data/media/photo");
65         retVal = sprintf_s(path, sizeof(path) / sizeof(path[0]), "/data/media/photo/%s_%lld.jpg", "photo",
66                            GetCurrentLocalTimeStamp());
67         CHECK_ERROR_RETURN_RET_LOG(retVal < 0, -1, "Path Assignment failed");
68     } else if (type == SurfaceType::SECOND_PREVIEW) {
69         (void)system("mkdir -p /data/media/preview2");
70         retVal = sprintf_s(path, sizeof(path) / sizeof(path[0]), "/data/media/preview2/%s_%lld.yuv", "preview2",
71                            GetCurrentLocalTimeStamp());
72         CHECK_ERROR_RETURN_RET_LOG(retVal < 0, -1, "Path Assignment failed");
73     } else {
74         MEDIA_ERR_LOG("Unexpected flow!");
75         return -1;
76     }
77 
78     MEDIA_DEBUG_LOG("TestUtils::SaveYUV saving file to %{private}s", path);
79     int imgFd = open(path, O_RDWR | O_CREAT, FILE_PERMISSIONS_FLAG);
80     CHECK_ERROR_RETURN_RET_LOG(imgFd == -1, -1, "TestUtils::SaveYUV open file failed, errno = %{public}s.",
81         strerror(errno));
82     int ret = write(imgFd, buffer, size);
83     if (ret == -1) {
84         MEDIA_ERR_LOG("%s, write file failed, error = %{public}s", __FUNCTION__, strerror(errno));
85         close(imgFd);
86         return -1;
87     }
88     close(imgFd);
89     return 0;
90 }
91 
IsNumber(const char number[])92 bool TestUtils::IsNumber(const char number[])
93 {
94     for (int i = 0; number[i] != 0; i++) {
95         if (!std::isdigit(number[i])) {
96             return false;
97         }
98     }
99     return true;
100 }
101 
SaveVideoFile(const char * buffer,int32_t size,VideoSaveMode operationMode,int32_t & fd)102 int32_t TestUtils::SaveVideoFile(const char* buffer, int32_t size, VideoSaveMode operationMode, int32_t &fd)
103 {
104     int32_t retVal = 0;
105 
106     if (operationMode == VideoSaveMode::CREATE) {
107         char path[255] = {0};
108 
109         (void)system("mkdir -p /data/media/video");
110         retVal = sprintf_s(path, sizeof(path) / sizeof(path[0]),
111                            "/data/media/video/%s_%lld.h264", "video", GetCurrentLocalTimeStamp());
112         CHECK_ERROR_RETURN_RET_LOG(retVal < 0, -1, "Failed to create video file name");
113         MEDIA_DEBUG_LOG("%{public}s, save video to file %{private}s", __FUNCTION__, path);
114         fd = open(path, O_RDWR | O_CREAT, FILE_PERMISSIONS_FLAG);
115         if (fd == -1) {
116             std::cout << "open file failed, errno = " << strerror(errno) << std::endl;
117             return -1;
118         }
119     } else if (operationMode == VideoSaveMode::APPEND && fd != -1) {
120         int32_t ret = write(fd, buffer, size);
121         if (ret == -1) {
122             std::cout << "write file failed, error = " << strerror(errno) << std::endl;
123             close(fd);
124             fd = -1;
125             return fd;
126         }
127     } else { // VideoSaveMode::CLOSE
128         if (fd != -1) {
129             close(fd);
130             fd = -1;
131         }
132     }
133     return 0;
134 }
135 
TestCameraMngerCallback(const char * testName)136 TestCameraMngerCallback::TestCameraMngerCallback(const char* testName) : testName_(testName) {
137 }
138 
OnCameraStatusChanged(const CameraStatusInfo & cameraStatusInfo) const139 void TestCameraMngerCallback::OnCameraStatusChanged(const CameraStatusInfo &cameraStatusInfo) const
140 {
141     MEDIA_DEBUG_LOG("OnCameraStatusChanged()");
142     return;
143 }
144 
OnFlashlightStatusChanged(const std::string & cameraID,const FlashStatus flashStatus) const145 void TestCameraMngerCallback::OnFlashlightStatusChanged(const std::string &cameraID,
146                                                         const FlashStatus flashStatus) const
147 {
148     MEDIA_DEBUG_LOG("OnFlashlightStatusChanged(), testName_: %{public}s, cameraID: %{public}s, flashStatus: %{public}d",
149                     testName_, cameraID.c_str(), flashStatus);
150     return;
151 }
152 
TestDeviceCallback(const char * testName)153 TestDeviceCallback::TestDeviceCallback(const char* testName) : testName_(testName) {
154 }
155 
OnError(const int32_t errorType,const int32_t errorMsg) const156 void TestDeviceCallback::OnError(const int32_t errorType, const int32_t errorMsg) const
157 {
158     MEDIA_DEBUG_LOG("TestDeviceCallback::OnError(), testName_: %{public}s, errorType: %{public}d, errorMsg: %{public}d",
159                     testName_, errorType, errorMsg);
160     return;
161 }
162 
TestOnResultCallback(const char * testName)163 TestOnResultCallback::TestOnResultCallback(const char* testName) : testName_(testName) {
164 }
165 
OnResult(const uint64_t timestamp,const std::shared_ptr<Camera::CameraMetadata> & result) const166 void TestOnResultCallback::OnResult(const uint64_t timestamp,
167                                     const std::shared_ptr<Camera::CameraMetadata> &result) const
168 {
169     MEDIA_DEBUG_LOG("TestOnResultCallback::OnResult(), testName_: %{public}s",
170                     testName_);
171     return;
172 }
173 
174 
TestPhotoOutputCallback(const char * testName)175 TestPhotoOutputCallback::TestPhotoOutputCallback(const char* testName) : testName_(testName) {
176 }
177 
OnCaptureStarted(const int32_t captureID) const178 void TestPhotoOutputCallback::OnCaptureStarted(const int32_t captureID) const
179 {
180     MEDIA_INFO_LOG("PhotoOutputCallback:OnCaptureStarted(), testName_: %{public}s, captureID: %{public}d",
181                    testName_, captureID);
182 }
183 
OnCaptureStarted(const int32_t captureID,uint32_t exposureTime) const184 void TestPhotoOutputCallback::OnCaptureStarted(const int32_t captureID, uint32_t exposureTime) const
185 {
186     MEDIA_INFO_LOG("PhotoOutputCallback:OnCaptureStarted(), testName_: %{public}s, captureID: %{public}d",
187                    testName_, captureID);
188 }
189 
OnCaptureEnded(const int32_t captureID,const int32_t frameCount) const190 void TestPhotoOutputCallback::OnCaptureEnded(const int32_t captureID, const int32_t frameCount) const
191 {
192     MEDIA_INFO_LOG("TestPhotoOutputCallback:OnCaptureEnded(), testName_: %{public}s, captureID: %{public}d,"
193                    " frameCount: %{public}d", testName_, captureID, frameCount);
194 }
195 
OnFrameShutter(const int32_t captureId,const uint64_t timestamp) const196 void TestPhotoOutputCallback::OnFrameShutter(const int32_t captureId, const uint64_t timestamp) const
197 {
198     MEDIA_INFO_LOG("OnFrameShutter(), testName_: %{public}s, captureID: %{public}d", testName_, captureId);
199 }
200 
OnFrameShutterEnd(const int32_t captureId,const uint64_t timestamp) const201 void TestPhotoOutputCallback::OnFrameShutterEnd(const int32_t captureId, const uint64_t timestamp) const
202 {
203     MEDIA_INFO_LOG("OnFrameShutterEnd(), testName_: %{public}s, captureID: %{public}d", testName_, captureId);
204 }
205 
OnCaptureReady(const int32_t captureId,const uint64_t timestamp) const206 void TestPhotoOutputCallback::OnCaptureReady(const int32_t captureId, const uint64_t timestamp) const
207 {
208     MEDIA_INFO_LOG("OnCaptureReady(), testName_: %{public}s, captureID: %{public}d", testName_, captureId);
209 }
210 
OnEstimatedCaptureDuration(const int32_t duration) const211 void TestPhotoOutputCallback::OnEstimatedCaptureDuration(const int32_t duration) const
212 {
213     MEDIA_INFO_LOG("OnEstimatedCaptureDuration(), duration: %{public}d", duration);
214 }
215 
OnCaptureError(const int32_t captureId,const int32_t errorCode) const216 void TestPhotoOutputCallback::OnCaptureError(const int32_t captureId, const int32_t errorCode) const
217 {
218     MEDIA_INFO_LOG("OnCaptureError(), testName_: %{public}s, captureID: %{public}d, errorCode: %{public}d",
219                    testName_, captureId, errorCode);
220 }
221 
TestPreviewOutputCallback(const char * testName)222 TestPreviewOutputCallback::TestPreviewOutputCallback(const char* testName) : testName_(testName) {
223 }
224 
OnFrameStarted() const225 void TestPreviewOutputCallback::OnFrameStarted() const
226 {
227     MEDIA_INFO_LOG("TestPreviewOutputCallback:OnFrameStarted(), testName_: %{public}s", testName_);
228 }
229 
OnFrameEnded(const int32_t frameCount) const230 void TestPreviewOutputCallback::OnFrameEnded(const int32_t frameCount) const
231 {
232     MEDIA_INFO_LOG("TestPreviewOutputCallback:OnFrameEnded(), testName_: %{public}s, frameCount: %{public}d",
233                    testName_, frameCount);
234 }
235 
OnError(const int32_t errorCode) const236 void TestPreviewOutputCallback::OnError(const int32_t errorCode) const
237 {
238     MEDIA_INFO_LOG("TestPreviewOutputCallback:OnError(), testName_: %{public}s, errorCode: %{public}d",
239                    testName_, errorCode);
240 }
241 
OnSketchStatusDataChanged(const SketchStatusData & statusData) const242 void TestPreviewOutputCallback::OnSketchStatusDataChanged(const SketchStatusData& statusData) const
243 {
244     MEDIA_DEBUG_LOG("TestPreviewOutputCallback::OnSketchStatusDataChanged(), testName_: %{public}s", testName_);
245     return;
246 }
247 
TestVideoOutputCallback(const char * testName)248 TestVideoOutputCallback::TestVideoOutputCallback(const char* testName) : testName_(testName) {
249 }
250 
OnFrameStarted() const251 void TestVideoOutputCallback::OnFrameStarted() const
252 {
253     MEDIA_INFO_LOG("TestVideoOutputCallback:OnFrameStarted(), testName_: %{public}s", testName_);
254 }
255 
OnFrameEnded(const int32_t frameCount) const256 void TestVideoOutputCallback::OnFrameEnded(const int32_t frameCount) const
257 {
258     MEDIA_INFO_LOG("TestVideoOutputCallback:OnFrameEnded(), testName_: %{public}s, frameCount: %{public}d",
259                    testName_, frameCount);
260 }
261 
OnError(const int32_t errorCode) const262 void TestVideoOutputCallback::OnError(const int32_t errorCode) const
263 {
264     MEDIA_INFO_LOG("TestVideoOutputCallback:OnError(), testName_: %{public}s, errorCode: %{public}d",
265                    testName_, errorCode);
266 }
267 
OnDeferredVideoEnhancementInfo(const CaptureEndedInfoExt info) const268 void TestVideoOutputCallback::OnDeferredVideoEnhancementInfo(const CaptureEndedInfoExt info) const
269 {
270     MEDIA_INFO_LOG("TestVideoOutputCallback:OnDeferredVideoEnhancementInfo()");
271 }
272 
TestMetadataOutputObjectCallback(const char * testName)273 TestMetadataOutputObjectCallback::TestMetadataOutputObjectCallback(const char* testName) : testName_(testName) {
274 }
275 
OnMetadataObjectsAvailable(std::vector<sptr<MetadataObject>> metaObjects) const276 void TestMetadataOutputObjectCallback::OnMetadataObjectsAvailable(std::vector<sptr<MetadataObject>> metaObjects) const
277 {
278     MEDIA_INFO_LOG("TestMetadataOutputObjectCallback:OnMetadataObjectsAvailable(), testName_: %{public}s, "
279                    "metaObjects size: %{public}zu", testName_, metaObjects.size());
280     for (size_t i = 0; i < metaObjects.size(); i++) {
281         MEDIA_INFO_LOG("TestMetadataOutputObjectCallback::OnMetadataObjectsAvailable "
282                        "metaObjInfo: Type(%{public}d), Rect{x(%{pulic}f),y(%{pulic}f),w(%{pulic}f),d(%{pulic}f)} "
283                        "Timestamp: %{public}" PRId64,
284                        metaObjects[i]->GetType(),
285                        metaObjects[i]->GetBoundingBox().topLeftX, metaObjects[i]->GetBoundingBox().topLeftY,
286                        metaObjects[i]->GetBoundingBox().width, metaObjects[i]->GetBoundingBox().height,
287                        static_cast<int64_t>(metaObjects[i]->GetTimestamp()));
288     }
289 }
290 
OnProcessImageDone(const std::string & imageId,const uint8_t * addr,const long bytes,bool isCloudImageEnhanceSupported)291 void TestDeferredPhotoProcSessionCallback::OnProcessImageDone(const std::string& imageId,
292                                                               const uint8_t* addr,
293                                                               const long bytes, bool isCloudImageEnhanceSupported)
294 {
295     MEDIA_INFO_LOG("TestDeferredPhotoProcSessionCallback OnProcessImageDone.");
296 }
297 
OnProcessImageDone(const std::string & imageId,std::shared_ptr<Media::Picture> picture,bool isCloudImageEnhanceSupported)298 void TestDeferredPhotoProcSessionCallback::OnProcessImageDone(const std::string &imageId,
299     std::shared_ptr<Media::Picture> picture, bool isCloudImageEnhanceSupported)
300 {
301     MEDIA_INFO_LOG("TestDeferredPhotoProcSessionCallback OnProcessImageDone Picture.");
302 }
303 
OnDeliveryLowQualityImage(const std::string & imageId,std::shared_ptr<Media::Picture> picture)304 void TestDeferredPhotoProcSessionCallback::OnDeliveryLowQualityImage(const std::string &imageId,
305     std::shared_ptr<Media::Picture> picture)
306 {
307     MEDIA_INFO_LOG("TestDeferredPhotoProcSessionCallback OnDeliveryLowQualityImage.");
308 }
309 
OnError(const std::string & imageId,const DpsErrorCode errorCode)310 void TestDeferredPhotoProcSessionCallback::OnError(const std::string& imageId, const DpsErrorCode errorCode)
311 {
312     MEDIA_INFO_LOG("TestDeferredPhotoProcSessionCallback OnError.");
313 }
314 
OnStateChanged(const DpsStatusCode status)315 void TestDeferredPhotoProcSessionCallback::OnStateChanged(const DpsStatusCode status)
316 {
317     MEDIA_INFO_LOG("TestDeferredPhotoProcSessionCallback OnStateChanged.");
318 }
319 
SurfaceListener(const char * testName,SurfaceType type,int32_t & fd,sptr<IConsumerSurface> surface)320 SurfaceListener::SurfaceListener(const char* testName, SurfaceType type, int32_t &fd, sptr<IConsumerSurface> surface)
321     : testName_(testName), surfaceType_(type), fd_(fd), surface_(surface) {
322 }
323 
OnBufferAvailable()324 void SurfaceListener::OnBufferAvailable()
325 {
326     int32_t flushFence = 0;
327     int64_t timestamp = 0;
328     OHOS::Rect damage;
329     MEDIA_DEBUG_LOG("SurfaceListener::OnBufferAvailable(), testName_: %{public}s, surfaceType_: %{public}d",
330                     testName_, surfaceType_);
331     OHOS::sptr<OHOS::SurfaceBuffer> buffer = nullptr;
332     if (surface_ == nullptr) {
333         MEDIA_ERR_LOG("OnBufferAvailable:surface_ is null");
334         return;
335     }
336     surface_->AcquireBuffer(buffer, flushFence, timestamp, damage);
337     if (buffer != nullptr) {
338         char* addr = static_cast<char *>(buffer->GetVirAddr());
339         int32_t size = buffer->GetSize();
340 
341         switch (surfaceType_) {
342             case SurfaceType::PREVIEW:
343                 if (previewIndex_ % TestUtils::PREVIEW_SKIP_FRAMES == 0
344                     && TestUtils::SaveYUV(addr, size, surfaceType_) != CAMERA_OK) {
345                     MEDIA_ERR_LOG("Failed to save buffer");
346                     previewIndex_ = 0;
347                 }
348                 previewIndex_++;
349                 break;
350 
351             case SurfaceType::SECOND_PREVIEW:
352                 if (secondPreviewIndex_ % TestUtils::PREVIEW_SKIP_FRAMES == 0
353                     && TestUtils::SaveYUV(addr, size, surfaceType_) != CAMERA_OK) {
354                     MEDIA_ERR_LOG("Failed to save buffer");
355                     secondPreviewIndex_ = 0;
356                 }
357                 secondPreviewIndex_++;
358                 break;
359 
360             case SurfaceType::PHOTO:
361                 if (TestUtils::SaveYUV(addr, size, surfaceType_) != CAMERA_OK) {
362                     MEDIA_ERR_LOG("Failed to save buffer");
363                 }
364                 break;
365 
366             case SurfaceType::VIDEO:
367                 if (fd_ == -1 && (TestUtils::SaveVideoFile(nullptr, 0, VideoSaveMode::CREATE, fd_) != CAMERA_OK)) {
368                     MEDIA_ERR_LOG("Failed to Create video file");
369                 }
370                 if (TestUtils::SaveVideoFile(addr, size, VideoSaveMode::APPEND, fd_) != CAMERA_OK) {
371                     MEDIA_ERR_LOG("Failed to save buffer");
372                 }
373                 break;
374 
375             default:
376                 MEDIA_ERR_LOG("Unexpected type");
377                 break;
378         }
379         surface_->ReleaseBuffer(buffer, -1);
380     } else {
381         MEDIA_ERR_LOG("AcquireBuffer failed!");
382     }
383 }
384 } // namespace CameraStandard
385 } // namespace OHOS
386 
387