• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
DefaultInfosPreview()504 void TestCameraBase::DefaultInfosPreview()
505 {
506     if (streamCustomerPreview_ == nullptr) {
507         streamCustomerPreview_ = std::make_shared<StreamCustomer>();
508     }
509     streamInfoPre.streamId_ = STREAM_ID_PREVIEW;
510     streamInfoPre.width_ = PREVIEW_WIDTH; // 640:picture width
511     streamInfoPre.height_ = PREVIEW_HEIGHT; // 480:picture height
512     streamInfoPre.format_ = PIXEL_FMT_RGBA_8888;
513     streamInfoPre.dataspace_ = 8; // 8:picture dataspace
514     streamInfoPre.intent_ = PREVIEW;
515     streamInfoPre.tunneledMode_ = 5; // 5:tunnel mode
516     streamInfoPre.bufferQueue_ = new BufferProducerSequenceable(streamCustomerPreview_->CreateProducer());
517     ASSERT_NE(streamInfoPre.bufferQueue_, nullptr);
518     streamInfoPre.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
519     std::cout << "preview success1." << std::endl;
520     std::vector<StreamInfo>().swap(streamInfos);
521     streamInfos.push_back(streamInfoPre);
522 }
523 
DefaultInfosCapture()524 void TestCameraBase::DefaultInfosCapture()
525 {
526     if (streamCustomerCapture_ == nullptr) {
527         streamCustomerCapture_ = std::make_shared<StreamCustomer>();
528     }
529     streamInfoCapture.streamId_ = STREAM_ID_CAPTURE;
530     streamInfoCapture.width_ = CAPTURE_WIDTH; // 1280:picture width
531     streamInfoCapture.height_ = CAPTURE_HEIGHT; // 960:picture height
532     streamInfoCapture.format_ = PIXEL_FMT_RGBA_8888;
533     streamInfoCapture.dataspace_ = 8; // 8:picture dataspace
534     streamInfoCapture.intent_ = STILL_CAPTURE;
535     streamInfoCapture.encodeType_ = ENCODE_TYPE_JPEG;
536     streamInfoCapture.tunneledMode_ = 5; // 5:tunnel mode
537     streamInfoCapture.bufferQueue_ = new BufferProducerSequenceable(streamCustomerCapture_->CreateProducer());
538     ASSERT_NE(streamInfoCapture.bufferQueue_, nullptr);
539     streamInfoCapture.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
540     std::cout << "capture success1." << std::endl;
541     streamInfos.push_back(streamInfoCapture);
542 }
543 
CalTime(struct timeval start,struct timeval end)544 float TestCameraBase::CalTime(struct timeval start, struct timeval end)
545 {
546     float timeUse = 0;
547     timeUse = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // 1000000:time
548     return timeUse;
549 }
550 
AchieveStreamOperator()551 void TestCameraBase::AchieveStreamOperator()
552 {
553     // Create and get streamOperator information
554     OHOS::sptr<DemoStreamOperatorCallback> streamOperatorCallback_ = new DemoStreamOperatorCallback();
555     rc = (CamRetCode)cameraDevice->GetStreamOperator(streamOperatorCallback_, streamOperator);
556     EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
557     if (rc == HDI::Camera::V1_0::NO_ERROR) {
558         CAMERA_LOGI("AchieveStreamOperator success.");
559     } else {
560         CAMERA_LOGE("AchieveStreamOperator fail, rc = %{public}d", rc);
561     }
562 }
563 
StartStream(std::vector<StreamIntent> intents)564 void TestCameraBase::StartStream(std::vector<StreamIntent> intents)
565 {
566     for (auto& intent : intents) {
567         if (intent == PREVIEW) {
568             if (streamCustomerPreview_ == nullptr) {
569                 streamCustomerPreview_ = std::make_shared<StreamCustomer>();
570             }
571             streamInfoPre.streamId_ = STREAM_ID_PREVIEW;
572             streamInfoPre.width_ = PREVIEW_WIDTH; // 640:picture width
573             streamInfoPre.height_ = PREVIEW_HEIGHT; // 480:picture height
574             streamInfoPre.format_ = PIXEL_FMT_RGBA_8888;
575             streamInfoPre.dataspace_ = 8; // 8:picture dataspace
576             streamInfoPre.intent_ = intent;
577             streamInfoPre.tunneledMode_ = 5; // 5:tunnel mode
578             streamInfoPre.bufferQueue_ = new BufferProducerSequenceable(streamCustomerPreview_->CreateProducer());
579             ASSERT_NE(streamInfoPre.bufferQueue_, nullptr);
580             streamInfoPre.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
581             CAMERA_LOGD("preview success.");
582             std::vector<StreamInfo>().swap(streamInfos);
583             streamInfos.push_back(streamInfoPre);
584         } else if (intent == VIDEO) {
585             if (streamCustomerVideo_ == nullptr) {
586                 streamCustomerVideo_ = std::make_shared<StreamCustomer>();
587             }
588             streamInfoVideo.streamId_ = STREAM_ID_VIDEO;
589             streamInfoVideo.width_ = VIDEO_WIDTH; // 1280:picture width
590             streamInfoVideo.height_ = VIDEO_HEIGHT; // 960:picture height
591             streamInfoVideo.format_ = PIXEL_FMT_RGBA_8888;
592             streamInfoVideo.dataspace_ = 8; // 8:picture dataspace
593             streamInfoVideo.intent_ = intent;
594             streamInfoVideo.encodeType_ = ENCODE_TYPE_H264;
595             streamInfoVideo.tunneledMode_ = 5; // 5:tunnel mode
596             streamInfoVideo.bufferQueue_ = new BufferProducerSequenceable(streamCustomerVideo_->CreateProducer());
597             ASSERT_NE(streamInfoVideo.bufferQueue_, nullptr);
598             streamInfoVideo.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
599             CAMERA_LOGD("video success.");
600             std::vector<StreamInfo>().swap(streamInfos);
601             streamInfos.push_back(streamInfoVideo);
602         } else if (intent == STILL_CAPTURE) {
603             if (streamCustomerCapture_ == nullptr) {
604                 streamCustomerCapture_ = std::make_shared<StreamCustomer>();
605             }
606             streamInfoCapture.streamId_ = STREAM_ID_CAPTURE;
607             streamInfoCapture.width_ = CAPTURE_WIDTH; // 1280:picture width
608             streamInfoCapture.height_ = CAPTURE_HEIGHT; // 960:picture height
609             streamInfoCapture.format_ = PIXEL_FMT_RGBA_8888;
610             streamInfoCapture.dataspace_ = 8; // 8:picture dataspace
611             streamInfoCapture.intent_ = intent;
612             streamInfoCapture.encodeType_ = ENCODE_TYPE_JPEG;
613             streamInfoCapture.tunneledMode_ = 5; // 5:tunnel mode
614             streamInfoCapture.bufferQueue_ = new BufferProducerSequenceable(streamCustomerCapture_->CreateProducer());
615             ASSERT_NE(streamInfoCapture.bufferQueue_, nullptr);
616             streamInfoCapture.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
617             CAMERA_LOGD("capture success.");
618             std::vector<StreamInfo>().swap(streamInfos);
619             streamInfos.push_back(streamInfoCapture);
620         } else if (intent == ANALYZE) {
621             if (streamCustomerAnalyze_ == nullptr) {
622                 streamCustomerAnalyze_ = std::make_shared<StreamCustomer>();
623             }
624             streamInfoAnalyze.streamId_ = STREAM_ID_ANALYZE;
625             streamInfoAnalyze.width_ = ANALYZE_WIDTH; // 640:picture width
626             streamInfoAnalyze.height_ = ANALYZE_HEIGHT; // 480:picture height
627             streamInfoAnalyze.format_ = PIXEL_FMT_RGBA_8888;
628             streamInfoAnalyze.dataspace_ = 8; // 8:picture dataspace
629             streamInfoAnalyze.intent_ = intent;
630             streamInfoAnalyze.tunneledMode_ = 5; // 5:tunnel mode
631             streamInfoAnalyze.bufferQueue_ = new BufferProducerSequenceable(streamCustomerAnalyze_->CreateProducer());
632             ASSERT_NE(streamInfoAnalyze.bufferQueue_, nullptr);
633             streamInfoAnalyze.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
634             CAMERA_LOGD("analyze success.");
635             std::vector<StreamInfo>().swap(streamInfos);
636             streamInfos.push_back(streamInfoAnalyze);
637         }
638         rc = (CamRetCode)streamOperator->CreateStreams(streamInfos);
639         EXPECT_EQ(false, rc != HDI::Camera::V1_0::NO_ERROR);
640         if (rc == HDI::Camera::V1_0::NO_ERROR) {
641             CAMERA_LOGI("CreateStreams success.");
642         } else {
643             CAMERA_LOGE("CreateStreams fail, rc = %{public}d", rc);
644         }
645 
646         rc = (CamRetCode)streamOperator->CommitStreams(NORMAL, ability_);
647         EXPECT_EQ(false, rc != HDI::Camera::V1_0::NO_ERROR);
648         if (rc == HDI::Camera::V1_0::NO_ERROR) {
649             CAMERA_LOGI("CommitStreams success.");
650         } else {
651             CAMERA_LOGE("CommitStreams fail, rc = %{public}d", rc);
652         }
653     }
654 }
655 
StartCapture(int streamId,int captureId,bool shutterCallback,bool isStreaming)656 void TestCameraBase::StartCapture(int streamId, int captureId, bool shutterCallback, bool isStreaming)
657 {
658     // Get preview
659     captureInfo.streamIds_ = {streamId};
660     captureInfo.captureSetting_ = ability_;
661     captureInfo.enableShutterCallback_ = shutterCallback;
662     rc = (CamRetCode)streamOperator->Capture(captureId, captureInfo, isStreaming);
663     EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
664     if (rc == HDI::Camera::V1_0::NO_ERROR) {
665         CAMERA_LOGI("check Capture: Capture success, captureId = %{public}d", captureId);
666     } else {
667         CAMERA_LOGE("check Capture: Capture fail, rc = %{public}d, captureId = %{public}d", rc, captureId);
668     }
669     if (captureId == CAPTURE_ID_PREVIEW) {
670         streamCustomerPreview_->ReceiveFrameOn(nullptr);
671     } else if (captureId == CAPTURE_ID_CAPTURE) {
672         streamCustomerCapture_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
673             StoreImage(addr, size);
674         });
675     } else if (captureId == CAPTURE_ID_VIDEO) {
676         OpenVideoFile();
677         streamCustomerVideo_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
678             StoreVideo(addr, size);
679         });
680     } else if (captureId == CAPTURE_ID_ANALYZE) {
681         streamCustomerAnalyze_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
682             PrintFaceDetectInfo(addr, size);
683         });
684     }
685     sleep(2); // 2:sleep two second
686 }
687 
StopStream(std::vector<int> & captureIds,std::vector<int> & streamIds)688 void TestCameraBase::StopStream(std::vector<int>& captureIds, std::vector<int>& streamIds)
689 {
690     constexpr uint32_t timeForWaitCancelCapture = 2;
691     sleep(timeForWaitCancelCapture);
692     if (captureIds.size() > 0) {
693         for (const auto &captureId : captureIds) {
694             if (captureId == CAPTURE_ID_PREVIEW) {
695                 streamCustomerPreview_->ReceiveFrameOff();
696             } else if (captureId == CAPTURE_ID_CAPTURE) {
697                 streamCustomerCapture_->ReceiveFrameOff();
698             } else if (captureId == CAPTURE_ID_VIDEO) {
699                 streamCustomerVideo_->ReceiveFrameOff();
700                 sleep(1);
701                 CloseFd();
702             } else if (captureId == CAPTURE_ID_ANALYZE) {
703                 streamCustomerAnalyze_->ReceiveFrameOff();
704             }
705         }
706         for (const auto &captureId : captureIds) {
707             CAMERA_LOGI("check Capture: CancelCapture success, captureId = %{public}d", captureId);
708             rc = (CamRetCode)streamOperator->CancelCapture(captureId);
709             sleep(timeForWaitCancelCapture);
710             EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
711             if (rc == HDI::Camera::V1_0::NO_ERROR) {
712                 CAMERA_LOGI("check Capture: CancelCapture success, captureId = %{public}d", captureId);
713             } else {
714                 CAMERA_LOGE("check Capture: CancelCapture fail, rc = %{public}d, captureId = %{public}d",
715                     rc, captureId);
716             }
717         }
718     }
719     sleep(1);
720     if (streamIds.size() > 0) {
721         // release stream
722         rc = (CamRetCode)streamOperator->ReleaseStreams(streamIds);
723         EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
724         if (rc == HDI::Camera::V1_0::NO_ERROR) {
725             CAMERA_LOGI("check Capture: ReleaseStreams success.");
726         } else {
727             CAMERA_LOGE("check Capture: ReleaseStreams fail, rc = %{public}d, streamIds = %{public}d",
728                 rc, streamIds.front());
729         }
730     }
731 }
732 
PrintStabiliInfo(const std::vector<uint8_t> & result)733 void DemoCameraDeviceCallback::PrintStabiliInfo(const std::vector<uint8_t>& result)
734 {
735     std::shared_ptr<CameraMetadata> metaData;
736     MetadataUtils::ConvertVecToMetadata(result, metaData);
737 
738     if (metaData == nullptr) {
739         CAMERA_LOGE("TestCameraBase: result is null");
740         return;
741     }
742     common_metadata_header_t* data = metaData->get();
743     if (data == nullptr) {
744         CAMERA_LOGE("TestCameraBase: data is null");
745         return;
746     }
747     uint8_t videoStabiliMode;
748     camera_metadata_item_t entry;
749     int ret = FindCameraMetadataItem(data, OHOS_CONTROL_VIDEO_STABILIZATION_MODE, &entry);
750     if (ret != 0) {
751         CAMERA_LOGE("demo test: get OHOS_CONTROL_EXPOSURE_MODE error");
752         return;
753     }
754     videoStabiliMode = *(entry.data.u8);
755     CAMERA_LOGI("videoStabiliMode: %{public}d", static_cast<int>(videoStabiliMode));
756 }
757 
PrintFpsInfo(const std::vector<uint8_t> & result)758 void DemoCameraDeviceCallback::PrintFpsInfo(const std::vector<uint8_t>& result)
759 {
760     std::shared_ptr<CameraMetadata> metaData;
761     MetadataUtils::ConvertVecToMetadata(result, metaData);
762 
763     if (metaData == nullptr) {
764         CAMERA_LOGE("TestCameraBase: result is null");
765         return;
766     }
767     common_metadata_header_t* data = metaData->get();
768     if (data == nullptr) {
769         CAMERA_LOGE("TestCameraBase: data is null");
770         return;
771     }
772     std::vector<int32_t> fpsRange;
773     camera_metadata_item_t entry;
774     int ret = FindCameraMetadataItem(data, OHOS_CONTROL_FPS_RANGES, &entry);
775     if (ret != 0) {
776         CAMERA_LOGE("demo test: get OHOS_CONTROL_EXPOSURE_MODE error");
777         return;
778     }
779 
780     for (int i = 0; i < entry.count; i++) {
781         fpsRange.push_back(*(entry.data.i32 + i));
782     }
783     CAMERA_LOGI("PrintFpsInfo fpsRange: [%{public}d, %{public}d]", fpsRange[0], fpsRange[1]);
784 }
785 
786 #ifndef CAMERA_BUILT_ON_OHOS_LITE
OnError(ErrorType type,int32_t errorCode)787 int32_t DemoCameraDeviceCallback::OnError(ErrorType type, int32_t errorCode)
788 {
789     CAMERA_LOGI("demo test: OnError type : %{public}d, errorMsg : %{public}d", type, errorCode);
790 }
791 
OnResult(uint64_t timestamp,const std::vector<uint8_t> & result)792 int32_t DemoCameraDeviceCallback::OnResult(uint64_t timestamp, const std::vector<uint8_t>& result)
793 {
794     CAMERA_LOGI("%{public}s, enter.", __func__);
795     PrintStabiliInfo(result);
796     PrintFpsInfo(result);
797     DealCameraMetadata(result);
798     return RC_OK;
799 }
800 
OnCameraStatus(const std::string & cameraId,CameraStatus status)801 int32_t DemoCameraHostCallback::OnCameraStatus(const std::string& cameraId, CameraStatus status)
802 {
803     CAMERA_LOGI("%{public}s, enter.", __func__);
804     std::cout << "OnCameraStatus, enter, cameraId = " << cameraId << ", status = " << status << std::endl;
805     return RC_OK;
806 }
807 
OnFlashlightStatus(const std::string & cameraId,FlashlightStatus status)808 int32_t DemoCameraHostCallback::OnFlashlightStatus(const std::string& cameraId, FlashlightStatus status)
809 {
810     CAMERA_LOGI("%{public}s, enter. cameraId = %s, status = %d",
811         __func__, cameraId.c_str(), static_cast<int>(status));
812     return RC_OK;
813 }
814 
OnCameraEvent(const std::string & cameraId,CameraEvent event)815 int32_t DemoCameraHostCallback::OnCameraEvent(const std::string& cameraId, CameraEvent event)
816 {
817     CAMERA_LOGI("%{public}s, enter. cameraId = %s, event = %d",
818         __func__, cameraId.c_str(), static_cast<int>(event));
819     std::cout << "OnCameraEvent, enter, cameraId = " << cameraId << ", event = " << event<< std::endl;
820     return RC_OK;
821 }
822 
OnCaptureStarted(int32_t captureId,const std::vector<int32_t> & streamIds)823 int32_t DemoStreamOperatorCallback::OnCaptureStarted(int32_t captureId, const std::vector<int32_t>& streamIds)
824 {
825     CAMERA_LOGI("%{public}s, enter.", __func__);
826     return RC_OK;
827 }
828 
OnCaptureEnded(int32_t captureId,const std::vector<CaptureEndedInfo> & infos)829 int32_t DemoStreamOperatorCallback::OnCaptureEnded(int32_t captureId, const std::vector<CaptureEndedInfo>& infos)
830 {
831     CAMERA_LOGI("%{public}s, enter.", __func__);
832     return RC_OK;
833 }
834 
DealCameraMetadata(const std::vector<uint8_t> & settings)835 void DemoCameraDeviceCallback::DealCameraMetadata(const std::vector<uint8_t> &settings)
836 {
837     std::shared_ptr<CameraMetadata> result;
838     MetadataUtils::ConvertVecToMetadata(settings, result);
839     if (result == nullptr) {
840         CAMERA_LOGE("TestCameraBase: result is null");
841         return;
842     }
843     common_metadata_header_t *data = result->get();
844     if (data == nullptr) {
845         CAMERA_LOGE("data is null");
846         return;
847     }
848     for (auto it = DATA_BASE.cbegin(); it != DATA_BASE.cend(); it++) {
849         std::string st = {};
850         st = MetadataItemDump(data, *it);
851         CAMERA_LOGI("%{publid}s", st.c_str());
852     }
853 }
854 
OnCaptureError(int32_t captureId,const std::vector<CaptureErrorInfo> & infos)855 int32_t DemoStreamOperatorCallback::OnCaptureError(int32_t captureId, const std::vector<CaptureErrorInfo>& infos)
856 {
857     CAMERA_LOGI("%{public}s, enter.", __func__);
858     return RC_OK;
859 }
860 
OnFrameShutter(int32_t captureId,const std::vector<int32_t> & streamIds,uint64_t timestamp)861 int32_t DemoStreamOperatorCallback::OnFrameShutter(int32_t captureId,
862     const std::vector<int32_t>& streamIds, uint64_t timestamp)
863 {
864     CAMERA_LOGI("%{public}s, enter.", __func__);
865     return RC_OK;
866 }
867 
868 #endif
869