1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "test_camera_base.h"
16 using namespace std;
17 
18 const std::vector<int32_t> DATA_BASE = {
19     OHOS_CAMERA_STREAM_ID,
20     OHOS_SENSOR_COLOR_CORRECTION_GAINS,
21     OHOS_SENSOR_EXPOSURE_TIME,
22     OHOS_CONTROL_EXPOSURE_MODE,
23     OHOS_CONTROL_AE_EXPOSURE_COMPENSATION,
24     OHOS_CONTROL_FOCUS_MODE,
25     OHOS_CONTROL_METER_MODE,
26     OHOS_CONTROL_FLASH_MODE,
27     OHOS_CONTROL_FPS_RANGES,
28     OHOS_CONTROL_AWB_MODE,
29     OHOS_CONTROL_AF_REGIONS,
30     OHOS_CONTROL_METER_POINT,
31     OHOS_CONTROL_VIDEO_STABILIZATION_MODE,
32     OHOS_CONTROL_FOCUS_STATE,
33     OHOS_CONTROL_EXPOSURE_STATE,
34 };
35 
TestCameraBase()36 TestCameraBase::TestCameraBase()
37 {
38 }
39 
GetCurrentLocalTimeStamp()40 uint64_t TestCameraBase::GetCurrentLocalTimeStamp()
41 {
42     std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp =
43         std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
44     auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
45     return tmp.count();
46 }
47 
StoreImage(const unsigned char * bufStart,const uint32_t size) const48 void TestCameraBase::StoreImage(const unsigned char *bufStart, const uint32_t size) const
49 {
50     constexpr uint32_t pathLen = 64;
51     char path[pathLen] = {0};
52 #ifdef CAMERA_BUILT_ON_OHOS_LITE
53     char prefix[] = "/userdata/photo/";
54 #else
55     char prefix[] = "/data/";
56 #endif
57 
58     int imgFD = 0;
59     int ret = 0;
60 
61     struct timeval start = {};
62     gettimeofday(&start, nullptr);
63     if (sprintf_s(path, sizeof(path), "%spicture_%ld.jpeg", prefix, start.tv_usec) < 0) {
64         CAMERA_LOGE("sprintf_s error .....");
65         return;
66     }
67 
68     imgFD = open(path, O_RDWR | O_CREAT, 00766); // 00766:file operate permission
69     if (imgFD == -1) {
70         CAMERA_LOGE("demo test:open image file error %{public}s.....", strerror(errno));
71         return;
72     }
73 
74     CAMERA_LOGD("demo test:StoreImage %{public}s size == %{public}d", path, size);
75 
76     ret = write(imgFD, bufStart, size);
77     if (ret == -1) {
78         CAMERA_LOGE("demo test:write image file error %{public}s.....", strerror(errno));
79     }
80 
81     close(imgFD);
82 }
83 
StoreVideo(const unsigned char * bufStart,const uint32_t size) const84 void TestCameraBase::StoreVideo(const unsigned char *bufStart, const uint32_t size) const
85 {
86     int ret = 0;
87 
88     ret = write(videoFd_, bufStart, size);
89     if (ret == -1) {
90         CAMERA_LOGE("demo test:write video file error %{public}s.....", strerror(errno));
91     }
92     CAMERA_LOGD("demo test:StoreVideo size == %{public}d", size);
93 }
94 
OpenVideoFile()95 void TestCameraBase::OpenVideoFile()
96 {
97     constexpr uint32_t pathLen = 64;
98     char path[pathLen] = {0};
99 #ifdef CAMERA_BUILT_ON_OHOS_LITE
100     char prefix[] = "/userdata/video/";
101 #else
102     char prefix[] = "/data/";
103 #endif
104     auto seconds = time(nullptr);
105     if (sprintf_s(path, sizeof(path), "%svideo%ld.h264", prefix, seconds) < 0) {
106         CAMERA_LOGE("%{public}s: sprintf  failed", __func__);
107         return;
108     }
109     videoFd_ = open(path, O_RDWR | O_CREAT, 00766); // 00766:file operate permission
110     if (videoFd_ < 0) {
111         CAMERA_LOGE("demo test: StartVideo open %s %{public}s failed", path, strerror(errno));
112     }
113 }
114 
CloseFd()115 void TestCameraBase::CloseFd()
116 {
117     close(videoFd_);
118     videoFd_ = -1;
119 }
120 
PrintFaceDetectInfo(const unsigned char * bufStart,const uint32_t size) const121 void TestCameraBase::PrintFaceDetectInfo(const unsigned char *bufStart, const uint32_t size) const
122 {
123     common_metadata_header_t* data = reinterpret_cast<common_metadata_header_t*>(
124         const_cast<unsigned char*>(bufStart));
125     if (data->item_count > MAX_ITEM_CAPACITY || data->data_count > MAX_DATA_CAPACITY) {
126         CAMERA_LOGE("demo test: invalid item_count or data_count");
127         return;
128     }
129     camera_metadata_item_t entry;
130     int ret = 0;
131     ret = FindCameraMetadataItem(data, OHOS_STATISTICS_FACE_DETECT_SWITCH, &entry);
132     if (ret != 0) {
133         CAMERA_LOGE("demo test: get OHOS_STATISTICS_FACE_DETECT_SWITCH error");
134         return;
135     }
136     uint8_t switchValue = *(entry.data.u8);
137     CAMERA_LOGI("demo test: switchValue=%{public}d", switchValue);
138 
139     ret = FindCameraMetadataItem(data, OHOS_STATISTICS_FACE_RECTANGLES, &entry);
140     if (ret != 0) {
141         CAMERA_LOGE("demo test: get OHOS_STATISTICS_FACE_RECTANGLES error");
142         return;
143     }
144     uint32_t rectCount = entry.count;
145     CAMERA_LOGI("demo test: rectCount=%{public}d", rectCount);
146     std::vector<std::vector<float>> faceRectangles;
147     std::vector<float> faceRectangle;
148     for (int i = 0; i < rectCount; i++) {
149         faceRectangle.push_back(*(entry.data.f + i));
150     }
151     faceRectangles.push_back(faceRectangle);
152     for (std::vector<std::vector<float>>::iterator it = faceRectangles.begin(); it < faceRectangles.end(); it++) {
153         for (std::vector<float>::iterator innerIt = (*it).begin(); innerIt < (*it).end(); innerIt++) {
154             CAMERA_LOGI("demo test: innerIt : %{public}f", *innerIt);
155         }
156     }
157 
158     ret = FindCameraMetadataItem(data, OHOS_STATISTICS_FACE_IDS, &entry);
159     if (ret != 0) {
160         CAMERA_LOGE("demo test: get OHOS_STATISTICS_FACE_IDS error");
161         return;
162     }
163     uint32_t idCount = entry.count;
164     CAMERA_LOGI("demo test: idCount=%{public}d", idCount);
165     std::vector<int32_t> faceIds;
166     for (int i = 0; i < idCount; i++) {
167         faceIds.push_back(*(entry.data.i32 + i));
168     }
169     for (auto it = faceIds.begin(); it != faceIds.end(); it++) {
170         CAMERA_LOGI("demo test: faceIds : %{public}d", *it);
171     }
172 }
173 
SaveYUV(char * type,unsigned char * buffer,int32_t size)174 int32_t TestCameraBase::SaveYUV(char* type, unsigned char* buffer, int32_t size)
175 {
176     int ret;
177     char path[PATH_MAX] = {0};
178     ret = sprintf_s(path, sizeof(path) / sizeof(path[0]), "/mnt/yuv/%s_%lld.yuv", type, GetCurrentLocalTimeStamp());
179     if (ret < 0) {
180         CAMERA_LOGE("%s, sprintf_s failed, errno = %s.", __FUNCTION__, strerror(errno));
181         return -1;
182     }
183     CAMERA_LOGI("%s, save yuv to file %s", __FUNCTION__, path);
184     system("mkdir -p /mnt/yuv");
185     int imgFd = open(path, O_RDWR | O_CREAT, 00766); // 00766: file permissions
186     if (imgFd == -1) {
187         CAMERA_LOGI("%s, open file failed, errno = %s.", __FUNCTION__, strerror(errno));
188         return -1;
189     }
190     ret = write(imgFd, buffer, size);
191     if (ret == -1) {
192         CAMERA_LOGI("%s, write file failed, error = %s", __FUNCTION__, strerror(errno));
193         close(imgFd);
194         return -1;
195     }
196     close(imgFd);
197     return 0;
198 }
199 
DoFbMunmap(unsigned char * addr)200 int TestCameraBase::DoFbMunmap(unsigned char* addr)
201 {
202     int ret;
203     unsigned int size = vinfo_.xres * vinfo_.yres * vinfo_.bits_per_pixel / 8; // 8:picture size;
204     CAMERA_LOGI("main test:munmapped size = %d", size);
205     ret = (munmap(addr, finfo_.smem_len));
206     return ret;
207 }
208 
DoFbMmap(int * pmemfd)209 unsigned char* TestCameraBase::DoFbMmap(int* pmemfd)
210 {
211     unsigned char* ret;
212     int screensize = vinfo_.xres * vinfo_.yres * vinfo_.bits_per_pixel / 8; // 8:picture size
213     ret = static_cast<unsigned char*>(mmap(nullptr, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, *pmemfd, 0));
214     if (ret == MAP_FAILED) {
215         CAMERA_LOGE("main test:do_mmap: pmem mmap() failed: %s (%d)", strerror(errno), errno);
216         return nullptr;
217     }
218     CAMERA_LOGI("main test:do_mmap: pmem mmap fd %d len %u", *pmemfd, screensize);
219     return ret;
220 }
221 
FBLog()222 void TestCameraBase::FBLog()
223 {
224     CAMERA_LOGI("the fixed information is as follow:");
225     CAMERA_LOGI("id=%s", finfo_.id);
226     CAMERA_LOGI("sem_start=%lx", finfo_.smem_start);
227     CAMERA_LOGI("smem_len=%u", finfo_.smem_len);
228     CAMERA_LOGI("type=%u", finfo_.type);
229     CAMERA_LOGI("line_length=%u", finfo_.line_length);
230     CAMERA_LOGI("mmio_start=%lu", finfo_.mmio_start);
231     CAMERA_LOGI("mmio_len=%d", finfo_.mmio_len);
232     CAMERA_LOGI("visual=%d", finfo_.visual);
233 
234     CAMERA_LOGI("variable information is as follow:");
235     CAMERA_LOGI("The xres is :%u", vinfo_.xres);
236     CAMERA_LOGI("The yres is :%u", vinfo_.yres);
237     CAMERA_LOGI("xres_virtual=%u", vinfo_.xres_virtual);
238     CAMERA_LOGI("yres_virtual=%u", vinfo_.yres_virtual);
239     CAMERA_LOGI("xoffset=%u", vinfo_.xoffset);
240     CAMERA_LOGI("yoffset=%u", vinfo_.yoffset);
241     CAMERA_LOGI("bits_per_pixel is :%u", vinfo_.bits_per_pixel);
242     CAMERA_LOGI("red.offset=%u", vinfo_.red.offset);
243     CAMERA_LOGI("red.length=%u", vinfo_.red.length);
244     CAMERA_LOGI("red.msb_right=%u", vinfo_.red.msb_right);
245     CAMERA_LOGI("green.offset=%d", vinfo_.green.offset);
246     CAMERA_LOGI("green.length=%d", vinfo_.green.length);
247     CAMERA_LOGI("green.msb_right=%d", vinfo_.green.msb_right);
248     CAMERA_LOGI("blue.offset=%d", vinfo_.blue.offset);
249     CAMERA_LOGI("blue.length=%d", vinfo_.blue.length);
250     CAMERA_LOGI("blue.msb_right=%d", vinfo_.blue.msb_right);
251     CAMERA_LOGI("transp.offset=%d", vinfo_.transp.offset);
252     CAMERA_LOGI("transp.length=%d", vinfo_.transp.length);
253     CAMERA_LOGI("transp.msb_right=%d", vinfo_.transp.msb_right);
254     CAMERA_LOGI("height=%x", vinfo_.height);
255 }
256 
FBInit()257 OHOS::Camera::RetCode TestCameraBase::FBInit()
258 {
259     fbFd_ = open("/dev/fb0", O_RDWR);
260     if (fbFd_ < 0) {
261         CAMERA_LOGE("main test:cannot open framebuffer %s file node", "/dev/fb0");
262         return RC_ERROR;
263     }
264 
265     if (ioctl(fbFd_, FBIOGET_VSCREENINFO, &vinfo_) < 0) {
266         CAMERA_LOGE("main test:cannot retrieve vscreenInfo!");
267         close(fbFd_);
268         fbFd_ = -1;
269         return RC_ERROR;
270     }
271 
272     if (ioctl(fbFd_, FBIOGET_FSCREENINFO, &finfo_) < 0) {
273         CAMERA_LOGE("main test:can't retrieve fscreenInfo!");
274         close(fbFd_);
275         fbFd_ = -1;
276         return RC_ERROR;
277     }
278 
279     FBLog();
280 
281     CAMERA_LOGI("main test:allocating display buffer memory");
282     displayBuf_ = DoFbMmap(&fbFd_);
283     if (displayBuf_ == nullptr) {
284         CAMERA_LOGE("main test:error displayBuf_ mmap error");
285         close(fbFd_);
286         fbFd_ = -1;
287         return RC_ERROR;
288     }
289     return RC_OK;
290 }
291 
ProcessImage(unsigned char * p,unsigned char * fbp)292 void TestCameraBase::ProcessImage(unsigned char* p, unsigned char* fbp)
293 {
294     unsigned char* in = p;
295     int width = 640; // 640:Displays the size of the width
296     int height = 480; // 480:Displays the size of the height
297     int istride = 1280; // 1280:Initial value of span
298     int x, y, j;
299     int y0, u, v, r, g, b;
300     int32_t location = 0;
301     int xpos = (vinfo_.xres - width) / 2;
302     int ypos = (vinfo_.yres - height) / 2;
303     int yPos, uPos, vPos;
304     int yPosIncrement, uPosIncrement, vPosIncrement;
305 
306     yPos = 0; // 0:Pixel initial value
307     uPos = 1; // 1:Pixel initial value
308     vPos = 3; // 3:Pixel initial value
309     yPosIncrement = 2; // 2:yPos increase value
310     uPosIncrement = 4; // 4:uPos increase value
311     vPosIncrement = 4; // 4:vPos increase value
312 
313     for (y = ypos; y < (height + ypos); y++) {
314         for (j = 0, x = xpos; j < width; j++, x++) {
315             location = (x + vinfo_.xoffset) * (vinfo_.bits_per_pixel / 8) + // 8: The bytes for each time
316             (y + vinfo_.yoffset) * finfo_.line_length; // add one y number of rows at a time
317 
318             y0 = in[yPos];
319             u = in[uPos] - 128; // 128:display size
320             v = in[vPos] - 128; // 128:display size
321 
322             r = RANGE_LIMIT(y0 + v + ((v * 103) >> 8)); // 103,8:display range
323             g = RANGE_LIMIT(y0 - ((u * 88) >> 8) - ((v * 183) >> 8)); // 88,8,183:display range
324             b = RANGE_LIMIT(y0 + u + ((u * 198) >> 8)); // 198,8:display range
325 
326             fbp[location + 1] = ((r & 0xF8) | (g >> 5)); // 5:display range
327             fbp[location + 0] = (((g & 0x1C) << 3) | (b >> 3)); // 3:display range
328 
329             yPos += yPosIncrement;
330 
331             if (j & 0x01) {
332                 uPos += uPosIncrement;
333                 vPos += vPosIncrement;
334             }
335         }
336 
337         yPos = 0; // 0:Pixel initial value
338         uPos = 1; // 1:Pixel initial value
339         vPos = 3; // 3:Pixel initial value
340         in += istride; // add one y number of rows at a time
341     }
342 }
343 
LcdDrawScreen(unsigned char * displayBuf,unsigned char * addr)344 void TestCameraBase::LcdDrawScreen(unsigned char* displayBuf, unsigned char* addr)
345 {
346     ProcessImage(addr, displayBuf);
347 }
348 
BufferCallback(unsigned char * addr,int choice)349 void TestCameraBase::BufferCallback(unsigned char* addr, int choice)
350 {
351     if (choice == PREVIEW_MODE) {
352         LcdDrawScreen(displayBuf_, addr);
353         return;
354     } else {
355         LcdDrawScreen(displayBuf_, addr);
356         std::cout << "==========[test log] capture start saveYuv......" << std::endl;
357         SaveYUV("capture", reinterpret_cast<unsigned char*>(addr), bufSize_);
358         std::cout << "==========[test log] capture end saveYuv......" << std::endl;
359         return;
360     }
361 }
362 
Init()363 void TestCameraBase::Init()
364 {
365     CAMERA_LOGD("TestCameraBase::Init().");
366     if (cameraHost == nullptr) {
367         constexpr const char *demoServiceName = "camera_service";
368         cameraHost = ICameraHost::Get(demoServiceName, false);
369         CAMERA_LOGI("Camera::CameraHost::CreateCameraHost()");
370         if (cameraHost == nullptr) {
371             CAMERA_LOGE("CreateCameraHost failed.");
372             return;
373         }
374         CAMERA_LOGI("CreateCameraHost success.");
375     }
376 
377     OHOS::sptr<DemoCameraHostCallback> cameraHostCallback = new DemoCameraHostCallback();
378     OHOS::Camera::RetCode ret = cameraHost->SetCallback(cameraHostCallback);
379     if (ret != HDI::Camera::V1_0::NO_ERROR) {
380         CAMERA_LOGE("SetCallback failed.");
381         return;
382     } else {
383         CAMERA_LOGI("SetCallback success.");
384     }
385 
386     if (cameraDevice == nullptr) {
387         cameraHost->GetCameraIds(cameraIds);
388         cameraHost->GetCameraAbility(cameraIds.front(), ability_);
389         MetadataUtils::ConvertVecToMetadata(ability_, ability);
390         const OHOS::sptr<DemoCameraDeviceCallback> callback = new DemoCameraDeviceCallback();
391         rc = (CamRetCode)cameraHost->OpenCamera(cameraIds.front(), callback, cameraDevice);
392         if (rc != HDI::Camera::V1_0::NO_ERROR || cameraDevice == nullptr) {
393             CAMERA_LOGE("OpenCamera failed, rc = %{public}d", rc);
394             return;
395         }
396         CAMERA_LOGI("OpenCamera success.");
397     }
398 }
399 
UsbInit()400 void TestCameraBase::UsbInit()
401 {
402     if (cameraHost == nullptr) {
403         constexpr const char *demoServiceName = "camera_service";
404         cameraHost = ICameraHost::Get(demoServiceName, false);
405         if (cameraHost == nullptr) {
406             std::cout << "==========[test log] CreateCameraHost failed." << std::endl;
407             return;
408         }
409         std::cout << "==========[test log] CreateCameraHost success." << std::endl;
410     }
411 
412     OHOS::sptr<DemoCameraHostCallback> cameraHostCallback = new DemoCameraHostCallback();
413     OHOS::Camera::RetCode ret = cameraHost->SetCallback(cameraHostCallback);
414     if (ret != HDI::Camera::V1_0::NO_ERROR) {
415         std::cout << "==========[test log] SetCallback failed." << std::endl;
416         return;
417     } else {
418         std::cout << "==========[test log] SetCallback success." << std::endl;
419     }
420 }
421 
GetCameraAbility()422 std::shared_ptr<CameraAbility> TestCameraBase::GetCameraAbility()
423 {
424     if (cameraDevice == nullptr) {
425         OHOS::Camera::RetCode ret = cameraHost->GetCameraIds(cameraIds);
426         if (ret != HDI::Camera::V1_0::NO_ERROR) {
427             std::cout << "==========[test log]GetCameraIds failed." << std::endl;
428             return ability;
429         } else {
430             std::cout << "==========[test log]GetCameraIds success." << std::endl;
431         }
432         if (cameraIds.size() == 0) {
433             std::cout << "==========[test log]camera device list is empty." << std::endl;
434             return ability;
435         }
436         if (cameraIds.size() > 0) {
437             ret = cameraHost->GetCameraAbility(cameraIds.back(), ability_);
438             if (ret != HDI::Camera::V1_0::NO_ERROR) {
439                 std::cout << "==========[test log]GetCameraAbility failed, rc = " << rc << std::endl;
440             }
441             MetadataUtils::ConvertVecToMetadata(ability_, ability);
442         }
443     }
444     return ability;
445 }
446 
OpenUsbCamera()447 void TestCameraBase::OpenUsbCamera()
448 {
449     if (cameraDevice == nullptr) {
450         cameraHost->GetCameraIds(cameraIds);
451         if (cameraIds.size() > 0) {
452             cameraHost->GetCameraAbility(cameraIds.back(), ability_);
453             MetadataUtils::ConvertVecToMetadata(ability_, ability);
454             const OHOS::sptr<DemoCameraDeviceCallback> callback = new DemoCameraDeviceCallback();
455             rc = (CamRetCode)cameraHost->OpenCamera(cameraIds.back(), callback, cameraDevice);
456             if (rc != HDI::Camera::V1_0::NO_ERROR || cameraDevice == nullptr) {
457                 std::cout << "OpenCamera failed, rc = " << rc << std::endl;
458                 return;
459             }
460             std::cout << "OpenCamera success." << std::endl;
461         } else {
462             std::cout << "No usb camera plugged in" << std::endl;
463         }
464     }
465 }
466 
SelectOpenCamera(std::string cameraId)467 CamRetCode TestCameraBase::SelectOpenCamera(std::string cameraId)
468 {
469     cameraHost->GetCameraAbility(cameraId, ability_);
470     MetadataUtils::ConvertVecToMetadata(ability_, ability);
471     const OHOS::sptr<DemoCameraDeviceCallback> callback = new DemoCameraDeviceCallback();
472     rc = (CamRetCode)cameraHost->OpenCamera(cameraId, callback, cameraDevice);
473     if (rc != HDI::Camera::V1_0::NO_ERROR || cameraDevice == nullptr) {
474         std::cout << "OpenCamera failed, rc = " << rc << std::endl;
475         return rc;
476     }
477     std::cout << "OpenCamera success." << std::endl;
478     return rc;
479 }
480 
Close()481 void TestCameraBase::Close()
482 {
483     CAMERA_LOGD("cameraDevice->Close().");
484     if (cameraDevice != nullptr) {
485         cameraDevice->Close();
486         cameraDevice = nullptr;
487     }
488 }
489 
OpenCamera()490 void TestCameraBase::OpenCamera()
491 {
492     if (cameraDevice == nullptr) {
493         cameraHost->GetCameraIds(cameraIds);
494         const OHOS::sptr<OHOS::Camera::CameraDeviceCallback> callback = new CameraDeviceCallback();
495         rc = (CamRetCode)cameraHost->OpenCamera(cameraIds.front(), callback, cameraDevice);
496         if (rc != HDI::Camera::V1_0::NO_ERROR || cameraDevice == nullptr) {
497             std::cout << "==========[test log] OpenCamera failed, rc = " << rc << std::endl;
498             return;
499         }
500         std::cout << "==========[test log]  OpenCamera success." << std::endl;
501     }
502 }
503 
CalTime(struct timeval start,struct timeval end)504 float TestCameraBase::CalTime(struct timeval start, struct timeval end)
505 {
506     float timeUse = 0;
507     timeUse = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // 1000000:time
508     return timeUse;
509 }
510 
AchieveStreamOperator()511 void TestCameraBase::AchieveStreamOperator()
512 {
513     // Create and get streamOperator information
514     OHOS::sptr<DemoStreamOperatorCallback> streamOperatorCallback_ = new DemoStreamOperatorCallback();
515     rc = (CamRetCode)cameraDevice->GetStreamOperator(streamOperatorCallback_, streamOperator);
516     EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
517     if (rc == HDI::Camera::V1_0::NO_ERROR) {
518         CAMERA_LOGI("AchieveStreamOperator success.");
519     } else {
520         CAMERA_LOGE("AchieveStreamOperator fail, rc = %{public}d", rc);
521     }
522 }
523 
StartStream(std::vector<StreamIntent> intents)524 void TestCameraBase::StartStream(std::vector<StreamIntent> intents)
525 {
526     for (auto& intent : intents) {
527         if (intent == PREVIEW) {
528             if (streamCustomerPreview_ == nullptr) {
529                 streamCustomerPreview_ = std::make_shared<StreamCustomer>();
530             }
531             streamInfoPre.streamId_ = STREAM_ID_PREVIEW;
532             streamInfoPre.width_ = PREVIEW_WIDTH; // 640:picture width
533             streamInfoPre.height_ = PREVIEW_HEIGHT; // 480:picture height
534             streamInfoPre.format_ = PIXEL_FMT_RGBA_8888;
535             streamInfoPre.dataspace_ = 8; // 8:picture dataspace
536             streamInfoPre.intent_ = intent;
537             streamInfoPre.tunneledMode_ = 5; // 5:tunnel mode
538             streamInfoPre.bufferQueue_ = new BufferProducerSequenceable(streamCustomerPreview_->CreateProducer());
539             ASSERT_NE(streamInfoPre.bufferQueue_, nullptr);
540             streamInfoPre.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
541             CAMERA_LOGD("preview success.");
542             std::vector<StreamInfo>().swap(streamInfos);
543             streamInfos.push_back(streamInfoPre);
544         } else if (intent == VIDEO) {
545             if (streamCustomerVideo_ == nullptr) {
546                 streamCustomerVideo_ = std::make_shared<StreamCustomer>();
547             }
548             streamInfoVideo.streamId_ = STREAM_ID_VIDEO;
549             streamInfoVideo.width_ = VIDEO_WIDTH; // 1280:picture width
550             streamInfoVideo.height_ = VIDEO_HEIGHT; // 960:picture height
551             streamInfoVideo.format_ = PIXEL_FMT_RGBA_8888;
552             streamInfoVideo.dataspace_ = 8; // 8:picture dataspace
553             streamInfoVideo.intent_ = intent;
554             streamInfoVideo.encodeType_ = ENCODE_TYPE_H264;
555             streamInfoVideo.tunneledMode_ = 5; // 5:tunnel mode
556             streamInfoVideo.bufferQueue_ = new BufferProducerSequenceable(streamCustomerVideo_->CreateProducer());
557             ASSERT_NE(streamInfoVideo.bufferQueue_, nullptr);
558             streamInfoVideo.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
559             CAMERA_LOGD("video success.");
560             std::vector<StreamInfo>().swap(streamInfos);
561             streamInfos.push_back(streamInfoVideo);
562         } else if (intent == STILL_CAPTURE) {
563             if (streamCustomerCapture_ == nullptr) {
564                 streamCustomerCapture_ = std::make_shared<StreamCustomer>();
565             }
566             streamInfoCapture.streamId_ = STREAM_ID_CAPTURE;
567             streamInfoCapture.width_ = CAPTURE_WIDTH; // 1280:picture width
568             streamInfoCapture.height_ = CAPTURE_HEIGHT; // 960:picture height
569             streamInfoCapture.format_ = PIXEL_FMT_RGBA_8888;
570             streamInfoCapture.dataspace_ = 8; // 8:picture dataspace
571             streamInfoCapture.intent_ = intent;
572             streamInfoCapture.encodeType_ = ENCODE_TYPE_JPEG;
573             streamInfoCapture.tunneledMode_ = 5; // 5:tunnel mode
574             streamInfoCapture.bufferQueue_ = new BufferProducerSequenceable(streamCustomerCapture_->CreateProducer());
575             ASSERT_NE(streamInfoCapture.bufferQueue_, nullptr);
576             streamInfoCapture.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
577             CAMERA_LOGD("capture success.");
578             std::vector<StreamInfo>().swap(streamInfos);
579             streamInfos.push_back(streamInfoCapture);
580         } else if (intent == ANALYZE) {
581             if (streamCustomerAnalyze_ == nullptr) {
582                 streamCustomerAnalyze_ = std::make_shared<StreamCustomer>();
583             }
584             streamInfoAnalyze.streamId_ = STREAM_ID_ANALYZE;
585             streamInfoAnalyze.width_ = ANALYZE_WIDTH; // 640:picture width
586             streamInfoAnalyze.height_ = ANALYZE_HEIGHT; // 480:picture height
587             streamInfoAnalyze.format_ = PIXEL_FMT_RGBA_8888;
588             streamInfoAnalyze.dataspace_ = 8; // 8:picture dataspace
589             streamInfoAnalyze.intent_ = intent;
590             streamInfoAnalyze.tunneledMode_ = 5; // 5:tunnel mode
591             streamInfoAnalyze.bufferQueue_ = new BufferProducerSequenceable(streamCustomerAnalyze_->CreateProducer());
592             ASSERT_NE(streamInfoAnalyze.bufferQueue_, nullptr);
593             streamInfoAnalyze.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
594             CAMERA_LOGD("analyze success.");
595             std::vector<StreamInfo>().swap(streamInfos);
596             streamInfos.push_back(streamInfoAnalyze);
597         }
598         rc = (CamRetCode)streamOperator->CreateStreams(streamInfos);
599         EXPECT_EQ(false, rc != HDI::Camera::V1_0::NO_ERROR);
600         if (rc == HDI::Camera::V1_0::NO_ERROR) {
601             CAMERA_LOGI("CreateStreams success.");
602         } else {
603             CAMERA_LOGE("CreateStreams fail, rc = %{public}d", rc);
604         }
605 
606         rc = (CamRetCode)streamOperator->CommitStreams(NORMAL, ability_);
607         EXPECT_EQ(false, rc != HDI::Camera::V1_0::NO_ERROR);
608         if (rc == HDI::Camera::V1_0::NO_ERROR) {
609             CAMERA_LOGI("CommitStreams success.");
610         } else {
611             CAMERA_LOGE("CommitStreams fail, rc = %{public}d", rc);
612         }
613     }
614 }
615 
StartCapture(int streamId,int captureId,bool shutterCallback,bool isStreaming)616 void TestCameraBase::StartCapture(int streamId, int captureId, bool shutterCallback, bool isStreaming)
617 {
618     // Get preview
619     captureInfo.streamIds_ = {streamId};
620     captureInfo.captureSetting_ = ability_;
621     captureInfo.enableShutterCallback_ = shutterCallback;
622     rc = (CamRetCode)streamOperator->Capture(captureId, captureInfo, isStreaming);
623     EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
624     if (rc == HDI::Camera::V1_0::NO_ERROR) {
625         CAMERA_LOGI("check Capture: Capture success, captureId = %{public}d", captureId);
626     } else {
627         CAMERA_LOGE("check Capture: Capture fail, rc = %{public}d, captureId = %{public}d", rc, captureId);
628     }
629     if (captureId == CAPTURE_ID_PREVIEW) {
630         streamCustomerPreview_->ReceiveFrameOn(nullptr);
631     } else if (captureId == CAPTURE_ID_CAPTURE) {
632         streamCustomerCapture_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
633             StoreImage(addr, size);
634         });
635     } else if (captureId == CAPTURE_ID_VIDEO) {
636         OpenVideoFile();
637         streamCustomerVideo_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
638             StoreVideo(addr, size);
639         });
640     } else if (captureId == CAPTURE_ID_ANALYZE) {
641         streamCustomerAnalyze_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
642             PrintFaceDetectInfo(addr, size);
643         });
644     }
645     sleep(2); // 2:sleep two second
646 }
647 
StopStream(std::vector<int> & captureIds,std::vector<int> & streamIds)648 void TestCameraBase::StopStream(std::vector<int>& captureIds, std::vector<int>& streamIds)
649 {
650     constexpr uint32_t timeForWaitCancelCapture = 2;
651     sleep(timeForWaitCancelCapture);
652     if (captureIds.size() > 0) {
653         for (const auto &captureId : captureIds) {
654             if (captureId == CAPTURE_ID_PREVIEW) {
655                 streamCustomerPreview_->ReceiveFrameOff();
656             } else if (captureId == CAPTURE_ID_CAPTURE) {
657                 streamCustomerCapture_->ReceiveFrameOff();
658             } else if (captureId == CAPTURE_ID_VIDEO) {
659                 streamCustomerVideo_->ReceiveFrameOff();
660                 sleep(1);
661                 CloseFd();
662             } else if (captureId == CAPTURE_ID_ANALYZE) {
663                 streamCustomerAnalyze_->ReceiveFrameOff();
664             }
665         }
666         for (const auto &captureId : captureIds) {
667             CAMERA_LOGI("check Capture: CancelCapture success, captureId = %{public}d", captureId);
668             rc = (CamRetCode)streamOperator->CancelCapture(captureId);
669             sleep(timeForWaitCancelCapture);
670             EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
671             if (rc == HDI::Camera::V1_0::NO_ERROR) {
672                 CAMERA_LOGI("check Capture: CancelCapture success, captureId = %{public}d", captureId);
673             } else {
674                 CAMERA_LOGE("check Capture: CancelCapture fail, rc = %{public}d, captureId = %{public}d",
675                     rc, captureId);
676             }
677         }
678     }
679     sleep(1);
680     if (streamIds.size() > 0) {
681         // release stream
682         rc = (CamRetCode)streamOperator->ReleaseStreams(streamIds);
683         EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
684         if (rc == HDI::Camera::V1_0::NO_ERROR) {
685             CAMERA_LOGI("check Capture: ReleaseStreams success.");
686         } else {
687             CAMERA_LOGE("check Capture: ReleaseStreams fail, rc = %{public}d, streamIds = %{public}d",
688                 rc, streamIds.front());
689         }
690     }
691 }
692 
PrintStabiliInfo(const std::vector<uint8_t> & result)693 void DemoCameraDeviceCallback::PrintStabiliInfo(const std::vector<uint8_t>& result)
694 {
695     std::shared_ptr<CameraMetadata> metaData;
696     MetadataUtils::ConvertVecToMetadata(result, metaData);
697 
698     if (metaData == nullptr) {
699         CAMERA_LOGE("TestCameraBase: result is null");
700         return;
701     }
702     common_metadata_header_t* data = metaData->get();
703     if (data == nullptr) {
704         CAMERA_LOGE("TestCameraBase: data is null");
705         return;
706     }
707     uint8_t videoStabiliMode;
708     camera_metadata_item_t entry;
709     int ret = FindCameraMetadataItem(data, OHOS_CONTROL_VIDEO_STABILIZATION_MODE, &entry);
710     if (ret != 0) {
711         CAMERA_LOGE("demo test: get OHOS_CONTROL_EXPOSURE_MODE error");
712         return;
713     }
714     videoStabiliMode = *(entry.data.u8);
715     CAMERA_LOGI("videoStabiliMode: %{public}d", static_cast<int>(videoStabiliMode));
716 }
717 
PrintFpsInfo(const std::vector<uint8_t> & result)718 void DemoCameraDeviceCallback::PrintFpsInfo(const std::vector<uint8_t>& result)
719 {
720     std::shared_ptr<CameraMetadata> metaData;
721     MetadataUtils::ConvertVecToMetadata(result, metaData);
722 
723     if (metaData == nullptr) {
724         CAMERA_LOGE("TestCameraBase: result is null");
725         return;
726     }
727     common_metadata_header_t* data = metaData->get();
728     if (data == nullptr) {
729         CAMERA_LOGE("TestCameraBase: data is null");
730         return;
731     }
732     std::vector<int32_t> fpsRange;
733     camera_metadata_item_t entry;
734     int ret = FindCameraMetadataItem(data, OHOS_CONTROL_FPS_RANGES, &entry);
735     if (ret != 0) {
736         CAMERA_LOGE("demo test: get OHOS_CONTROL_EXPOSURE_MODE error");
737         return;
738     }
739 
740     for (int i = 0; i < entry.count; i++) {
741         fpsRange.push_back(*(entry.data.i32 + i));
742     }
743     CAMERA_LOGI("PrintFpsInfo fpsRange: [%{public}d, %{public}d]", fpsRange[0], fpsRange[1]);
744 }
745 
746 #ifndef CAMERA_BUILT_ON_OHOS_LITE
OnError(ErrorType type,int32_t errorCode)747 int32_t DemoCameraDeviceCallback::OnError(ErrorType type, int32_t errorCode)
748 {
749     CAMERA_LOGI("demo test: OnError type : %{public}d, errorMsg : %{public}d", type, errorCode);
750 }
751 
OnResult(uint64_t timestamp,const std::vector<uint8_t> & result)752 int32_t DemoCameraDeviceCallback::OnResult(uint64_t timestamp, const std::vector<uint8_t>& result)
753 {
754     CAMERA_LOGI("%{public}s, enter.", __func__);
755     PrintStabiliInfo(result);
756     PrintFpsInfo(result);
757     DealCameraMetadata(result);
758     return RC_OK;
759 }
760 
OnCameraStatus(const std::string & cameraId,CameraStatus status)761 int32_t DemoCameraHostCallback::OnCameraStatus(const std::string& cameraId, CameraStatus status)
762 {
763     CAMERA_LOGI("%{public}s, enter.", __func__);
764     std::cout << "OnCameraStatus, enter, cameraId = " << cameraId << ", status = " << status << std::endl;
765     return RC_OK;
766 }
767 
OnFlashlightStatus(const std::string & cameraId,FlashlightStatus status)768 int32_t DemoCameraHostCallback::OnFlashlightStatus(const std::string& cameraId, FlashlightStatus status)
769 {
770     CAMERA_LOGI("%{public}s, enter. cameraId = %s, status = %d",
771         __func__, cameraId.c_str(), static_cast<int>(status));
772     return RC_OK;
773 }
774 
OnCameraEvent(const std::string & cameraId,CameraEvent event)775 int32_t DemoCameraHostCallback::OnCameraEvent(const std::string& cameraId, CameraEvent event)
776 {
777     CAMERA_LOGI("%{public}s, enter. cameraId = %s, event = %d",
778         __func__, cameraId.c_str(), static_cast<int>(event));
779     std::cout << "OnCameraEvent, enter, cameraId = " << cameraId << ", event = " << event<< std::endl;
780     return RC_OK;
781 }
782 
OnCaptureStarted(int32_t captureId,const std::vector<int32_t> & streamIds)783 int32_t DemoStreamOperatorCallback::OnCaptureStarted(int32_t captureId, const std::vector<int32_t>& streamIds)
784 {
785     CAMERA_LOGI("%{public}s, enter.", __func__);
786     return RC_OK;
787 }
788 
OnCaptureEnded(int32_t captureId,const std::vector<CaptureEndedInfo> & infos)789 int32_t DemoStreamOperatorCallback::OnCaptureEnded(int32_t captureId, const std::vector<CaptureEndedInfo>& infos)
790 {
791     CAMERA_LOGI("%{public}s, enter.", __func__);
792     return RC_OK;
793 }
794 
DealCameraMetadata(const std::vector<uint8_t> & settings)795 void DemoCameraDeviceCallback::DealCameraMetadata(const std::vector<uint8_t> &settings)
796 {
797     std::shared_ptr<CameraMetadata> result;
798     MetadataUtils::ConvertVecToMetadata(settings, result);
799     if (result == nullptr) {
800         CAMERA_LOGE("TestCameraBase: result is null");
801         return;
802     }
803     common_metadata_header_t *data = result->get();
804     if (data == nullptr) {
805         CAMERA_LOGE("data is null");
806         return;
807     }
808     for (auto it = DATA_BASE.cbegin(); it != DATA_BASE.cend(); it++) {
809         std::string st = {};
810         st = MetadataItemDump(data, *it);
811         CAMERA_LOGI("%{publid}s", st.c_str());
812     }
813 }
814 
OnCaptureError(int32_t captureId,const std::vector<CaptureErrorInfo> & infos)815 int32_t DemoStreamOperatorCallback::OnCaptureError(int32_t captureId, const std::vector<CaptureErrorInfo>& infos)
816 {
817     CAMERA_LOGI("%{public}s, enter.", __func__);
818     return RC_OK;
819 }
820 
OnFrameShutter(int32_t captureId,const std::vector<int32_t> & streamIds,uint64_t timestamp)821 int32_t DemoStreamOperatorCallback::OnFrameShutter(int32_t captureId,
822     const std::vector<int32_t>& streamIds, uint64_t timestamp)
823 {
824     CAMERA_LOGI("%{public}s, enter.", __func__);
825     return RC_OK;
826 }
827 
828 #endif
829