• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 "image_utils.h"
17 
18 #include <sys/stat.h>
19 #include <cerrno>
20 #include <charconv>
21 #include <climits>
22 #include <cmath>
23 #include <cstdint>
24 #include <cstdlib>
25 #include <string>
26 #include <fstream>
27 #include <sstream>
28 #include <chrono>
29 
30 #include "__config"
31 #include "image_log.h"
32 #include "ios"
33 #include "istream"
34 #include "media_errors.h"
35 #include "new"
36 #include "plugin_server.h"
37 #include "singleton.h"
38 #include "string"
39 #include "type_traits"
40 #include "vector"
41 #include "image_trace.h"
42 #include "hitrace_meter.h"
43 #include "image_system_properties.h"
44 #include "image/abs_image_decoder.h"
45 #include "pixel_map.h"
46 #ifdef IOS_PLATFORM
47 #include <sys/syscall.h>
48 #endif
49 #if !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
50 #include "surface_buffer.h"
51 #else
52 #include "refbase.h"
53 #endif
54 
55 #undef LOG_DOMAIN
56 #define LOG_DOMAIN LOG_TAG_DOMAIN_ID_IMAGE
57 
58 #undef LOG_TAG
59 #define LOG_TAG "imageUtils"
60 
61 namespace OHOS {
62 namespace Media {
63 using namespace std;
64 using namespace MultimediaPlugin;
65 
66 constexpr int32_t ALPHA8_BYTES = 1;
67 constexpr int32_t RGB565_BYTES = 2;
68 constexpr int32_t RGB888_BYTES = 3;
69 constexpr int32_t ARGB8888_BYTES = 4;
70 constexpr int32_t RGBA_F16_BYTES = 8;
71 constexpr int32_t NV21_BYTES = 2;  // Each pixel is sorted on 3/2 bytes.
72 constexpr uint8_t MOVE_BITS_8 = 8;
73 constexpr uint8_t MOVE_BITS_16 = 16;
74 constexpr uint8_t MOVE_BITS_24 = 24;
75 constexpr int32_t NV21P010_BYTES = 3;
76 constexpr int32_t ASTC_4X4_BYTES = 1;
77 constexpr int32_t ASTC_4X4_BLOCK = 4;
78 constexpr int32_t ASTC_6X6_BLOCK = 6;
79 constexpr int32_t ASTC_8X8_BLOCK = 8;
80 constexpr int32_t ASTC_BLOCK_SIZE = 16;
81 constexpr int32_t ASTC_HEADER_SIZE = 16;
82 constexpr uint8_t FILL_NUMBER = 3;
83 constexpr uint8_t ALIGN_NUMBER = 4;
84 constexpr float EPSILON = 1e-6;
85 constexpr int MAX_DIMENSION = INT32_MAX >> 2;
86 constexpr int32_t DMA_SIZE = 512 * 512;
87 static bool g_pluginRegistered = false;
88 static const uint8_t NUM_0 = 0;
89 static const uint8_t NUM_1 = 1;
90 static const uint8_t NUM_2 = 2;
91 static const uint8_t NUM_3 = 3;
92 static const uint8_t NUM_4 = 4;
93 static const uint8_t NUM_5 = 5;
94 static const uint8_t NUM_6 = 6;
95 static const uint8_t NUM_7 = 7;
96 static const string FILE_DIR_IN_THE_SANDBOX = "/data/storage/el2/base/files/";
97 
GetFileSize(const string & pathName,size_t & size)98 bool ImageUtils::GetFileSize(const string &pathName, size_t &size)
99 {
100     if (pathName.empty()) {
101         IMAGE_LOGE("[ImageUtil]input parameter exception.");
102         return false;
103     }
104     struct stat statbuf;
105     int ret = stat(pathName.c_str(), &statbuf);
106     if (ret != 0) {
107         IMAGE_LOGE("[ImageUtil]get the file size failed, ret:%{public}d, errno:%{public}d.", ret, errno);
108         return false;
109     }
110     size = statbuf.st_size;
111     return true;
112 }
113 
GetFileSize(const int fd,size_t & size)114 bool ImageUtils::GetFileSize(const int fd, size_t &size)
115 {
116     struct stat statbuf;
117 
118     if (fd < 0) {
119         return false;
120     }
121 
122     int ret = fstat(fd, &statbuf);
123     if (ret != 0) {
124         IMAGE_LOGE("[ImageUtil]get the file size failed, ret:%{public}d, errno:%{public}d.", ret, errno);
125         return false;
126     }
127     size = statbuf.st_size;
128     return true;
129 }
130 
GetInputStreamSize(istream & inputStream,size_t & size)131 bool ImageUtils::GetInputStreamSize(istream &inputStream, size_t &size)
132 {
133     if (inputStream.rdbuf() == nullptr) {
134         IMAGE_LOGE("[ImageUtil]input parameter exception.");
135         return false;
136     }
137     size_t original = inputStream.tellg();
138     inputStream.seekg(0, ios_base::end);
139     size = inputStream.tellg();
140     inputStream.seekg(original);
141     return true;
142 }
143 
GetPixelBytes(const PixelFormat & pixelFormat)144 int32_t ImageUtils::GetPixelBytes(const PixelFormat &pixelFormat)
145 {
146     int pixelBytes = 0;
147     switch (pixelFormat) {
148         case PixelFormat::ARGB_8888:
149         case PixelFormat::BGRA_8888:
150         case PixelFormat::RGBA_8888:
151         case PixelFormat::RGBA_1010102:
152         case PixelFormat::CMYK:
153             pixelBytes = ARGB8888_BYTES;
154             break;
155         case PixelFormat::ALPHA_8:
156             pixelBytes = ALPHA8_BYTES;
157             break;
158         case PixelFormat::RGB_888:
159             pixelBytes = RGB888_BYTES;
160             break;
161         case PixelFormat::RGB_565:
162             pixelBytes = RGB565_BYTES;
163             break;
164         case PixelFormat::RGBA_F16:
165         case PixelFormat::RGBA_U16:
166             pixelBytes = RGBA_F16_BYTES;
167             break;
168         case PixelFormat::NV21:
169         case PixelFormat::NV12:
170             pixelBytes = NV21_BYTES;  // perl pixel 1.5 Bytes but return int so return 2
171             break;
172         case PixelFormat::ASTC_4x4:
173         case PixelFormat::ASTC_6x6:
174         case PixelFormat::ASTC_8x8:
175             pixelBytes = ASTC_4X4_BYTES;
176             break;
177         case PixelFormat::YCBCR_P010:
178         case PixelFormat::YCRCB_P010:
179             pixelBytes = NV21P010_BYTES;
180             break;
181         default:
182             IMAGE_LOGE("[ImageUtil]get pixel bytes failed, pixelFormat:%{public}d.",
183                 static_cast<int32_t>(pixelFormat));
184             break;
185     }
186     return pixelBytes;
187 }
188 
GetRowDataSizeByPixelFormat(const int32_t & width,const PixelFormat & format)189 int32_t ImageUtils::GetRowDataSizeByPixelFormat(const int32_t &width, const PixelFormat &format)
190 {
191     uint64_t uWidth = static_cast<uint64_t>(width);
192     uint64_t pixelBytes = static_cast<uint64_t>(GetPixelBytes(format));
193     uint64_t rowDataSize = 0;
194     switch (format) {
195         case PixelFormat::ALPHA_8:
196             rowDataSize = pixelBytes * ((uWidth + FILL_NUMBER) / ALIGN_NUMBER * ALIGN_NUMBER);
197             break;
198         case PixelFormat::ASTC_4x4:
199             rowDataSize = pixelBytes * (((uWidth + NUM_3) >> NUM_2) << NUM_2);
200             break;
201         case PixelFormat::ASTC_6x6:
202             rowDataSize = pixelBytes * (((uWidth + NUM_5) / NUM_6) * NUM_6);
203             break;
204         case PixelFormat::ASTC_8x8:
205             rowDataSize = pixelBytes * (((uWidth + NUM_7) >> NUM_3) << NUM_3);
206             break;
207         default:
208             rowDataSize = pixelBytes * uWidth;
209     }
210     if (rowDataSize > INT32_MAX) {
211         IMAGE_LOGE("GetRowDataSizeByPixelFormat failed: rowDataSize overflowed");
212         return -1;
213     }
214     return static_cast<int32_t>(rowDataSize);
215 }
216 
RegisterPluginServer()217 uint32_t ImageUtils::RegisterPluginServer()
218 {
219 #ifdef _WIN32
220     vector<string> pluginPaths = { "" };
221 #elif defined(_APPLE)
222     vector<string> pluginPaths = { "./" };
223 #elif defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM)
224     vector<string> pluginPaths = {};
225 #else
226     vector<string> pluginPaths = { "/system/etc/multimediaplugin/image" };
227 #endif
228     PluginServer &pluginServer = DelayedRefSingleton<PluginServer>::GetInstance();
229     uint32_t result = pluginServer.Register(std::move(pluginPaths));
230     if (result != SUCCESS) {
231         IMAGE_LOGE("[ImageUtil]failed to register plugin server, ERRNO: %{public}u.", result);
232     } else {
233         g_pluginRegistered = true;
234         IMAGE_LOGD("[ImageUtil]success to register plugin server");
235     }
236     return result;
237 }
238 
GetPluginServer()239 PluginServer& ImageUtils::GetPluginServer()
240 {
241     if (!g_pluginRegistered) {
242         uint32_t result = RegisterPluginServer();
243         if (result != SUCCESS) {
244             IMAGE_LOGI("[ImageUtil]failed to register plugin server, ERRNO: %{public}u.", result);
245         }
246     }
247     return DelayedRefSingleton<PluginServer>::GetInstance();
248 }
249 
PathToRealPath(const string & path,string & realPath)250 bool ImageUtils::PathToRealPath(const string &path, string &realPath)
251 {
252     if (path.empty()) {
253         IMAGE_LOGE("path is empty!");
254         return false;
255     }
256 
257     if ((path.length() >= PATH_MAX)) {
258         IMAGE_LOGE("path len is error, the len is: [%{public}lu]", static_cast<unsigned long>(path.length()));
259         return false;
260     }
261 
262     char tmpPath[PATH_MAX] = { 0 };
263 
264 #ifdef _WIN32
265     if (_fullpath(tmpPath, path.c_str(), path.length()) == nullptr) {
266         IMAGE_LOGW("path to _fullpath error");
267     }
268 #else
269     if (realpath(path.c_str(), tmpPath) == nullptr) {
270         IMAGE_LOGE("path to realpath is nullptr");
271         return false;
272     }
273 #endif
274 
275     realPath = tmpPath;
276     return true;
277 }
278 
FloatCompareZero(float src)279 bool ImageUtils::FloatCompareZero(float src)
280 {
281     return fabs(src - 0) < EPSILON;
282 }
283 
GetValidAlphaTypeByFormat(const AlphaType & dstType,const PixelFormat & format)284 AlphaType ImageUtils::GetValidAlphaTypeByFormat(const AlphaType &dstType, const PixelFormat &format)
285 {
286     switch (format) {
287         case PixelFormat::RGBA_8888:
288         case PixelFormat::BGRA_8888:
289         case PixelFormat::ARGB_8888:
290         case PixelFormat::RGBA_1010102:
291         case PixelFormat::RGBA_F16: {
292             break;
293         }
294         case PixelFormat::ALPHA_8: {
295             if (dstType != AlphaType::IMAGE_ALPHA_TYPE_PREMUL) {
296                 return AlphaType::IMAGE_ALPHA_TYPE_PREMUL;
297             }
298             break;
299         }
300         case PixelFormat::RGB_888:
301         case PixelFormat::RGB_565: {
302             if (dstType != AlphaType::IMAGE_ALPHA_TYPE_OPAQUE) {
303                 return AlphaType::IMAGE_ALPHA_TYPE_OPAQUE;
304             }
305             break;
306         }
307         case PixelFormat::NV21:
308         case PixelFormat::NV12:
309         case PixelFormat::YCBCR_P010:
310         case PixelFormat::YCRCB_P010: {
311             if (dstType != AlphaType::IMAGE_ALPHA_TYPE_OPAQUE) {
312                 return AlphaType::IMAGE_ALPHA_TYPE_OPAQUE;
313             }
314             break;
315         }
316         case PixelFormat::CMYK:
317         default: {
318             IMAGE_LOGE("GetValidAlphaTypeByFormat unsupport the format(%{public}d).", format);
319             return AlphaType::IMAGE_ALPHA_TYPE_UNKNOWN;
320         }
321     }
322     return dstType;
323 }
324 
GetPixelMapAllocatorType(const Size & size,const PixelFormat & format,bool useDMA)325 AllocatorType ImageUtils::GetPixelMapAllocatorType(const Size &size, const PixelFormat &format, bool useDMA)
326 {
327 #if !defined(_WIN32) && !defined(_APPLE) && !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
328     return useDMA && (format == PixelFormat::RGBA_8888 || (format == PixelFormat::RGBA_1010102 ||
329         format == PixelFormat::YCRCB_P010 ||
330         format == PixelFormat::YCBCR_P010)) &&
331         size.width * size.height >= DMA_SIZE ?
332         AllocatorType::DMA_ALLOC : AllocatorType::SHARE_MEM_ALLOC;
333 #else
334     return AllocatorType::HEAP_ALLOC;
335 #endif
336 }
337 
IsValidImageInfo(const ImageInfo & info)338 bool ImageUtils::IsValidImageInfo(const ImageInfo &info)
339 {
340     if (info.size.width <= 0 || info.size.height <= 0 || info.size.width > MAX_DIMENSION ||
341         info.size.height > MAX_DIMENSION) {
342         IMAGE_LOGE("width(%{public}d) or height(%{public}d) is invalid.", info.size.width, info.size.height);
343         return false;
344     }
345     if (info.pixelFormat == PixelFormat::UNKNOWN || info.alphaType == AlphaType::IMAGE_ALPHA_TYPE_UNKNOWN) {
346         IMAGE_LOGE("check pixelformat and alphatype is invalid.");
347         return false;
348     }
349     return true;
350 }
351 
IsAstc(PixelFormat format)352 bool ImageUtils::IsAstc(PixelFormat format)
353 {
354     return format == PixelFormat::ASTC_4x4 || format == PixelFormat::ASTC_6x6 || format == PixelFormat::ASTC_8x8;
355 }
356 
CheckMulOverflow(int32_t width,int32_t bytesPerPixel)357 bool ImageUtils::CheckMulOverflow(int32_t width, int32_t bytesPerPixel)
358 {
359     if (width == 0 || bytesPerPixel == 0) {
360         IMAGE_LOGE("param is 0");
361         return true;
362     }
363     int32_t rowSize = width * bytesPerPixel;
364     if ((rowSize / width) != bytesPerPixel) {
365         IMAGE_LOGE("width * bytesPerPixel overflow!");
366         return true;
367     }
368     return false;
369 }
370 
CheckMulOverflow(int32_t width,int32_t height,int32_t bytesPerPixel)371 bool ImageUtils::CheckMulOverflow(int32_t width, int32_t height, int32_t bytesPerPixel)
372 {
373     if (width == 0 || height == 0 || bytesPerPixel == 0) {
374         IMAGE_LOGE("param is 0");
375         return true;
376     }
377     int32_t rectSize = width * height;
378     if ((rectSize / width) != height) {
379         IMAGE_LOGE("width * height overflow!");
380         return true;
381     }
382     int32_t bufferSize = rectSize * bytesPerPixel;
383     if ((bufferSize / bytesPerPixel) != rectSize) {
384         IMAGE_LOGE("bytesPerPixel overflow!");
385         return true;
386     }
387     return false;
388 }
389 
ReversePixels(uint8_t * srcPixels,uint8_t * dstPixels,uint32_t byteCount)390 static void ReversePixels(uint8_t* srcPixels, uint8_t* dstPixels, uint32_t byteCount)
391 {
392     if (byteCount % NUM_4 != NUM_0) {
393         IMAGE_LOGE("Pixel count must multiple of 4.");
394         return;
395     }
396     uint8_t *src = srcPixels;
397     uint8_t *dst = dstPixels;
398     for (uint32_t i = NUM_0 ; i < byteCount; i += NUM_4) {
399         // 0-B 1-G 2-R 3-A
400         dst[NUM_0] = src[NUM_3];
401         dst[NUM_1] = src[NUM_2];
402         dst[NUM_2] = src[NUM_1];
403         dst[NUM_3] = src[NUM_0];
404         src += NUM_4;
405         dst += NUM_4;
406     }
407 }
408 
BGRAToARGB(uint8_t * srcPixels,uint8_t * dstPixels,uint32_t byteCount)409 void ImageUtils::BGRAToARGB(uint8_t* srcPixels, uint8_t* dstPixels, uint32_t byteCount)
410 {
411     ImageTrace imageTrace("BGRAToARGB");
412     ReversePixels(srcPixels, dstPixels, byteCount);
413 }
414 
ARGBToBGRA(uint8_t * srcPixels,uint8_t * dstPixels,uint32_t byteCount)415 void ImageUtils::ARGBToBGRA(uint8_t* srcPixels, uint8_t* dstPixels, uint32_t byteCount)
416 {
417     ReversePixels(srcPixels, dstPixels, byteCount);
418 }
419 
SurfaceBuffer_Reference(void * buffer)420 int32_t ImageUtils::SurfaceBuffer_Reference(void* buffer)
421 {
422     if (buffer == nullptr) {
423         IMAGE_LOGE("parameter error, please check input parameter");
424         return ERR_SURFACEBUFFER_REFERENCE_FAILED;
425     }
426     OHOS::RefBase *ref = reinterpret_cast<OHOS::RefBase *>(buffer);
427     ref->IncStrongRef(ref);
428     return SUCCESS;
429 }
430 
SurfaceBuffer_Unreference(void * buffer)431 int32_t ImageUtils::SurfaceBuffer_Unreference(void* buffer)
432 {
433     if (buffer == nullptr) {
434         IMAGE_LOGE("parameter error, please check input parameter");
435         return ERR_SURFACEBUFFER_UNREFERENCE_FAILED;
436     }
437     OHOS::RefBase *ref = reinterpret_cast<OHOS::RefBase *>(buffer);
438     ref->DecStrongRef(ref);
439     return SUCCESS;
440 }
441 
DumpPixelMap(PixelMap * pixelMap,std::string customFileName,uint64_t imageId)442 void ImageUtils::DumpPixelMap(PixelMap* pixelMap, std::string customFileName, uint64_t imageId)
443 {
444     IMAGE_LOGI("ImageUtils::DumpPixelMap start");
445     std::string fileName = FILE_DIR_IN_THE_SANDBOX + GetLocalTime() + customFileName + std::to_string(imageId) +
446         GetPixelMapName(pixelMap) + ".dat";
447     int32_t totalSize = pixelMap->GetRowStride() * pixelMap->GetHeight();
448     if (pixelMap->GetPixelFormat() == PixelFormat::NV12 || pixelMap->GetPixelFormat() == PixelFormat::NV21) {
449 #if !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
450         if (pixelMap->GetAllocatorType() == AllocatorType::DMA_ALLOC) {
451             auto sbBuffer = reinterpret_cast<SurfaceBuffer*>(pixelMap->GetFd());
452             if (!sbBuffer) {
453                 return;
454             }
455             totalSize = static_cast<int32_t>(sbBuffer->GetSize());
456         } else {
457             totalSize = static_cast<int32_t>(pixelMap->GetCapacity());
458         }
459 #else
460         totalSize = static_cast<int32_t>(pixelMap->GetCapacity());
461 #endif
462         IMAGE_LOGI("ImageUtils::DumpPixelMap YUV420 totalSize is %{public}d", totalSize);
463     }
464     if (SUCCESS != SaveDataToFile(fileName, reinterpret_cast<const char*>(pixelMap->GetPixels()), totalSize)) {
465         IMAGE_LOGI("ImageUtils::DumpPixelMap failed");
466         return;
467     }
468     IMAGE_LOGI("ImageUtils::DumpPixelMap success, path = %{public}s", fileName.c_str());
469 }
470 
DumpPixelMapIfDumpEnabled(std::unique_ptr<PixelMap> & pixelMap,uint64_t imageId)471 void ImageUtils::DumpPixelMapIfDumpEnabled(std::unique_ptr<PixelMap>& pixelMap, uint64_t imageId)
472 {
473     if (!ImageSystemProperties::GetDumpImageEnabled()) {
474         return;
475     }
476     if (pixelMap == nullptr) {
477         IMAGE_LOGI("ImageUtils::DumpPixelMapIfDumpEnabled pixelMap is null");
478         return;
479     }
480     DumpPixelMap(pixelMap.get(), "_imageId", imageId);
481 }
482 
DumpPixelMapBeforeEncode(PixelMap & pixelMap)483 void ImageUtils::DumpPixelMapBeforeEncode(PixelMap& pixelMap)
484 {
485     if (!ImageSystemProperties::GetDumpImageEnabled()) {
486         return;
487     }
488     DumpPixelMap(&pixelMap, "_beforeEncode");
489 }
490 
DumpDataIfDumpEnabled(const char * data,const size_t & totalSize,const std::string & fileSuffix,uint64_t imageId)491 void ImageUtils::DumpDataIfDumpEnabled(const char* data, const size_t& totalSize,
492     const std::string& fileSuffix, uint64_t imageId)
493 {
494     if (!ImageSystemProperties::GetDumpImageEnabled()) {
495         return;
496     }
497     std::string fileName = FILE_DIR_IN_THE_SANDBOX + GetLocalTime() + "_imageId" + std::to_string(imageId) +
498         "_data_total" + std::to_string(totalSize) + "." + fileSuffix;
499     if (SUCCESS != SaveDataToFile(fileName, data, totalSize)) {
500         IMAGE_LOGI("ImageUtils::DumpDataIfDumpEnabled failed");
501         return;
502     }
503     IMAGE_LOGI("ImageUtils::DumpDataIfDumpEnabled success, path = %{public}s", fileName.c_str());
504 }
505 
GetNowTimeMilliSeconds()506 uint64_t ImageUtils::GetNowTimeMilliSeconds()
507 {
508     auto now = std::chrono::system_clock::now();
509     return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
510 }
511 
GetNowTimeMicroSeconds()512 uint64_t ImageUtils::GetNowTimeMicroSeconds()
513 {
514     auto now = std::chrono::system_clock::now();
515     return std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count();
516 }
517 
GetCurrentProcessName()518 std::string ImageUtils::GetCurrentProcessName()
519 {
520     std::string processName;
521     std::ifstream cmdlineFile("/proc/self/cmdline");
522     if (cmdlineFile.is_open()) {
523         std::ostringstream oss;
524         oss << cmdlineFile.rdbuf();
525         cmdlineFile.close();
526 
527         //Extrace process name from the command line
528         std::string cmdline = oss.str();
529         size_t pos = cmdline.find_first_of('\0');
530         if (pos != std::string::npos) {
531             processName = cmdline.substr(0, pos);
532         }
533     }
534     return processName;
535 }
536 
SaveDataToFile(const std::string & fileName,const char * data,const size_t & totalSize)537 uint32_t ImageUtils::SaveDataToFile(const std::string& fileName, const char* data, const size_t& totalSize)
538 {
539     std::ofstream outFile(fileName, std::ofstream::out);
540     if (!outFile.is_open()) {
541         IMAGE_LOGI("ImageUtils::SaveDataToFile write error, path=%{public}s", fileName.c_str());
542         return IMAGE_RESULT_SAVE_DATA_TO_FILE_FAILED;
543     }
544     if (data == nullptr) {
545         IMAGE_LOGE("ImageUtils::SaveDataToFile data is nullptr");
546         return IMAGE_RESULT_SAVE_DATA_TO_FILE_FAILED;
547     }
548     outFile.write(data, totalSize);
549     return SUCCESS;
550 }
551 
GetLocalTime()552 std::string ImageUtils::GetLocalTime()
553 {
554     // time string : "year-month-day hour_minute_second.millisecond", ':' is not supported in windows file name
555     auto now = std::chrono::system_clock::now();
556     auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
557     std::time_t t = std::chrono::system_clock::to_time_t(now);
558     std::tm tm = *std::localtime(&t);
559 
560     std::stringstream ss;
561     int millSecondWidth = 3;
562     ss << std::put_time(&tm, "%Y-%m-%d %H_%M_%S.") << std::setfill('0') << std::setw(millSecondWidth) << ms.count();
563     return ss.str();
564 }
565 
GetPixelMapName(PixelMap * pixelMap)566 std::string ImageUtils::GetPixelMapName(PixelMap* pixelMap)
567 {
568     if (!pixelMap) {
569         IMAGE_LOGE("ImageUtils::GetPixelMapName error, pixelMap is null");
570         return "";
571     }
572 #ifdef IOS_PLATFORM
573     std::string pixelMapStr = "_pixelMap_w" + std::to_string(pixelMap->GetWidth()) +
574         "_h" + std::to_string(pixelMap->GetHeight()) +
575         "_rowStride" + std::to_string(pixelMap->GetRowStride()) +
576         "_total" + std::to_string(pixelMap->GetRowStride() * pixelMap->GetHeight()) +
577         "_pid" + std::to_string(getpid()) +
578         "_tid" + std::to_string(syscall(SYS_thread_selfid)) +
579         "_uniqueId" + std::to_string(pixelMap->GetUniqueId());
580 #else
581     std::string yuvInfoStr = "";
582     if (pixelMap->GetPixelFormat() == PixelFormat::NV12 || pixelMap->GetPixelFormat() == PixelFormat::NV21) {
583         YUVDataInfo yuvInfo;
584         pixelMap->GetImageYUVInfo(yuvInfo);
585         yuvInfoStr += "_yWidth" + std::to_string(yuvInfo.yWidth) +
586             "_yHeight" + std::to_string(yuvInfo.yHeight) +
587             "_yStride" + std::to_string(yuvInfo.yStride) +
588             "_yOffset" + std::to_string(yuvInfo.yOffset) +
589             "_uvWidth" + std::to_string(yuvInfo.uvWidth) +
590             "_uvHeight" + std::to_string(yuvInfo.uvHeight) +
591             "_uvStride" + std::to_string(yuvInfo.uvStride) +
592             "_uvOffset" + std::to_string(yuvInfo.uvOffset);
593     }
594     std::string pixelMapStr = "_pixelMap_w" + std::to_string(pixelMap->GetWidth()) +
595         "_h" + std::to_string(pixelMap->GetHeight()) +
596         "_rowStride" + std::to_string(pixelMap->GetRowStride()) +
597         "_pixelFormat" + std::to_string((int32_t)pixelMap->GetPixelFormat()) +
598         yuvInfoStr +
599         "_total" + std::to_string(pixelMap->GetRowStride() * pixelMap->GetHeight()) +
600         "_pid" + std::to_string(getpid()) +
601         "_tid" + std::to_string(gettid()) +
602         "_uniqueId" + std::to_string(pixelMap->GetUniqueId());
603 #endif
604     return pixelMapStr;
605 }
606 
607  // BytesToUint16 function will modify the offset value.
BytesToUint16(uint8_t * bytes,uint32_t & offset,bool isBigEndian)608 uint16_t ImageUtils::BytesToUint16(uint8_t* bytes, uint32_t& offset, bool isBigEndian)
609 {
610     uint16_t data = 0;
611     if (bytes == nullptr) {
612         return data;
613     }
614     if (isBigEndian) {
615         data = (bytes[offset] << MOVE_BITS_8) | bytes[offset + NUM_1];
616     } else {
617         data = (bytes[offset + NUM_1] << MOVE_BITS_8) | bytes[offset];
618     }
619     offset += NUM_2;
620     return data;
621 }
622 
623 // BytesToUint32 function will modify the offset value.
BytesToUint32(uint8_t * bytes,uint32_t & offset,bool isBigEndian)624 uint32_t ImageUtils::BytesToUint32(uint8_t* bytes, uint32_t& offset, bool isBigEndian)
625 {
626     uint32_t data = 0;
627     if (bytes == nullptr) {
628         return data;
629     }
630     if (isBigEndian) {
631         data = (bytes[offset] << MOVE_BITS_24) | (bytes[offset + NUM_1] << MOVE_BITS_16) |
632                 (bytes[offset + NUM_2] << MOVE_BITS_8) | (bytes[offset + NUM_3]);
633     } else {
634         data = (bytes[offset + NUM_3] << MOVE_BITS_24) | (bytes[offset + NUM_2] << MOVE_BITS_16) |
635                 (bytes[offset + NUM_1] << MOVE_BITS_8) | bytes[offset];
636     }
637     offset += NUM_4;
638     return data;
639 }
640 
641 // BytesToInt32 function will modify the offset value.
BytesToInt32(uint8_t * bytes,uint32_t & offset,bool isBigEndian)642 int32_t ImageUtils::BytesToInt32(uint8_t* bytes, uint32_t& offset, bool isBigEndian)
643 {
644     int32_t data = 0;
645     if (bytes == nullptr) {
646         return data;
647     }
648     if (isBigEndian) {
649         data = (bytes[offset] << MOVE_BITS_24) | (bytes[offset + NUM_1] << MOVE_BITS_16) |
650                 (bytes[offset + NUM_2] << MOVE_BITS_8) | (bytes[offset + NUM_3]);
651     } else {
652         data = (bytes[offset + NUM_3] << MOVE_BITS_24) | (bytes[offset + NUM_2] << MOVE_BITS_16) |
653                 (bytes[offset + NUM_1] << MOVE_BITS_8) | bytes[offset];
654     }
655     offset += NUM_4;
656     return data;
657 }
658 
659 // BytesToFloat function will modify the offset value.
BytesToFloat(uint8_t * bytes,uint32_t & offset,bool isBigEndian)660 float ImageUtils::BytesToFloat(uint8_t* bytes, uint32_t& offset, bool isBigEndian)
661 {
662     uint32_t data = BytesToUint32(bytes, offset, isBigEndian);
663     union {
664         uint32_t i;
665         float f;
666     } u;
667     u.i = data;
668     return u.f;
669 }
670 
Uint16ToBytes(uint16_t data,vector<uint8_t> & bytes,uint32_t & offset,bool isBigEndian)671 void ImageUtils::Uint16ToBytes(uint16_t data, vector<uint8_t>& bytes, uint32_t& offset, bool isBigEndian)
672 {
673     uint8_t BYTE_ONE = (data >> MOVE_BITS_8) & 0xFF;
674     uint8_t BYTE_TWO = data & 0xFF;
675     if (isBigEndian) {
676         bytes[offset++] = BYTE_ONE;
677         bytes[offset++] = BYTE_TWO;
678     } else {
679         bytes[offset++] = BYTE_TWO;
680         bytes[offset++] = BYTE_ONE;
681     }
682 }
683 
Uint32ToBytes(uint32_t data,vector<uint8_t> & bytes,uint32_t & offset,bool isBigEndian)684 void ImageUtils::Uint32ToBytes(uint32_t data, vector<uint8_t>& bytes, uint32_t& offset, bool isBigEndian)
685 {
686     uint8_t BYTE_ONE = (data >> MOVE_BITS_24) & 0xFF;
687     uint8_t BYTE_TWO = (data >> MOVE_BITS_16) & 0xFF;
688     uint8_t BYTE_THREE = (data >> MOVE_BITS_8) & 0xFF;
689     uint8_t BYTE_FOUR = data & 0xFF;
690     if (isBigEndian) {
691         bytes[offset++] = BYTE_ONE;
692         bytes[offset++] = BYTE_TWO;
693         bytes[offset++] = BYTE_THREE;
694         bytes[offset++] = BYTE_FOUR;
695     } else {
696         bytes[offset++] = BYTE_FOUR;
697         bytes[offset++] = BYTE_THREE;
698         bytes[offset++] = BYTE_TWO;
699         bytes[offset++] = BYTE_ONE;
700     }
701 }
702 
FloatToBytes(float data,vector<uint8_t> & bytes,uint32_t & offset,bool isBigEndian)703 void ImageUtils::FloatToBytes(float data, vector<uint8_t>& bytes, uint32_t& offset, bool isBigEndian)
704 {
705     union {
706         uint32_t i;
707         float f;
708     } u;
709     u.f = data;
710     Uint32ToBytes(u.i, bytes, offset, isBigEndian);
711 }
712 
Int32ToBytes(int32_t data,vector<uint8_t> & bytes,uint32_t & offset,bool isBigEndian)713 void ImageUtils::Int32ToBytes(int32_t data, vector<uint8_t>& bytes, uint32_t& offset, bool isBigEndian)
714 {
715     union {
716         uint32_t uit;
717         int32_t it;
718     } u;
719     u.it = data;
720     Uint32ToBytes(u.uit, bytes, offset, isBigEndian);
721 }
722 
ArrayToBytes(const uint8_t * data,uint32_t length,vector<uint8_t> & bytes,uint32_t & offset)723 void ImageUtils::ArrayToBytes(const uint8_t* data, uint32_t length, vector<uint8_t>& bytes, uint32_t& offset)
724 {
725     for (uint32_t i = 0; i < length; i++) {
726         bytes[offset++] = data[i] & 0xFF;
727     }
728 }
729 
FlushSurfaceBuffer(PixelMap * pixelMap)730 void ImageUtils::FlushSurfaceBuffer(PixelMap* pixelMap)
731 {
732 #if !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
733     if (!pixelMap || pixelMap->GetAllocatorType() != AllocatorType::DMA_ALLOC) {
734         return;
735     }
736     SurfaceBuffer* surfaceBuffer = static_cast<SurfaceBuffer*>(pixelMap->GetFd());
737     if (surfaceBuffer && (surfaceBuffer->GetUsage() & BUFFER_USAGE_MEM_MMZ_CACHE)) {
738         GSError err = surfaceBuffer->Map();
739         if (err != GSERROR_OK) {
740             IMAGE_LOGE("ImageUtils Map failed, GSError=%{public}d", err);
741             return;
742         }
743         err = surfaceBuffer->FlushCache();
744         if (err != GSERROR_OK) {
745             IMAGE_LOGE("ImageUtils FlushCache failed, GSError=%{public}d", err);
746         }
747     }
748 #else
749     return;
750 #endif
751 }
752 
FlushContextSurfaceBuffer(ImagePlugin::DecodeContext & context)753 void ImageUtils::FlushContextSurfaceBuffer(ImagePlugin::DecodeContext& context)
754 {
755 #if !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
756     if (context.pixelsBuffer.context == nullptr || context.allocatorType != AllocatorType::DMA_ALLOC) {
757         return;
758     }
759     SurfaceBuffer* surfaceBuffer = static_cast<SurfaceBuffer*>(context.pixelsBuffer.context);
760     if (surfaceBuffer && (surfaceBuffer->GetUsage() & BUFFER_USAGE_MEM_MMZ_CACHE)) {
761         GSError err = surfaceBuffer->Map();
762         if (err != GSERROR_OK) {
763             IMAGE_LOGE("ImageUtils Map failed, GSError=%{public}d", err);
764             return;
765         }
766         err = surfaceBuffer->FlushCache();
767         if (err != GSERROR_OK) {
768             IMAGE_LOGE("ImageUtils FlushCache failed, GSError=%{public}d", err);
769         }
770     }
771 #else
772     return;
773 #endif
774 }
775 
InvalidateContextSurfaceBuffer(ImagePlugin::DecodeContext & context)776 void ImageUtils::InvalidateContextSurfaceBuffer(ImagePlugin::DecodeContext& context)
777 {
778 #if !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
779     if (context.pixelsBuffer.context == nullptr || context.allocatorType != AllocatorType::DMA_ALLOC) {
780         return;
781     }
782     SurfaceBuffer* surfaceBuffer = static_cast<SurfaceBuffer*>(context.pixelsBuffer.context);
783     if (surfaceBuffer && (surfaceBuffer->GetUsage() & BUFFER_USAGE_MEM_MMZ_CACHE)) {
784         GSError err = surfaceBuffer->InvalidateCache();
785         if (err != GSERROR_OK) {
786             IMAGE_LOGE("ImageUtils FlushCache failed, GSError=%{public}d", err);
787         }
788     }
789 #else
790     return;
791 #endif
792 }
793 
GetAstcBytesCount(const ImageInfo & imageInfo)794 size_t ImageUtils::GetAstcBytesCount(const ImageInfo& imageInfo)
795 {
796     size_t astcBytesCount = 0;
797     uint32_t blockWidth = 0;
798     uint32_t blockHeight = 0;
799 
800     switch (imageInfo.pixelFormat) {
801         case PixelFormat::ASTC_4x4:
802             blockWidth = ASTC_4X4_BLOCK;
803             blockHeight = ASTC_4X4_BLOCK;
804             break;
805         case PixelFormat::ASTC_6x6:
806             blockWidth = ASTC_6X6_BLOCK;
807             blockHeight = ASTC_6X6_BLOCK;
808             break;
809         case PixelFormat::ASTC_8x8:
810             blockWidth = ASTC_8X8_BLOCK;
811             blockHeight = ASTC_8X8_BLOCK;
812             break;
813         default:
814             IMAGE_LOGE("ImageUtils GetAstcBytesCount failed, format is not supported %{public}d",
815                 imageInfo.pixelFormat);
816             return 0;
817     }
818     if ((blockWidth >= ASTC_4X4_BLOCK) && (blockHeight >= ASTC_4X4_BLOCK)) {
819         astcBytesCount = ((imageInfo.size.width + blockWidth - 1) / blockWidth) *
820             ((imageInfo.size.height + blockHeight - 1) / blockHeight) * ASTC_BLOCK_SIZE + ASTC_HEADER_SIZE;
821     }
822     return astcBytesCount;
823 }
824 
IsAuxiliaryPictureTypeSupported(AuxiliaryPictureType type)825 bool ImageUtils::IsAuxiliaryPictureTypeSupported(AuxiliaryPictureType type)
826 {
827     auto auxTypes = GetAllAuxiliaryPictureType();
828     return (auxTypes.find(type) != auxTypes.end());
829 }
830 
IsAuxiliaryPictureEncoded(AuxiliaryPictureType type)831 bool ImageUtils::IsAuxiliaryPictureEncoded(AuxiliaryPictureType type)
832 {
833     return AuxiliaryPictureType::GAINMAP == type || AuxiliaryPictureType::UNREFOCUS_MAP == type ||
834         AuxiliaryPictureType::FRAGMENT_MAP == type;
835 }
836 
IsMetadataTypeSupported(MetadataType metadataType)837 bool ImageUtils::IsMetadataTypeSupported(MetadataType metadataType)
838 {
839     if (metadataType == MetadataType::EXIF || metadataType == MetadataType::FRAGMENT) {
840         return true;
841     } else {
842         return false;
843     }
844 }
845 
GetAllAuxiliaryPictureType()846 const std::set<AuxiliaryPictureType> ImageUtils::GetAllAuxiliaryPictureType()
847 {
848     static const std::set<AuxiliaryPictureType> auxTypes = {
849         AuxiliaryPictureType::GAINMAP,
850         AuxiliaryPictureType::DEPTH_MAP,
851         AuxiliaryPictureType::UNREFOCUS_MAP,
852         AuxiliaryPictureType::LINEAR_MAP,
853         AuxiliaryPictureType::FRAGMENT_MAP};
854     return auxTypes;
855 }
856 
StrToUint32(const std::string & str,uint32_t & value)857 bool ImageUtils::StrToUint32(const std::string& str, uint32_t& value)
858 {
859     auto [ptr, errCode] = std::from_chars(str.data(), str.data() + str.size(), value);
860     bool ret = errCode == std::errc{} && (ptr == str.data() + str.size());
861     return ret;
862 }
863 
IsInRange(uint32_t value,uint32_t minValue,uint32_t maxValue)864 bool ImageUtils::IsInRange(uint32_t value, uint32_t minValue, uint32_t maxValue)
865 {
866     return (value >= minValue) && (value <= maxValue);
867 }
868 } // namespace Media
869 } // namespace OHOS
870