1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "convert_utils.h"
17 
18 #include <chrono>
19 #include <unistd.h>
20 #include <fcntl.h>
21 
22 #include "pixel_map.h"
23 #include "image_packer.h"
24 #include "media_errors.h"
25 #include "image_log.h"
26 
27 #undef LOG_DOMAIN
28 #define LOG_DOMAIN LOG_TAG_DOMAIN_ID_IMAGE
29 
30 #undef LOG_TAG
31 #define LOG_TAG "CONVERT_UTILS"
32 
33 static const int FOUR_BYTES_PER_PIXEL = 4;
34 static const int NUM_TWO = 2;
35 using namespace OHOS::Media;
36 
ConvertDataToFd(const uint8_t * data,size_t size,std::string encodeFormat)37 int ConvertDataToFd(const uint8_t* data, size_t size, std::string encodeFormat)
38 {
39     if (size < FOUR_BYTES_PER_PIXEL) {
40         return -1;
41     }
42     int picturePixels = size / FOUR_BYTES_PER_PIXEL;
43     InitializationOptions opts = {};
44     if (picturePixels % NUM_TWO == 0) {
45         opts.size.width = picturePixels / NUM_TWO;
46         opts.size.height = NUM_TWO;
47     } else {
48         opts.size.width = picturePixels;
49         opts.size.height = 1;
50     }
51     auto pixelMap = PixelMap::Create(reinterpret_cast<const uint32_t*>(data),
52         static_cast<uint32_t>(picturePixels) * FOUR_BYTES_PER_PIXEL, opts);
53     if (pixelMap == nullptr) {
54         return -1;
55     }
56 
57     std::string pathName = "/data/local/tmp/testFile_" + GetNowTimeStr() + ".dat";
58     IMAGE_LOGI("%{public}s pathName is %{public}s", __func__, pathName.c_str());
59     std::remove(pathName.c_str());
60     int fd = open(pathName.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
61     if (fd < 0) {
62         return -1;
63     }
64     ImagePacker packer;
65     PackOption option;
66     option.format = encodeFormat;
67     packer.StartPacking(fd, option);
68     packer.AddImage(*(pixelMap.get()));
69     uint32_t errorCode = packer.FinalizePacking();
70     if (errorCode != SUCCESS) {
71         return -1;
72     }
73     return fd;
74 }
75 
GetNowTimeStr()76 std::string GetNowTimeStr()
77 {
78     auto now = std::chrono::system_clock::now();
79     auto us = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
80     return std::to_string(us.count());
81 }