• 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;
299     int y;
300     int j;
301     int y0;
302     int u;
303     int v;
304     int r;
305     int g;
306     int b;
307     int32_t location = 0;
308     int xpos = (vinfo_.xres - width) / 2;
309     int ypos = (vinfo_.yres - height) / 2;
310     int yPos = 0; // 0:Pixel initial value
311     int uPos = 1; // 1:Pixel initial value
312     int vPos = 3; // 3:Pixel initial value
313     int yPosIncrement = 2; // 2:yPos increase value
314     int uPosIncrement = 4; // 4:uPos increase value
315     int vPosIncrement = 4; // 4:vPos increase value
316 
317     for (y = ypos; y < (height + ypos); y++) {
318         for (j = 0, x = xpos; j < width; j++, x++) {
319             location = (x + vinfo_.xoffset) * (vinfo_.bits_per_pixel / 8) + // 8: The bytes for each time
320             (y + vinfo_.yoffset) * finfo_.line_length; // add one y number of rows at a time
321 
322             y0 = in[yPos];
323             u = in[uPos] - 128; // 128:display size
324             v = in[vPos] - 128; // 128:display size
325 
326             r = RANGE_LIMIT(y0 + v + ((v * 103) >> 8)); // 103,8:display range
327             g = RANGE_LIMIT(y0 - ((u * 88) >> 8) - ((v * 183) >> 8)); // 88,8,183:display range
328             b = RANGE_LIMIT(y0 + u + ((u * 198) >> 8)); // 198,8:display range
329 
330             fbp[location + 1] = ((r & 0xF8) | (g >> 5)); // 5:display range
331             fbp[location + 0] = (((g & 0x1C) << 3) | (b >> 3)); // 3:display range
332 
333             yPos += yPosIncrement;
334 
335             if (j & 0x01) {
336                 uPos += uPosIncrement;
337                 vPos += vPosIncrement;
338             }
339         }
340 
341         yPos = 0; // 0:Pixel initial value
342         uPos = 1; // 1:Pixel initial value
343         vPos = 3; // 3:Pixel initial value
344         in += istride; // add one y number of rows at a time
345     }
346 }
347 
LcdDrawScreen(unsigned char * displayBuf,unsigned char * addr)348 void TestCameraBase::LcdDrawScreen(unsigned char* displayBuf, unsigned char* addr)
349 {
350     ProcessImage(addr, displayBuf);
351 }
352 
BufferCallback(unsigned char * addr,int choice)353 void TestCameraBase::BufferCallback(unsigned char* addr, int choice)
354 {
355     if (choice == PREVIEW_MODE) {
356         LcdDrawScreen(displayBuf_, addr);
357         return;
358     } else {
359         LcdDrawScreen(displayBuf_, addr);
360         std::cout << "==========[test log] capture start saveYuv......" << std::endl;
361         SaveYUV("capture", reinterpret_cast<unsigned char*>(addr), bufSize_);
362         std::cout << "==========[test log] capture end saveYuv......" << std::endl;
363         return;
364     }
365 }
366 
Init()367 void TestCameraBase::Init()
368 {
369     CAMERA_LOGD("TestCameraBase::Init().");
370     if (cameraHost == nullptr) {
371         constexpr const char *demoServiceName = "camera_service";
372         cameraHost = ICameraHost::Get(demoServiceName, false);
373         CAMERA_LOGI("Camera::CameraHost::CreateCameraHost()");
374         if (cameraHost == nullptr) {
375             CAMERA_LOGE("CreateCameraHost failed.");
376             return;
377         }
378         CAMERA_LOGI("CreateCameraHost success.");
379     }
380 
381     OHOS::sptr<DemoCameraHostCallback> cameraHostCallback = new DemoCameraHostCallback();
382     OHOS::Camera::RetCode ret = cameraHost->SetCallback(cameraHostCallback);
383     if (ret != HDI::Camera::V1_0::NO_ERROR) {
384         CAMERA_LOGE("SetCallback failed.");
385         return;
386     } else {
387         CAMERA_LOGI("SetCallback success.");
388     }
389 
390     if (cameraDevice == nullptr) {
391         cameraHost->GetCameraIds(cameraIds);
392         cameraHost->GetCameraAbility(cameraIds.front(), ability_);
393         MetadataUtils::ConvertVecToMetadata(ability_, ability);
394         const OHOS::sptr<DemoCameraDeviceCallback> callback = new DemoCameraDeviceCallback();
395         rc = (CamRetCode)cameraHost->OpenCamera(cameraIds.front(), callback, cameraDevice);
396         if (rc != HDI::Camera::V1_0::NO_ERROR || cameraDevice == nullptr) {
397             CAMERA_LOGE("OpenCamera failed, rc = %{public}d", rc);
398             return;
399         }
400         CAMERA_LOGI("OpenCamera success.");
401     }
402 }
403 
UsbInit()404 void TestCameraBase::UsbInit()
405 {
406     if (cameraHost == nullptr) {
407         constexpr const char *demoServiceName = "camera_service";
408         cameraHost = ICameraHost::Get(demoServiceName, false);
409         if (cameraHost == nullptr) {
410             std::cout << "==========[test log] CreateCameraHost failed." << std::endl;
411             return;
412         }
413         std::cout << "==========[test log] CreateCameraHost success." << std::endl;
414     }
415 
416     OHOS::sptr<DemoCameraHostCallback> cameraHostCallback = new DemoCameraHostCallback();
417     OHOS::Camera::RetCode ret = cameraHost->SetCallback(cameraHostCallback);
418     if (ret != HDI::Camera::V1_0::NO_ERROR) {
419         std::cout << "==========[test log] SetCallback failed." << std::endl;
420         return;
421     } else {
422         std::cout << "==========[test log] SetCallback success." << std::endl;
423     }
424 }
425 
GetCameraAbility()426 std::shared_ptr<CameraAbility> TestCameraBase::GetCameraAbility()
427 {
428     if (cameraDevice == nullptr) {
429         OHOS::Camera::RetCode ret = cameraHost->GetCameraIds(cameraIds);
430         if (ret != HDI::Camera::V1_0::NO_ERROR) {
431             std::cout << "==========[test log]GetCameraIds failed." << std::endl;
432             return ability;
433         } else {
434             std::cout << "==========[test log]GetCameraIds success." << std::endl;
435         }
436         if (cameraIds.size() == 0) {
437             std::cout << "==========[test log]camera device list is empty." << std::endl;
438             return ability;
439         }
440         if (cameraIds.size() > 0) {
441             ret = cameraHost->GetCameraAbility(cameraIds.back(), ability_);
442             if (ret != HDI::Camera::V1_0::NO_ERROR) {
443                 std::cout << "==========[test log]GetCameraAbility failed, rc = " << rc << std::endl;
444             }
445             MetadataUtils::ConvertVecToMetadata(ability_, ability);
446         }
447     }
448     return ability;
449 }
450 
OpenUsbCamera()451 void TestCameraBase::OpenUsbCamera()
452 {
453     if (cameraDevice == nullptr) {
454         cameraHost->GetCameraIds(cameraIds);
455         if (cameraIds.size() > 0) {
456             cameraHost->GetCameraAbility(cameraIds.back(), ability_);
457             MetadataUtils::ConvertVecToMetadata(ability_, ability);
458             const OHOS::sptr<DemoCameraDeviceCallback> callback = new DemoCameraDeviceCallback();
459             rc = (CamRetCode)cameraHost->OpenCamera(cameraIds.back(), callback, cameraDevice);
460             if (rc != HDI::Camera::V1_0::NO_ERROR || cameraDevice == nullptr) {
461                 std::cout << "OpenCamera failed, rc = " << rc << std::endl;
462                 return;
463             }
464             std::cout << "OpenCamera success." << std::endl;
465         } else {
466             std::cout << "No usb camera plugged in" << std::endl;
467         }
468     }
469 }
470 
SelectOpenCamera(std::string cameraId)471 CamRetCode TestCameraBase::SelectOpenCamera(std::string cameraId)
472 {
473     cameraHost->GetCameraAbility(cameraId, ability_);
474     MetadataUtils::ConvertVecToMetadata(ability_, ability);
475     const OHOS::sptr<DemoCameraDeviceCallback> callback = new DemoCameraDeviceCallback();
476     rc = (CamRetCode)cameraHost->OpenCamera(cameraId, callback, cameraDevice);
477     if (rc != HDI::Camera::V1_0::NO_ERROR || cameraDevice == nullptr) {
478         std::cout << "OpenCamera failed, rc = " << rc << std::endl;
479         return rc;
480     }
481     std::cout << "OpenCamera success." << std::endl;
482     return rc;
483 }
484 
Close()485 void TestCameraBase::Close()
486 {
487     CAMERA_LOGD("cameraDevice->Close().");
488     if (cameraDevice != nullptr) {
489         cameraDevice->Close();
490         cameraDevice = nullptr;
491     }
492 }
493 
OpenCamera()494 void TestCameraBase::OpenCamera()
495 {
496     if (cameraDevice == nullptr) {
497         cameraHost->GetCameraIds(cameraIds);
498         const OHOS::sptr<OHOS::Camera::CameraDeviceCallback> callback = new CameraDeviceCallback();
499         rc = (CamRetCode)cameraHost->OpenCamera(cameraIds.front(), callback, cameraDevice);
500         if (rc != HDI::Camera::V1_0::NO_ERROR || cameraDevice == nullptr) {
501             std::cout << "==========[test log] OpenCamera failed, rc = " << rc << std::endl;
502             return;
503         }
504         std::cout << "==========[test log]  OpenCamera success." << std::endl;
505     }
506 }
507 
DefaultInfosPreview()508 void TestCameraBase::DefaultInfosPreview()
509 {
510     if (streamCustomerPreview_ == nullptr) {
511         streamCustomerPreview_ = std::make_shared<StreamCustomer>();
512     }
513     streamInfoPre.streamId_ = STREAM_ID_PREVIEW;
514     streamInfoPre.width_ = PREVIEW_WIDTH; // 640:picture width
515     streamInfoPre.height_ = PREVIEW_HEIGHT; // 480:picture height
516     streamInfoPre.format_ = PIXEL_FMT_RGBA_8888;
517     streamInfoPre.dataspace_ = 8; // 8:picture dataspace
518     streamInfoPre.intent_ = PREVIEW;
519     streamInfoPre.tunneledMode_ = 5; // 5:tunnel mode
520     streamInfoPre.bufferQueue_ = new BufferProducerSequenceable(streamCustomerPreview_->CreateProducer());
521     ASSERT_NE(streamInfoPre.bufferQueue_, nullptr);
522     streamInfoPre.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
523     std::cout << "preview success1." << std::endl;
524     std::vector<StreamInfo>().swap(streamInfos);
525     streamInfos.push_back(streamInfoPre);
526 }
527 
DefaultInfosCapture()528 void TestCameraBase::DefaultInfosCapture()
529 {
530     if (streamCustomerCapture_ == nullptr) {
531         streamCustomerCapture_ = std::make_shared<StreamCustomer>();
532     }
533     streamInfoCapture.streamId_ = STREAM_ID_CAPTURE;
534     streamInfoCapture.width_ = CAPTURE_WIDTH; // 1280:picture width
535     streamInfoCapture.height_ = CAPTURE_HEIGHT; // 960:picture height
536     streamInfoCapture.format_ = PIXEL_FMT_RGBA_8888;
537     streamInfoCapture.dataspace_ = 8; // 8:picture dataspace
538     streamInfoCapture.intent_ = STILL_CAPTURE;
539     streamInfoCapture.encodeType_ = ENCODE_TYPE_JPEG;
540     streamInfoCapture.tunneledMode_ = 5; // 5:tunnel mode
541     streamInfoCapture.bufferQueue_ = new BufferProducerSequenceable(streamCustomerCapture_->CreateProducer());
542     ASSERT_NE(streamInfoCapture.bufferQueue_, nullptr);
543     streamInfoCapture.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
544     std::cout << "capture success1." << std::endl;
545     streamInfos.push_back(streamInfoCapture);
546 }
547 
CalTime(struct timeval start,struct timeval end)548 float TestCameraBase::CalTime(struct timeval start, struct timeval end)
549 {
550     float timeUse = 0;
551     timeUse = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // 1000000:time
552     return timeUse;
553 }
554 
AchieveStreamOperator()555 void TestCameraBase::AchieveStreamOperator()
556 {
557     // Create and get streamOperator information
558     OHOS::sptr<DemoStreamOperatorCallback> streamOperatorCallback_ = new DemoStreamOperatorCallback();
559     if (cameraDevice == nullptr) {
560         CAMERA_LOGI("cameraDevice is nullptr");
561         return;
562     }
563     rc = (CamRetCode)cameraDevice->GetStreamOperator(streamOperatorCallback_, streamOperator);
564     EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
565     if (rc == HDI::Camera::V1_0::NO_ERROR) {
566         CAMERA_LOGI("AchieveStreamOperator success.");
567     } else {
568         CAMERA_LOGE("AchieveStreamOperator fail, rc = %{public}d", rc);
569     }
570 }
571 
StartStream(std::vector<StreamIntent> intents)572 void TestCameraBase::StartStream(std::vector<StreamIntent> intents)
573 {
574     for (auto& intent : intents) {
575         if (intent == PREVIEW) {
576             if (streamCustomerPreview_ == nullptr) {
577                 streamCustomerPreview_ = std::make_shared<StreamCustomer>();
578             }
579             streamInfoPre.streamId_ = STREAM_ID_PREVIEW;
580             streamInfoPre.width_ = PREVIEW_WIDTH; // 640:picture width
581             streamInfoPre.height_ = PREVIEW_HEIGHT; // 480:picture height
582             streamInfoPre.format_ = PIXEL_FMT_RGBA_8888;
583             streamInfoPre.dataspace_ = 8; // 8:picture dataspace
584             streamInfoPre.intent_ = intent;
585             streamInfoPre.tunneledMode_ = 5; // 5:tunnel mode
586             streamInfoPre.bufferQueue_ = new BufferProducerSequenceable(streamCustomerPreview_->CreateProducer());
587             ASSERT_NE(streamInfoPre.bufferQueue_, nullptr);
588             streamInfoPre.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
589             CAMERA_LOGD("preview success.");
590             std::vector<StreamInfo>().swap(streamInfos);
591             streamInfos.push_back(streamInfoPre);
592         } else if (intent == VIDEO) {
593             if (streamCustomerVideo_ == nullptr) {
594                 streamCustomerVideo_ = std::make_shared<StreamCustomer>();
595             }
596             streamInfoVideo.streamId_ = STREAM_ID_VIDEO;
597             streamInfoVideo.width_ = VIDEO_WIDTH; // 1280:picture width
598             streamInfoVideo.height_ = VIDEO_HEIGHT; // 960:picture height
599             streamInfoVideo.format_ = PIXEL_FMT_RGBA_8888;
600             streamInfoVideo.dataspace_ = 8; // 8:picture dataspace
601             streamInfoVideo.intent_ = intent;
602             streamInfoVideo.encodeType_ = ENCODE_TYPE_H264;
603             streamInfoVideo.tunneledMode_ = 5; // 5:tunnel mode
604             streamInfoVideo.bufferQueue_ = new BufferProducerSequenceable(streamCustomerVideo_->CreateProducer());
605             ASSERT_NE(streamInfoVideo.bufferQueue_, nullptr);
606             streamInfoVideo.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
607             CAMERA_LOGD("video success.");
608             std::vector<StreamInfo>().swap(streamInfos);
609             streamInfos.push_back(streamInfoVideo);
610         } else if (intent == STILL_CAPTURE) {
611             if (streamCustomerCapture_ == nullptr) {
612                 streamCustomerCapture_ = std::make_shared<StreamCustomer>();
613             }
614             streamInfoCapture.streamId_ = STREAM_ID_CAPTURE;
615             streamInfoCapture.width_ = CAPTURE_WIDTH; // 1280:picture width
616             streamInfoCapture.height_ = CAPTURE_HEIGHT; // 960:picture height
617             streamInfoCapture.format_ = PIXEL_FMT_RGBA_8888;
618             streamInfoCapture.dataspace_ = 8; // 8:picture dataspace
619             streamInfoCapture.intent_ = intent;
620             streamInfoCapture.encodeType_ = ENCODE_TYPE_JPEG;
621             streamInfoCapture.tunneledMode_ = 5; // 5:tunnel mode
622             streamInfoCapture.bufferQueue_ = new BufferProducerSequenceable(streamCustomerCapture_->CreateProducer());
623             ASSERT_NE(streamInfoCapture.bufferQueue_, nullptr);
624             streamInfoCapture.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
625             CAMERA_LOGD("capture success.");
626             std::vector<StreamInfo>().swap(streamInfos);
627             streamInfos.push_back(streamInfoCapture);
628         } else if (intent == ANALYZE) {
629             if (streamCustomerAnalyze_ == nullptr) {
630                 streamCustomerAnalyze_ = std::make_shared<StreamCustomer>();
631             }
632             streamInfoAnalyze.streamId_ = STREAM_ID_ANALYZE;
633             streamInfoAnalyze.width_ = ANALYZE_WIDTH; // 640:picture width
634             streamInfoAnalyze.height_ = ANALYZE_HEIGHT; // 480:picture height
635             streamInfoAnalyze.format_ = PIXEL_FMT_RGBA_8888;
636             streamInfoAnalyze.dataspace_ = 8; // 8:picture dataspace
637             streamInfoAnalyze.intent_ = intent;
638             streamInfoAnalyze.tunneledMode_ = 5; // 5:tunnel mode
639             streamInfoAnalyze.bufferQueue_ = new BufferProducerSequenceable(streamCustomerAnalyze_->CreateProducer());
640             ASSERT_NE(streamInfoAnalyze.bufferQueue_, nullptr);
641             streamInfoAnalyze.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size
642             CAMERA_LOGD("analyze success.");
643             std::vector<StreamInfo>().swap(streamInfos);
644             streamInfos.push_back(streamInfoAnalyze);
645         }
646         rc = (CamRetCode)streamOperator->CreateStreams(streamInfos);
647         EXPECT_EQ(false, rc != HDI::Camera::V1_0::NO_ERROR);
648         if (rc == HDI::Camera::V1_0::NO_ERROR) {
649             CAMERA_LOGI("CreateStreams success.");
650         } else {
651             CAMERA_LOGE("CreateStreams fail, rc = %{public}d", rc);
652         }
653 
654         rc = (CamRetCode)streamOperator->CommitStreams(NORMAL, ability_);
655         EXPECT_EQ(false, rc != HDI::Camera::V1_0::NO_ERROR);
656         if (rc == HDI::Camera::V1_0::NO_ERROR) {
657             CAMERA_LOGI("CommitStreams success.");
658         } else {
659             CAMERA_LOGE("CommitStreams fail, rc = %{public}d", rc);
660         }
661     }
662 }
663 
StartCapture(int streamId,int captureId,bool shutterCallback,bool isStreaming)664 void TestCameraBase::StartCapture(int streamId, int captureId, bool shutterCallback, bool isStreaming)
665 {
666     // Get preview
667     captureInfo.streamIds_ = {streamId};
668     captureInfo.captureSetting_ = ability_;
669     captureInfo.enableShutterCallback_ = shutterCallback;
670     rc = (CamRetCode)streamOperator->Capture(captureId, captureInfo, isStreaming);
671     EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
672     if (rc == HDI::Camera::V1_0::NO_ERROR) {
673         CAMERA_LOGI("check Capture: Capture success, captureId = %{public}d", captureId);
674     } else {
675         CAMERA_LOGE("check Capture: Capture fail, rc = %{public}d, captureId = %{public}d", rc, captureId);
676     }
677     if (captureId == CAPTURE_ID_PREVIEW) {
678         streamCustomerPreview_->ReceiveFrameOn(nullptr);
679     } else if (captureId == CAPTURE_ID_CAPTURE) {
680         streamCustomerCapture_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
681             StoreImage(addr, size);
682         });
683     } else if (captureId == CAPTURE_ID_VIDEO) {
684         OpenVideoFile();
685         streamCustomerVideo_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
686             StoreVideo(addr, size);
687         });
688     } else if (captureId == CAPTURE_ID_ANALYZE) {
689         streamCustomerAnalyze_->ReceiveFrameOn([this](const unsigned char *addr, const uint32_t size) {
690             PrintFaceDetectInfo(addr, size);
691         });
692     }
693     sleep(2); // 2:sleep two second
694 }
695 
StopStream(std::vector<int> & captureIds,std::vector<int> & streamIds)696 void TestCameraBase::StopStream(std::vector<int>& captureIds, std::vector<int>& streamIds)
697 {
698     constexpr uint32_t timeForWaitCancelCapture = 2;
699     sleep(timeForWaitCancelCapture);
700     if (captureIds.size() > 0) {
701         for (const auto &captureId : captureIds) {
702             if (captureId == CAPTURE_ID_PREVIEW) {
703                 streamCustomerPreview_->ReceiveFrameOff();
704             } else if (captureId == CAPTURE_ID_CAPTURE) {
705                 streamCustomerCapture_->ReceiveFrameOff();
706             } else if (captureId == CAPTURE_ID_VIDEO) {
707                 streamCustomerVideo_->ReceiveFrameOff();
708                 sleep(1);
709                 CloseFd();
710             } else if (captureId == CAPTURE_ID_ANALYZE) {
711                 streamCustomerAnalyze_->ReceiveFrameOff();
712             }
713         }
714         for (const auto &captureId : captureIds) {
715             CAMERA_LOGI("check Capture: CancelCapture success, captureId = %{public}d", captureId);
716             rc = (CamRetCode)streamOperator->CancelCapture(captureId);
717             sleep(timeForWaitCancelCapture);
718             EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
719             if (rc == HDI::Camera::V1_0::NO_ERROR) {
720                 CAMERA_LOGI("check Capture: CancelCapture success, captureId = %{public}d", captureId);
721             } else {
722                 CAMERA_LOGE("check Capture: CancelCapture fail, rc = %{public}d, captureId = %{public}d",
723                     rc, captureId);
724             }
725         }
726     }
727     sleep(1);
728     if (streamIds.size() > 0) {
729         // release stream
730         rc = (CamRetCode)streamOperator->ReleaseStreams(streamIds);
731         EXPECT_EQ(true, rc == HDI::Camera::V1_0::NO_ERROR);
732         if (rc == HDI::Camera::V1_0::NO_ERROR) {
733             CAMERA_LOGI("check Capture: ReleaseStreams success.");
734         } else {
735             CAMERA_LOGE("check Capture: ReleaseStreams fail, rc = %{public}d, streamIds = %{public}d",
736                 rc, streamIds.front());
737         }
738     }
739 }
740 
PrintStabiliInfo(const std::vector<uint8_t> & result)741 void DemoCameraDeviceCallback::PrintStabiliInfo(const std::vector<uint8_t>& result)
742 {
743     std::shared_ptr<CameraMetadata> metaData;
744     MetadataUtils::ConvertVecToMetadata(result, metaData);
745 
746     if (metaData == nullptr) {
747         CAMERA_LOGE("TestCameraBase: result is null");
748         return;
749     }
750     common_metadata_header_t* data = metaData->get();
751     if (data == nullptr) {
752         CAMERA_LOGE("TestCameraBase: data is null");
753         return;
754     }
755     uint8_t videoStabiliMode;
756     camera_metadata_item_t entry;
757     int ret = FindCameraMetadataItem(data, OHOS_CONTROL_VIDEO_STABILIZATION_MODE, &entry);
758     if (ret != 0) {
759         CAMERA_LOGE("demo test: get OHOS_CONTROL_EXPOSURE_MODE error");
760         return;
761     }
762     videoStabiliMode = *(entry.data.u8);
763     CAMERA_LOGI("videoStabiliMode: %{public}d", static_cast<int>(videoStabiliMode));
764 }
765 
PrintFpsInfo(const std::vector<uint8_t> & result)766 void DemoCameraDeviceCallback::PrintFpsInfo(const std::vector<uint8_t>& result)
767 {
768     std::shared_ptr<CameraMetadata> metaData;
769     MetadataUtils::ConvertVecToMetadata(result, metaData);
770 
771     if (metaData == nullptr) {
772         CAMERA_LOGE("TestCameraBase: result is null");
773         return;
774     }
775     common_metadata_header_t* data = metaData->get();
776     if (data == nullptr) {
777         CAMERA_LOGE("TestCameraBase: data is null");
778         return;
779     }
780     std::vector<int32_t> fpsRange;
781     camera_metadata_item_t entry;
782     int ret = FindCameraMetadataItem(data, OHOS_CONTROL_FPS_RANGES, &entry);
783     if (ret != 0) {
784         CAMERA_LOGE("demo test: get OHOS_CONTROL_EXPOSURE_MODE error");
785         return;
786     }
787 
788     for (int i = 0; i < entry.count; i++) {
789         fpsRange.push_back(*(entry.data.i32 + i));
790     }
791     CAMERA_LOGI("PrintFpsInfo fpsRange: [%{public}d, %{public}d]", fpsRange[0], fpsRange[1]);
792 }
793 
794 #ifndef CAMERA_BUILT_ON_OHOS_LITE
OnError(ErrorType type,int32_t errorCode)795 int32_t DemoCameraDeviceCallback::OnError(ErrorType type, int32_t errorCode)
796 {
797     CAMERA_LOGI("demo test: OnError type : %{public}d, errorMsg : %{public}d", type, errorCode);
798 }
799 
OnResult(uint64_t timestamp,const std::vector<uint8_t> & result)800 int32_t DemoCameraDeviceCallback::OnResult(uint64_t timestamp, const std::vector<uint8_t>& result)
801 {
802     CAMERA_LOGI("%{public}s, enter.", __func__);
803     PrintStabiliInfo(result);
804     PrintFpsInfo(result);
805     DealCameraMetadata(result);
806     return RC_OK;
807 }
808 
OnCameraStatus(const std::string & cameraId,CameraStatus status)809 int32_t DemoCameraHostCallback::OnCameraStatus(const std::string& cameraId, CameraStatus status)
810 {
811     CAMERA_LOGI("%{public}s, enter.", __func__);
812     std::cout << "OnCameraStatus, enter, cameraId = " << cameraId << ", status = " << status << std::endl;
813     return RC_OK;
814 }
815 
OnFlashlightStatus(const std::string & cameraId,FlashlightStatus status)816 int32_t DemoCameraHostCallback::OnFlashlightStatus(const std::string& cameraId, FlashlightStatus status)
817 {
818     CAMERA_LOGI("%{public}s, enter. cameraId = %s, status = %d",
819         __func__, cameraId.c_str(), static_cast<int>(status));
820     return RC_OK;
821 }
822 
OnCameraEvent(const std::string & cameraId,CameraEvent event)823 int32_t DemoCameraHostCallback::OnCameraEvent(const std::string& cameraId, CameraEvent event)
824 {
825     CAMERA_LOGI("%{public}s, enter. cameraId = %s, event = %d",
826         __func__, cameraId.c_str(), static_cast<int>(event));
827     std::cout << "OnCameraEvent, enter, cameraId = " << cameraId << ", event = " << event<< std::endl;
828     return RC_OK;
829 }
830 
OnCaptureStarted(int32_t captureId,const std::vector<int32_t> & streamIds)831 int32_t DemoStreamOperatorCallback::OnCaptureStarted(int32_t captureId, const std::vector<int32_t>& streamIds)
832 {
833     CAMERA_LOGI("%{public}s, enter.", __func__);
834     return RC_OK;
835 }
836 
OnCaptureEnded(int32_t captureId,const std::vector<CaptureEndedInfo> & infos)837 int32_t DemoStreamOperatorCallback::OnCaptureEnded(int32_t captureId, const std::vector<CaptureEndedInfo>& infos)
838 {
839     CAMERA_LOGI("%{public}s, enter.", __func__);
840     return RC_OK;
841 }
842 
DealCameraMetadata(const std::vector<uint8_t> & settings)843 void DemoCameraDeviceCallback::DealCameraMetadata(const std::vector<uint8_t> &settings)
844 {
845     std::shared_ptr<CameraMetadata> result;
846     MetadataUtils::ConvertVecToMetadata(settings, result);
847     if (result == nullptr) {
848         CAMERA_LOGE("TestCameraBase: result is null");
849         return;
850     }
851     common_metadata_header_t *data = result->get();
852     if (data == nullptr) {
853         CAMERA_LOGE("data is null");
854         return;
855     }
856     for (auto it = DATA_BASE.cbegin(); it != DATA_BASE.cend(); it++) {
857         std::string st = {};
858         st = MetadataItemDump(data, *it);
859         CAMERA_LOGI("%{publid}s", st.c_str());
860     }
861 }
862 
OnCaptureError(int32_t captureId,const std::vector<CaptureErrorInfo> & infos)863 int32_t DemoStreamOperatorCallback::OnCaptureError(int32_t captureId, const std::vector<CaptureErrorInfo>& infos)
864 {
865     CAMERA_LOGI("%{public}s, enter.", __func__);
866     return RC_OK;
867 }
868 
OnFrameShutter(int32_t captureId,const std::vector<int32_t> & streamIds,uint64_t timestamp)869 int32_t DemoStreamOperatorCallback::OnFrameShutter(int32_t captureId,
870     const std::vector<int32_t>& streamIds, uint64_t timestamp)
871 {
872     CAMERA_LOGI("%{public}s, enter.", __func__);
873     return RC_OK;
874 }
875 
876 #endif
877