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 "post_proc.h"
17 
18 #include <unistd.h>
19 
20 #include "basic_transformer.h"
21 #include "image_log.h"
22 #include "image_system_properties.h"
23 #include "image_trace.h"
24 #include "image_utils.h"
25 #include "media_errors.h"
26 #include "memory_manager.h"
27 #include "pixel_convert_adapter.h"
28 #ifndef _WIN32
29 #include "securec.h"
30 #else
31 #include "memory.h"
32 #endif
33 
34 #if !defined(_WIN32) && !defined(_APPLE) && !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
35 #include <sys/mman.h>
36 #include "ashmem.h"
37 #include "surface_buffer.h"
38 #include "vpe_utils.h"
39 
40 #ifdef __cplusplus
41 extern "C" {
42 #endif
43 #include "libswscale/swscale.h"
44 #ifdef __cplusplus
45 };
46 #endif
47 #endif
48 
49 #undef LOG_DOMAIN
50 #define LOG_DOMAIN LOG_TAG_DOMAIN_ID_IMAGE
51 
52 #undef LOG_TAG
53 #define LOG_TAG "PostProc"
54 
55 namespace OHOS {
56 namespace Media {
57 using namespace std;
58 constexpr uint32_t NEED_NEXT = 1;
59 constexpr float EPSILON = 1e-6;
60 constexpr uint8_t HALF = 2;
61 constexpr float HALF_F = 2;
62 constexpr int FFMPEG_NUM = 8;
63 constexpr int SLR_CACHE_CAPACITY = 256;
64 
65 #if !defined(_WIN32) && !defined(_APPLE) && !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
66 static const map<PixelFormat, AVPixelFormat> PIXEL_FORMAT_MAP = {
67     { PixelFormat::ALPHA_8, AVPixelFormat::AV_PIX_FMT_GRAY8 },
68     { PixelFormat::RGB_565, AVPixelFormat::AV_PIX_FMT_RGB565BE },
69     { PixelFormat::RGB_888, AVPixelFormat::AV_PIX_FMT_RGB24 },
70     { PixelFormat::RGBA_8888, AVPixelFormat::AV_PIX_FMT_RGBA },
71     { PixelFormat::ARGB_8888, AVPixelFormat::AV_PIX_FMT_ARGB },
72     { PixelFormat::BGRA_8888, AVPixelFormat::AV_PIX_FMT_BGRA },
73     { PixelFormat::RGBA_F16, AVPixelFormat::AV_PIX_FMT_RGBA64BE },
74 };
75 #endif
76 
DecodePostProc(const DecodeOptions &opts, PixelMap &pixelMap, FinalOutputStep finalOutputStep)77 uint32_t PostProc::DecodePostProc(const DecodeOptions &opts, PixelMap &pixelMap, FinalOutputStep finalOutputStep)
78 {
79     ImageInfo srcImageInfo;
80     pixelMap.GetImageInfo(srcImageInfo);
81     ImageInfo dstImageInfo;
82     GetDstImageInfo(opts, pixelMap, srcImageInfo, dstImageInfo);
83     uint32_t errorCode = ConvertProc(opts.CropRect, dstImageInfo, pixelMap, srcImageInfo);
84     if (errorCode != SUCCESS) {
85         IMAGE_LOGE("[PostProc]crop pixel map failed, errcode:%{public}u", errorCode);
86         return errorCode;
87     }
88     decodeOpts_.allocatorType = opts.allocatorType;
89     bool isNeedRotate = !ImageUtils::FloatCompareZero(opts.rotateDegrees);
90     if (isNeedRotate) {
91         if (!RotatePixelMap(opts.rotateDegrees, pixelMap)) {
92             IMAGE_LOGE("[PostProc]rotate:transform pixel map failed");
93             return ERR_IMAGE_TRANSFORM;
94         }
95     }
96     decodeOpts_.allocatorType = opts.allocatorType;
97     if (opts.desiredSize.height > 0 && opts.desiredSize.width > 0) {
98         if (!ScalePixelMap(opts.desiredSize, pixelMap)) {
99             IMAGE_LOGE("[PostProc]scale:transform pixel map failed");
100             return ERR_IMAGE_TRANSFORM;
101         }
102     } else {
103         ImageInfo info;
104         pixelMap.GetImageInfo(info);
105         if ((finalOutputStep == FinalOutputStep::DENSITY_CHANGE) && (info.baseDensity != 0)) {
106             int targetWidth = (pixelMap.GetWidth() * opts.fitDensity + (info.baseDensity >> 1)) / info.baseDensity;
107             int targetHeight = (pixelMap.GetHeight() * opts.fitDensity + (info.baseDensity >> 1)) / info.baseDensity;
108             Size size;
109             size.height = targetHeight;
110             size.width = targetWidth;
111             if (!ScalePixelMap(size, pixelMap)) {
112                 IMAGE_LOGE("[PostProc]density scale:transform pixel map failed");
113                 return ERR_IMAGE_TRANSFORM;
114             }
115             info.baseDensity = opts.fitDensity;
116             pixelMap.SetImageInfo(info, true);
117         }
118     }
119     return SUCCESS;
120 }
121 
GetDstImageInfo(const DecodeOptions &opts, PixelMap &pixelMap, ImageInfo srcImageInfo, ImageInfo &dstImageInfo)122 void PostProc::GetDstImageInfo(const DecodeOptions &opts, PixelMap &pixelMap,
123                                ImageInfo srcImageInfo, ImageInfo &dstImageInfo)
124 {
125     dstImageInfo.size = opts.desiredSize;
126     dstImageInfo.pixelFormat = opts.desiredPixelFormat;
127     dstImageInfo.baseDensity = srcImageInfo.baseDensity;
128     decodeOpts_ = opts;
129     if (opts.desiredPixelFormat == PixelFormat::UNKNOWN) {
130         if (opts.preference == MemoryUsagePreference::LOW_RAM &&
131             srcImageInfo.alphaType == AlphaType::IMAGE_ALPHA_TYPE_OPAQUE) {
132             dstImageInfo.pixelFormat = PixelFormat::RGB_565;
133         } else {
134             dstImageInfo.pixelFormat = PixelFormat::RGBA_8888;
135         }
136     }
137     // decode use, this value may be changed by real pixelFormat
138     if (pixelMap.GetAlphaType() == AlphaType::IMAGE_ALPHA_TYPE_UNPREMUL) {
139         dstImageInfo.alphaType = AlphaType::IMAGE_ALPHA_TYPE_PREMUL;
140     } else {
141         dstImageInfo.alphaType = pixelMap.GetAlphaType();
142     }
143 }
144 
CenterScale(const Size &size, PixelMap &pixelMap)145 bool PostProc::CenterScale(const Size &size, PixelMap &pixelMap)
146 {
147     int32_t srcWidth = pixelMap.GetWidth();
148     int32_t srcHeight = pixelMap.GetHeight();
149     int32_t targetWidth = size.width;
150     int32_t targetHeight = size.height;
151     if (targetWidth <= 0 || targetHeight <= 0 || srcWidth <= 0 || srcHeight <= 0) {
152         IMAGE_LOGE("[PostProc]params invalid, targetWidth:%{public}d, targetHeight:%{public}d, "
153             "srcWidth:%{public}d, srcHeight:%{public}d", targetWidth, targetHeight, srcWidth, srcHeight);
154         return false;
155     }
156     float widthScale = static_cast<float>(targetWidth) / static_cast<float>(srcWidth);
157     float heightScale = static_cast<float>(targetHeight) / static_cast<float>(srcHeight);
158     float scale = max(widthScale, heightScale);
159     if (pixelMap.IsAstc() && scale > 0) {
160         TransformData transformData;
161         pixelMap.GetTransformData(transformData);
162         transformData.scaleX *= scale;
163         transformData.scaleY *= scale;
164         transformData.cropLeft = (srcWidth - targetWidth / scale) / HALF_F;
165         transformData.cropTop = (srcHeight - targetHeight / scale) / HALF_F;
166         transformData.cropWidth = targetWidth / scale;
167         transformData.cropHeight = targetHeight / scale;
168         pixelMap.SetTransformData(transformData);
169         ImageInfo imageInfo;
170         pixelMap.GetImageInfo(imageInfo);
171         imageInfo.size.width = targetWidth;
172         imageInfo.size.height = targetHeight;
173         pixelMap.SetImageInfo(imageInfo, true);
174         return true;
175     }
176     if (!ScalePixelMap(scale, scale, pixelMap)) {
177         IMAGE_LOGE("[PostProc]center scale pixelmap %{public}f fail", scale);
178         return false;
179     }
180     srcWidth = pixelMap.GetWidth();
181     srcHeight = pixelMap.GetHeight();
182     if (srcWidth == targetWidth && srcHeight == targetHeight) {
183         return true;
184     }
185     if (srcWidth < targetWidth || srcHeight < targetHeight) {
186         IMAGE_LOGE("[PostProc]src size [%{public}d, %{public}d] must less than dst size [%{public}d,"
187             "%{public}d]", srcWidth, srcHeight, targetWidth, targetHeight);
188         return false;
189     }
190 
191     return CenterDisplay(pixelMap, srcWidth, srcHeight, targetWidth, targetHeight);
192 }
193 
CopyPixels(PixelMap& pixelMap, uint8_t* dstPixels, const Size& dstSize, const int32_t srcWidth, const int32_t srcHeight, int32_t srcRowStride, int32_t targetRowStride)194 bool PostProc::CopyPixels(PixelMap& pixelMap, uint8_t* dstPixels, const Size& dstSize,
195                           const int32_t srcWidth, const int32_t srcHeight,
196                           int32_t srcRowStride, int32_t targetRowStride)
197 {
198     int32_t targetWidth = dstSize.width;
199     int32_t targetHeight = dstSize.height;
200     int32_t left = max(0, srcWidth - targetWidth) / HALF;
201     int32_t top = max(0, srcHeight - targetHeight) / HALF;
202     int32_t pixelBytes = pixelMap.GetPixelBytes();
203     uint8_t *dstStartPixel = nullptr;
204     uint8_t *srcStartPixel = nullptr;
205     int32_t targetRowBytes = targetWidth * pixelBytes;
206     if (targetRowStride <= 0) {
207         targetRowStride = targetRowBytes;
208     }
209     int32_t srcRowBytes = srcWidth * pixelBytes;
210     if (srcRowStride <= 0) {
211         srcRowStride = srcRowBytes;
212     }
213     uint8_t *srcPixels = const_cast<uint8_t *>(pixelMap.GetPixels()) + top * srcRowStride + left * pixelBytes;
214     uint32_t copyRowBytes = static_cast<uint32_t>(std::min(srcWidth, targetWidth) * pixelBytes);
215     for (int32_t scanLine = 0; scanLine < std::min(srcHeight, targetHeight); scanLine++) {
216         dstStartPixel = dstPixels + scanLine * targetRowStride;
217         srcStartPixel = srcPixels + scanLine * srcRowStride;
218         errno_t errRet = memcpy_s(dstStartPixel, static_cast<size_t>(targetRowBytes), srcStartPixel, copyRowBytes);
219         if (errRet != EOK) {
220             IMAGE_LOGE("[PostProc]memcpy scanline %{public}d fail, errorCode = %{public}d", scanLine, errRet);
221             return false;
222         }
223     }
224     return true;
225 }
226 
CenterDisplay(PixelMap &pixelMap, int32_t srcWidth, int32_t srcHeight, int32_t targetWidth, int32_t targetHeight)227 bool PostProc::CenterDisplay(PixelMap &pixelMap, int32_t srcWidth, int32_t srcHeight, int32_t targetWidth,
228                              int32_t targetHeight)
229 {
230     ImageInfo dstImageInfo;
231     pixelMap.GetImageInfo(dstImageInfo);
232     int32_t srcRowStride = pixelMap.GetAllocatorType() == AllocatorType::DMA_ALLOC ? pixelMap.GetRowStride() : 0;
233     dstImageInfo.size.width = targetWidth;
234     dstImageInfo.size.height = targetHeight;
235     if (pixelMap.SetImageInfo(dstImageInfo, true) != SUCCESS) {
236         IMAGE_LOGE("update ImageInfo failed");
237         return false;
238     }
239     int32_t bufferSize = pixelMap.GetByteCount();
240     uint8_t *dstPixels = nullptr;
241     void *nativeBuffer = nullptr;
242     int fd = 0;
243     int targetRowStride = 0;
244     if (pixelMap.GetAllocatorType() == AllocatorType::HEAP_ALLOC) {
245         if (!AllocHeapBuffer(bufferSize, &dstPixels)) {
246             return false;
247         }
248     } else if (pixelMap.GetAllocatorType() == AllocatorType::DMA_ALLOC) {
249         dstPixels = AllocDmaMemory(dstImageInfo, bufferSize, &nativeBuffer, targetRowStride);
250     } else {
251         dstPixels = AllocSharedMemory(dstImageInfo.size, bufferSize, fd, pixelMap.GetUniqueId());
252     }
253     if (dstPixels == nullptr) {
254         IMAGE_LOGE("[PostProc]CenterDisplay AllocMemory[%{public}d] failed", pixelMap.GetAllocatorType());
255         return false;
256     }
257     if (!CopyPixels(pixelMap, dstPixels, dstImageInfo.size, srcWidth, srcHeight, srcRowStride, targetRowStride)) {
258         IMAGE_LOGE("[PostProc]CopyPixels failed");
259         ReleaseBuffer(pixelMap.GetAllocatorType(), fd, bufferSize, &dstPixels, nativeBuffer);
260         return false;
261     }
262     void *fdBuffer = nullptr;
263     if (pixelMap.GetAllocatorType() == AllocatorType::HEAP_ALLOC) {
264         pixelMap.SetPixelsAddr(dstPixels, nullptr, bufferSize, AllocatorType::HEAP_ALLOC, nullptr);
265     } else if (pixelMap.GetAllocatorType() == AllocatorType::DMA_ALLOC) {
266 #if !defined(_WIN32) && !defined(_APPLE) && !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
267         sptr<SurfaceBuffer> sourceSurfaceBuffer(reinterpret_cast<SurfaceBuffer*> (pixelMap.GetFd()));
268         sptr<SurfaceBuffer> dstSurfaceBuffer(reinterpret_cast<SurfaceBuffer*> (nativeBuffer));
269         VpeUtils::CopySurfaceBufferInfo(sourceSurfaceBuffer, dstSurfaceBuffer);
270 #endif
271         pixelMap.SetPixelsAddr(dstPixels, nativeBuffer, bufferSize, AllocatorType::DMA_ALLOC, nullptr);
272     } else {
273         fdBuffer = new int32_t();
274         *static_cast<int32_t *>(fdBuffer) = fd;
275         pixelMap.SetPixelsAddr(dstPixels, fdBuffer, bufferSize, AllocatorType::SHARE_MEM_ALLOC, nullptr);
276     }
277     return true;
278 }
279 
ProcessScanlineFilter(ScanlineFilter &scanlineFilter, const Rect &cropRect, PixelMap &pixelMap, uint8_t *resultData, uint32_t rowBytes)280 bool PostProc::ProcessScanlineFilter(ScanlineFilter &scanlineFilter, const Rect &cropRect, PixelMap &pixelMap,
281                                      uint8_t *resultData, uint32_t rowBytes)
282 {
283     auto srcData = pixelMap.GetPixels();
284     int32_t scanLine = 0;
285     while (scanLine < pixelMap.GetHeight()) {
286         FilterRowType filterRow = scanlineFilter.GetFilterRowType(scanLine);
287         if (filterRow == FilterRowType::NON_REFERENCE_ROW) {
288             scanLine++;
289             continue;
290         }
291         if (filterRow == FilterRowType::LAST_REFERENCE_ROW) {
292             break;
293         }
294         uint32_t ret = scanlineFilter.FilterLine(resultData + ((scanLine - cropRect.top) * rowBytes), rowBytes,
295                                                  srcData + (scanLine * pixelMap.GetRowBytes()));
296         if (ret != SUCCESS) {
297             IMAGE_LOGE("[PostProc]scan line failed, ret:%{public}u", ret);
298             return false;
299         }
300         scanLine++;
301     }
302     return true;
303 }
304 
CheckScanlineFilter(const Rect &cropRect, ImageInfo &dstImageInfo, PixelMap &pixelMap, int32_t pixelBytes, ScanlineFilter &scanlineFilter)305 uint32_t PostProc::CheckScanlineFilter(const Rect &cropRect, ImageInfo &dstImageInfo, PixelMap &pixelMap,
306                                        int32_t pixelBytes, ScanlineFilter &scanlineFilter)
307 {
308     uint64_t bufferSize = static_cast<uint64_t>(dstImageInfo.size.width) * dstImageInfo.size.height * pixelBytes;
309     uint8_t *resultData = nullptr;
310     int fd = 0;
311     if (decodeOpts_.allocatorType == AllocatorType::SHARE_MEM_ALLOC) {
312         resultData = AllocSharedMemory(dstImageInfo.size, bufferSize, fd, pixelMap.GetUniqueId());
313         if (resultData == nullptr) {
314             IMAGE_LOGE("[PostProc]AllocSharedMemory failed");
315             return ERR_IMAGE_CROP;
316         }
317     } else {
318         if (!AllocHeapBuffer(bufferSize, &resultData)) {
319             return ERR_IMAGE_CROP;
320         }
321     }
322     if (ImageUtils::CheckMulOverflow(dstImageInfo.size.width, pixelBytes)) {
323         IMAGE_LOGE("[PostProc]size.width:%{public}d, is too large",
324             dstImageInfo.size.width);
325         ReleaseBuffer(decodeOpts_.allocatorType, fd, bufferSize, &resultData);
326         return ERR_IMAGE_CROP;
327     }
328     uint32_t rowBytes = pixelBytes * dstImageInfo.size.width;
329     if (!ProcessScanlineFilter(scanlineFilter, cropRect, pixelMap, resultData, rowBytes)) {
330         IMAGE_LOGE("[PostProc]ProcessScanlineFilter failed");
331         ReleaseBuffer(decodeOpts_.allocatorType, fd, bufferSize, &resultData);
332         return ERR_IMAGE_CROP;
333     }
334     uint32_t result = pixelMap.SetImageInfo(dstImageInfo);
335     if (result != SUCCESS) {
336         ReleaseBuffer(decodeOpts_.allocatorType, fd, bufferSize, &resultData);
337         return result;
338     }
339 
340     if (decodeOpts_.allocatorType == AllocatorType::HEAP_ALLOC) {
341         pixelMap.SetPixelsAddr(resultData, nullptr, bufferSize, decodeOpts_.allocatorType, nullptr);
342         return result;
343     }
344     void *fdBuffer = new int32_t();
345     *static_cast<int32_t *>(fdBuffer) = fd;
346     pixelMap.SetPixelsAddr(resultData, fdBuffer, bufferSize, decodeOpts_.allocatorType, nullptr);
347     return result;
348 }
349 
ConvertProc(const Rect &cropRect, ImageInfo &dstImageInfo, PixelMap &pixelMap, ImageInfo &srcImageInfo)350 uint32_t PostProc::ConvertProc(const Rect &cropRect, ImageInfo &dstImageInfo, PixelMap &pixelMap,
351                                ImageInfo &srcImageInfo)
352 {
353     bool hasPixelConvert = HasPixelConvert(srcImageInfo, dstImageInfo);
354     uint32_t ret = NeedScanlineFilter(cropRect, srcImageInfo.size, hasPixelConvert);
355     if (ret != NEED_NEXT) {
356         return ret;
357     }
358 
359     // we suppose a quick method to scanline in mostly seen cases: NO CROP && hasPixelConvert
360     if (GetCropValue(cropRect, srcImageInfo.size) == CropValue::NOCROP &&
361         dstImageInfo.pixelFormat == PixelFormat::ARGB_8888 && hasPixelConvert) {
362         IMAGE_LOGI("[PostProc]no need crop, only pixel convert.");
363         return PixelConvertProc(dstImageInfo, pixelMap, srcImageInfo);
364     }
365 
366     ScanlineFilter scanlineFilter(srcImageInfo.pixelFormat);
367     // this method maybe update dst image size to crop size
368     SetScanlineCropAndConvert(cropRect, dstImageInfo, srcImageInfo, scanlineFilter, hasPixelConvert);
369 
370     int32_t pixelBytes = ImageUtils::GetPixelBytes(dstImageInfo.pixelFormat);
371     if (pixelBytes == 0) {
372         return ERR_IMAGE_CROP;
373     }
374     if (ImageUtils::CheckMulOverflow(dstImageInfo.size.width, dstImageInfo.size.height, pixelBytes)) {
375         IMAGE_LOGE("[PostProc]size.width:%{public}d, size.height:%{public}d is too large",
376             dstImageInfo.size.width, dstImageInfo.size.height);
377         return ERR_IMAGE_CROP;
378     }
379     return CheckScanlineFilter(cropRect, dstImageInfo, pixelMap, pixelBytes, scanlineFilter);
380 }
381 
PixelConvertProc(ImageInfo &dstImageInfo, PixelMap &pixelMap, ImageInfo &srcImageInfo)382 uint32_t PostProc::PixelConvertProc(ImageInfo &dstImageInfo, PixelMap &pixelMap,
383                                     ImageInfo &srcImageInfo)
384 {
385     uint32_t ret;
386     int fd = 0;
387     uint64_t bufferSize = 0;
388     uint8_t *resultData = nullptr;
389 
390     // as no crop, the size is same as src
391     dstImageInfo.size = srcImageInfo.size;
392     if (AllocBuffer(dstImageInfo, &resultData, bufferSize, fd, pixelMap.GetUniqueId()) != SUCCESS) {
393         ReleaseBuffer(decodeOpts_.allocatorType, fd, bufferSize, &resultData);
394         return ERR_IMAGE_CROP;
395     }
396 
397     int32_t pixelBytes = ImageUtils::GetPixelBytes(srcImageInfo.pixelFormat);
398     if (pixelBytes == 0) {
399         ReleaseBuffer(decodeOpts_.allocatorType, fd, bufferSize, &resultData);
400         return ERR_IMAGE_CROP;
401     }
402 
403     ret = pixelMap.SetImageInfo(dstImageInfo);
404     if (ret != SUCCESS) {
405         ReleaseBuffer(decodeOpts_.allocatorType, fd, bufferSize, &resultData);
406         return ret;
407     }
408 
409     if (decodeOpts_.allocatorType == AllocatorType::HEAP_ALLOC) {
410         pixelMap.SetPixelsAddr(resultData, nullptr, bufferSize, decodeOpts_.allocatorType, nullptr);
411         return ret;
412     }
413 
414     void *fdBuffer = new int32_t();
415     *static_cast<int32_t *>(fdBuffer) = fd;
416     pixelMap.SetPixelsAddr(resultData, fdBuffer, bufferSize, decodeOpts_.allocatorType, nullptr);
417     return ret;
418 }
419 
AllocBuffer(ImageInfo imageInfo, uint8_t **resultData, uint64_t &bufferSize, int &fd, uint32_t id)420 uint32_t PostProc::AllocBuffer(ImageInfo imageInfo, uint8_t **resultData, uint64_t &bufferSize, int &fd, uint32_t id)
421 {
422     int32_t pixelBytes = ImageUtils::GetPixelBytes(imageInfo.pixelFormat);
423     if (pixelBytes == 0) {
424         return ERR_IMAGE_CROP;
425     }
426     if (ImageUtils::CheckMulOverflow(imageInfo.size.width, imageInfo.size.height, pixelBytes)) {
427         IMAGE_LOGE("[PostProc]size.width:%{public}d, size.height:%{public}d is too large",
428             imageInfo.size.width, imageInfo.size.height);
429         return ERR_IMAGE_CROP;
430     }
431     bufferSize = static_cast<uint64_t>(imageInfo.size.width) * imageInfo.size.height * pixelBytes;
432     IMAGE_LOGD("[PostProc]size.width:%{public}d, size.height:%{public}d, bufferSize:%{public}lld",
433         imageInfo.size.width, imageInfo.size.height, static_cast<long long>(bufferSize));
434     if (decodeOpts_.allocatorType == AllocatorType::SHARE_MEM_ALLOC) {
435         *resultData = AllocSharedMemory(imageInfo.size, bufferSize, fd, id);
436         if (*resultData == nullptr) {
437             IMAGE_LOGE("[PostProc]AllocSharedMemory failed");
438             return ERR_IMAGE_CROP;
439         }
440     } else {
441         if (!AllocHeapBuffer(bufferSize, resultData)) {
442             return ERR_IMAGE_CROP;
443         }
444     }
445     return SUCCESS;
446 }
447 
AllocHeapBuffer(uint64_t bufferSize, uint8_t **buffer)448 bool PostProc::AllocHeapBuffer(uint64_t bufferSize, uint8_t **buffer)
449 {
450     if (bufferSize == 0 || bufferSize > MALLOC_MAX_LENTH) {
451         IMAGE_LOGE("[PostProc]Invalid value of bufferSize");
452         return false;
453     }
454     *buffer = static_cast<uint8_t *>(malloc(bufferSize));
455     if (*buffer == nullptr) {
456         IMAGE_LOGE("[PostProc]alloc covert color buffersize[%{public}llu] failed.",
457             static_cast<unsigned long long>(bufferSize));
458         return false;
459     }
460 #ifdef _WIN32
461     errno_t backRet = memset_s(*buffer, 0, bufferSize);
462     if (backRet != EOK) {
463         IMAGE_LOGE("[PostProc]memset convertData fail, errorCode = %{public}d", backRet);
464         ReleaseBuffer(AllocatorType::HEAP_ALLOC, 0, 0, buffer);
465         return false;
466     }
467     return true;
468 #else
469     errno_t errRet = memset_s(*buffer, bufferSize, 0, bufferSize);
470     if (errRet != EOK) {
471         IMAGE_LOGE("[PostProc]memset convertData fail, errorCode = %{public}d", errRet);
472         ReleaseBuffer(AllocatorType::HEAP_ALLOC, 0, 0, buffer);
473         return false;
474     }
475     return true;
476 #endif
477 }
478 
AllocSharedMemory(const Size &size, const uint64_t bufferSize, int &fd, uint32_t uniqueId)479 uint8_t *PostProc::AllocSharedMemory(const Size &size, const uint64_t bufferSize, int &fd, uint32_t uniqueId)
480 {
481 #if defined(_WIN32) || defined(_APPLE) || defined(IOS_PLATFORM) || defined(ANDROID_PLATFORM)
482         return nullptr;
483 #else
484     std::string name = "Parcel RawData, uniqueId: " + std::to_string(getpid()) + '_' + std::to_string(uniqueId);
485     fd = AshmemCreate(name.c_str(), bufferSize);
486     if (fd < 0) {
487         IMAGE_LOGE("[PostProc]AllocSharedMemory fd error, bufferSize %{public}lld",
488             static_cast<long long>(bufferSize));
489         return nullptr;
490     }
491     int result = AshmemSetProt(fd, PROT_READ | PROT_WRITE);
492     if (result < 0) {
493         IMAGE_LOGE("[PostProc]AshmemSetProt error");
494         ::close(fd);
495         return nullptr;
496     }
497     void* ptr = ::mmap(nullptr, bufferSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
498     if (ptr == MAP_FAILED) {
499         IMAGE_LOGE("[PostProc]mmap error, errno: %{public}s, fd %{public}d, bufferSize %{public}lld",
500             strerror(errno), fd, (long long)bufferSize);
501         ::close(fd);
502         return nullptr;
503     }
504     return reinterpret_cast<uint8_t *>(ptr);
505 #endif
506 }
507 
AllocDmaMemory(ImageInfo info, const uint64_t bufferSize, void **nativeBuffer, int &targetRowStride)508 uint8_t *PostProc::AllocDmaMemory(ImageInfo info, const uint64_t bufferSize,
509                                   void **nativeBuffer, int &targetRowStride)
510 {
511 #if defined(_WIN32) || defined(_APPLE) || defined(IOS_PLATFORM) || defined(ANDROID_PLATFORM)
512     return nullptr;
513 #else
514     MemoryData memoryData = {nullptr, (uint32_t)bufferSize, "PostProc", {info.size.width, info.size.height}};
515     memoryData.format = info.pixelFormat;
516     auto dstMemory = MemoryManager::CreateMemory(AllocatorType::DMA_ALLOC, memoryData);
517     if (dstMemory == nullptr) {
518         return nullptr;
519     }
520     *nativeBuffer = dstMemory->extend.data;
521     auto sbBuffer = reinterpret_cast<SurfaceBuffer *>(dstMemory->extend.data);
522     targetRowStride = sbBuffer->GetStride();
523     return (uint8_t *)dstMemory->data.data;
524 #endif
525 }
526 
ReleaseBuffer(AllocatorType allocatorType, int fd, uint64_t dataSize, uint8_t **buffer, void *nativeBuffer)527 void PostProc::ReleaseBuffer(AllocatorType allocatorType, int fd,
528                              uint64_t dataSize, uint8_t **buffer, void *nativeBuffer)
529 {
530 #if !defined(_WIN32) && !defined(_APPLE) && !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
531     if (allocatorType == AllocatorType::SHARE_MEM_ALLOC) {
532         if (*buffer != nullptr) {
533             ::munmap(*buffer, dataSize);
534             ::close(fd);
535         }
536         return;
537     }
538     if (allocatorType == AllocatorType::DMA_ALLOC) {
539         if (nativeBuffer != nullptr) {
540             int32_t err = ImageUtils::SurfaceBuffer_Unreference(static_cast<SurfaceBuffer*>(nativeBuffer));
541             if (err != OHOS::GSERROR_OK) {
542                 IMAGE_LOGE("PostProc NativeBufferReference failed");
543             }
544         }
545         return;
546     }
547 #endif
548 
549     if (allocatorType == AllocatorType::HEAP_ALLOC) {
550         if (*buffer != nullptr) {
551             free(*buffer);
552             *buffer = nullptr;
553         }
554         return;
555     }
556 }
557 
NeedScanlineFilter(const Rect &cropRect, const Size &srcSize, const bool &hasPixelConvert)558 uint32_t PostProc::NeedScanlineFilter(const Rect &cropRect, const Size &srcSize, const bool &hasPixelConvert)
559 {
560     CropValue value = GetCropValue(cropRect, srcSize);
561     if (value == CropValue::NOCROP && !hasPixelConvert) {
562         IMAGE_LOGI("[PostProc]no need crop and pixel convert.");
563         return SUCCESS;
564     } else if (value == CropValue::INVALID) {
565         IMAGE_LOGE("[PostProc]invalid corp region, top:%{public}d, left:%{public}d, "
566             "width:%{public}d, height:%{public}d", cropRect.top, cropRect.left, cropRect.width, cropRect.height);
567         return ERR_IMAGE_CROP;
568     }
569     return NEED_NEXT;
570 }
571 
ConvertPixelMapToPixmapInfo(PixelMap &pixelMap, PixmapInfo &pixmapInfo)572 void PostProc::ConvertPixelMapToPixmapInfo(PixelMap &pixelMap, PixmapInfo &pixmapInfo)
573 {
574     pixmapInfo.imageInfo.size.width = pixelMap.GetWidth();
575     pixmapInfo.imageInfo.size.height = pixelMap.GetHeight();
576     pixmapInfo.imageInfo.pixelFormat = pixelMap.GetPixelFormat();
577     pixmapInfo.imageInfo.colorSpace = pixelMap.GetColorSpace();
578     pixmapInfo.imageInfo.alphaType = pixelMap.GetAlphaType();
579     pixmapInfo.imageInfo.baseDensity = pixelMap.GetBaseDensity();
580     pixmapInfo.data = const_cast<uint8_t *>(pixelMap.GetPixels());
581     pixmapInfo.bufferSize = pixelMap.GetByteCount();
582 }
583 
RotatePixelMap(float rotateDegrees, PixelMap &pixelMap)584 bool PostProc::RotatePixelMap(float rotateDegrees, PixelMap &pixelMap)
585 {
586     BasicTransformer trans;
587     PixmapInfo input(false);
588     ConvertPixelMapToPixmapInfo(pixelMap, input);
589     // Default rotation at the center of the image, so divide 2
590     trans.SetRotateParam(rotateDegrees, static_cast<float>(input.imageInfo.size.width) * FHALF,
591                          static_cast<float>(input.imageInfo.size.height) * FHALF);
592     return Transform(trans, input, pixelMap);
593 }
594 
ScalePixelMap(const Size &size, PixelMap &pixelMap)595 bool PostProc::ScalePixelMap(const Size &size, PixelMap &pixelMap)
596 {
597     int32_t srcWidth = pixelMap.GetWidth();
598     int32_t srcHeight = pixelMap.GetHeight();
599     if (srcWidth <= 0 || srcHeight <= 0) {
600         IMAGE_LOGE("[PostProc]src width:%{public}d, height:%{public}d is invalid.", srcWidth, srcHeight);
601         return false;
602     }
603     float scaleX = static_cast<float>(size.width) / static_cast<float>(srcWidth);
604     float scaleY = static_cast<float>(size.height) / static_cast<float>(srcHeight);
605     return ScalePixelMap(scaleX, scaleY, pixelMap);
606 }
607 
ScalePixelMap(float scaleX, float scaleY, PixelMap &pixelMap)608 bool PostProc::ScalePixelMap(float scaleX, float scaleY, PixelMap &pixelMap)
609 {
610     // returns directly with a scale of 1.0
611     if ((fabs(scaleX - 1.0f) < EPSILON) && (fabs(scaleY - 1.0f) < EPSILON)) {
612         return true;
613     }
614     return pixelMap.resize(scaleX, scaleY);
615 }
TranslatePixelMap(float tX, float tY, PixelMap &pixelMap)616 bool PostProc::TranslatePixelMap(float tX, float tY, PixelMap &pixelMap)
617 {
618     BasicTransformer trans;
619     PixmapInfo input(false);
620     ConvertPixelMapToPixmapInfo(pixelMap, input);
621 
622     trans.SetTranslateParam(tX, tY);
623     return Transform(trans, input, pixelMap);
624 }
625 
Transform(BasicTransformer &trans, const PixmapInfo &input, PixelMap &pixelMap)626 bool PostProc::Transform(BasicTransformer &trans, const PixmapInfo &input, PixelMap &pixelMap)
627 {
628     if (pixelMap.IsTransformered()) {
629         IMAGE_LOGE("[PostProc]Transform pixelmap is transforming");
630         return false;
631     }
632     pixelMap.SetTransformered(true);
633     PixmapInfo output(false);
634     output.uniqueId = pixelMap.GetUniqueId();
635     uint32_t ret;
636     if (decodeOpts_.allocatorType == AllocatorType::SHARE_MEM_ALLOC) {
637         typedef uint8_t *(*AllocMemory)(const Size &size, const uint64_t bufferSize, int &fd, uint32_t uniqueId);
638         AllocMemory allcFunc = AllocSharedMemory;
639         ret = trans.TransformPixmap(input, output, allcFunc);
640     } else {
641         ret = trans.TransformPixmap(input, output);
642     }
643     if (ret != IMAGE_SUCCESS) {
644         output.Destroy();
645         return false;
646     }
647 
648     if (pixelMap.SetImageInfo(output.imageInfo) != SUCCESS) {
649         output.Destroy();
650         return false;
651     }
652     pixelMap.SetPixelsAddr(output.data, output.context, output.bufferSize, decodeOpts_.allocatorType, nullptr);
653     pixelMap.SetTransformered(false);
654     return true;
655 }
656 
GetCropValue(const Rect &rect, const Size &size)657 CropValue PostProc::GetCropValue(const Rect &rect, const Size &size)
658 {
659     bool isSameSize = (rect.top == 0 && rect.left == 0 && rect.height == size.height && rect.width == size.width);
660     if (!IsHasCrop(rect) || isSameSize) {
661         return CropValue::NOCROP;
662     }
663     bool isValid = ((rect.top >= 0 && rect.width > 0 && rect.left >= 0 && rect.height > 0) &&
664                     (rect.top + rect.height <= size.height) && (rect.left + rect.width <= size.width));
665     if (!isValid) {
666         return CropValue::INVALID;
667     }
668     return CropValue::VALID;
669 }
670 
ValidCropValue(Rect &rect, const Size &size)671 CropValue PostProc::ValidCropValue(Rect &rect, const Size &size)
672 {
673     CropValue res = GetCropValue(rect, size);
674     if (res == CropValue::INVALID) {
675         if (rect.top + rect.height > size.height) {
676             rect.height = size.height - rect.top;
677         }
678         if (rect.left + rect.width > size.width) {
679             rect.width = size.width - rect.left;
680         }
681         res = GetCropValue(rect, size);
682     }
683     return res;
684 }
685 
IsHasCrop(const Rect &rect)686 bool PostProc::IsHasCrop(const Rect &rect)
687 {
688     return (rect.top != 0 || rect.left != 0 || rect.width != 0 || rect.height != 0);
689 }
690 
HasPixelConvert(const ImageInfo &srcImageInfo, ImageInfo &dstImageInfo)691 bool PostProc::HasPixelConvert(const ImageInfo &srcImageInfo, ImageInfo &dstImageInfo)
692 {
693     dstImageInfo.alphaType = ImageUtils::GetValidAlphaTypeByFormat(dstImageInfo.alphaType, dstImageInfo.pixelFormat);
694     return (dstImageInfo.pixelFormat != srcImageInfo.pixelFormat || dstImageInfo.alphaType != srcImageInfo.alphaType);
695 }
696 
SetScanlineCropAndConvert(const Rect &cropRect, ImageInfo &dstImageInfo, ImageInfo &srcImageInfo, ScanlineFilter &scanlineFilter, bool hasPixelConvert)697 void PostProc::SetScanlineCropAndConvert(const Rect &cropRect, ImageInfo &dstImageInfo, ImageInfo &srcImageInfo,
698                                          ScanlineFilter &scanlineFilter, bool hasPixelConvert)
699 {
700     if (hasPixelConvert) {
701         scanlineFilter.SetPixelConvert(srcImageInfo, dstImageInfo);
702     }
703 
704     Rect srcRect = cropRect;
705     if (IsHasCrop(cropRect)) {
706         dstImageInfo.size.width = cropRect.width;
707         dstImageInfo.size.height = cropRect.height;
708     } else {
709         srcRect = { 0, 0, srcImageInfo.size.width, srcImageInfo.size.height };
710         dstImageInfo.size = srcImageInfo.size;
711     }
712     scanlineFilter.SetSrcRegion(srcRect);
713 }
714 
715 #if !defined(_WIN32) && !defined(_APPLE) && !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
GetScaleFormat(const PixelFormat &format, AVPixelFormat &pixelFormat)716 bool GetScaleFormat(const PixelFormat &format, AVPixelFormat &pixelFormat)
717 {
718     if (format != PixelFormat::UNKNOWN) {
719         auto formatPair = PIXEL_FORMAT_MAP.find(format);
720         if (formatPair != PIXEL_FORMAT_MAP.end() && formatPair->second != 0) {
721             pixelFormat = formatPair->second;
722             return true;
723         }
724     }
725     return false;
726 }
727 
GetInterpolation(const AntiAliasingOption &option)728 int GetInterpolation(const AntiAliasingOption &option)
729 {
730     switch (option) {
731         case AntiAliasingOption::NONE:
732             return SWS_POINT;
733         case AntiAliasingOption::LOW:
734             return SWS_BILINEAR;
735         case AntiAliasingOption::MEDIUM:
736             return SWS_BICUBIC;
737         case AntiAliasingOption::HIGH:
738             return SWS_AREA;
739         case AntiAliasingOption::FAST_BILINEAER:
740             return SWS_FAST_BILINEAR;
741         case AntiAliasingOption::BICUBLIN:
742             return SWS_BICUBLIN;
743         case AntiAliasingOption::GAUSS:
744             return SWS_GAUSS;
745         case AntiAliasingOption::SINC:
746             return SWS_SINC;
747         case AntiAliasingOption::LANCZOS:
748             return SWS_LANCZOS;
749         case AntiAliasingOption::SPLINE:
750             return SWS_SPLINE;
751         default:
752             return SWS_POINT;
753     }
754 }
755 
GetNewSkSLRCacheMgr()756 static SkSLRCacheMgr GetNewSkSLRCacheMgr()
757 {
758     static SkMutex slrMutex;
759     static SLRLRUCache slrCache(SLR_CACHE_CAPACITY);
760     return SkSLRCacheMgr(slrCache, slrMutex);
761 }
762 
initSLRFactor(Size srcSize, Size dstSize)763 std::shared_ptr<SLRWeightTuple> PostProc::initSLRFactor(Size srcSize, Size dstSize)
764 {
765     if (srcSize.width == 0 || srcSize.height == 0 || dstSize.width == 0 || dstSize.height == 0) {
766         IMAGE_LOGE("initSLRFactor invalid size, %{public}d, %{public}d, %{public}d, %{public}d",
767             srcSize.width, srcSize.height, dstSize.width, dstSize.height);
768         return nullptr;
769     }
770     SkSLRCacheMgr cacheMgr = GetNewSkSLRCacheMgr();
771     SLRWeightKey key(srcSize, dstSize);
772     std::shared_ptr<SLRWeightTuple> weightTuplePtr = cacheMgr.find(key.fKey);
773     if (weightTuplePtr == nullptr) {
774         SLRWeightMat slrWeightX = SLRProc::GetWeights(static_cast<float>(dstSize.width) / srcSize.width,
775             static_cast<int>(dstSize.width));
776         SLRWeightMat slrWeightY = SLRProc::GetWeights(static_cast<float>(dstSize.height) / srcSize.height,
777             static_cast<int>(dstSize.height));
778         SLRWeightTuple value{slrWeightX, slrWeightY, key};
779         std::shared_ptr<SLRWeightTuple> weightPtr = std::make_shared<SLRWeightTuple>(value);
780         cacheMgr.insert(key.fKey, weightPtr);
781         IMAGE_LOGI("initSLRFactor insert:%{public}d", key.fKey);
782         return weightPtr;
783     }
784     return weightTuplePtr;
785 }
786 
CheckPixelMapSLR(const Size &desiredSize, PixelMap &pixelMap)787 bool CheckPixelMapSLR(const Size &desiredSize, PixelMap &pixelMap)
788 {
789     ImageInfo imgInfo;
790     pixelMap.GetImageInfo(imgInfo);
791     if (imgInfo.pixelFormat != PixelFormat::RGBA_8888) {
792         IMAGE_LOGE("CheckPixelMapSLR only support RGBA_8888 format");
793         return false;
794     }
795     int32_t srcWidth = pixelMap.GetWidth();
796     int32_t srcHeight = pixelMap.GetHeight();
797     if (srcWidth <= 0 || srcHeight <= 0 || !pixelMap.GetWritablePixels()) {
798         IMAGE_LOGE("CheckPixelMapSLR invalid src size, %{public}d, %{public}d", srcWidth, srcHeight);
799         return false;
800     }
801     if (desiredSize.width <= 0 || desiredSize.height <= 0) {
802         IMAGE_LOGE("CheckPixelMapSLR invalid desired size, %{public}d, %{public}d",
803             desiredSize.width, desiredSize.height);
804         return false;
805     }
806     if (desiredSize.width == srcWidth && desiredSize.height == srcHeight) {
807         IMAGE_LOGE("CheckPixelMapSLR same source and desired size, %{public}d, %{public}d",
808             desiredSize.width, desiredSize.height);
809         return false;
810     }
811     int32_t pixelBytes = pixelMap.GetPixelBytes();
812     if (pixelBytes <= 0) {
813         IMAGE_LOGE("CheckPixelMapSLR invalid pixel bytes, %{public}d", pixelBytes);
814         return false;
815     }
816     uint64_t dstSizeOverflow =
817         static_cast<uint64_t>(desiredSize.width) * static_cast<uint64_t>(desiredSize.height) *
818         static_cast<uint64_t>(pixelBytes);
819     if (dstSizeOverflow > UINT_MAX) {
820         IMAGE_LOGE("ScalePixelMapWithSLR desired size overflow");
821         return false;
822     }
823     return true;
824 }
825 
ScalePixelMapWithSLR(const Size &desiredSize, PixelMap &pixelMap)826 bool PostProc::ScalePixelMapWithSLR(const Size &desiredSize, PixelMap &pixelMap)
827 {
828     ImageInfo imgInfo;
829     pixelMap.GetImageInfo(imgInfo);
830     if (!CheckPixelMapSLR(desiredSize, pixelMap)) {
831         return false;
832     }
833     ImageTrace imageTrace("ScalePixelMapWithSLR");
834     std::shared_ptr<SLRWeightTuple> weightTuplePtr = initSLRFactor(imgInfo.size, desiredSize);
835     if (weightTuplePtr == nullptr) {
836         IMAGE_LOGE("ScalePixelMapWithSLR init failed");
837         return false;
838     }
839     int32_t pixelBytes = pixelMap.GetPixelBytes();
840     SLRMat src(imgInfo.size, imgInfo.pixelFormat, pixelMap.GetWritablePixels(), pixelMap.GetRowStride() / pixelBytes);
841     uint32_t dstBufferSize = desiredSize.height * desiredSize.width * pixelBytes;
842     MemoryData memoryData = {nullptr, dstBufferSize, "ScalePixelMapWithSLR ImageData", desiredSize,
843         pixelMap.GetPixelFormat()};
844     auto m = MemoryManager::CreateMemory(pixelMap.GetAllocatorType(), memoryData);
845     if (m == nullptr) {
846         IMAGE_LOGE("ScalePixelMapWithSLR create memory failed");
847         return false;
848     }
849     size_t rowStride;
850     if (m->GetType() == AllocatorType::DMA_ALLOC) {
851 #if !defined(_WIN32) && !defined(_APPLE) && !defined(IOS_PLATFORM) && !defined(ANDROID_PLATFORM)
852         rowStride = reinterpret_cast<SurfaceBuffer*>(m->extend.data)->GetStride();
853 #endif
854     } else {
855         rowStride = desiredSize.width * pixelBytes;
856     }
857     SLRMat dst({desiredSize.width, desiredSize.height}, imgInfo.pixelFormat, m->data.data, rowStride / pixelBytes);
858     SLRWeightMat slrWeightX = std::get<0>(*weightTuplePtr);
859     SLRWeightMat slrWeightY = std::get<1>(*weightTuplePtr);
860     if (ImageSystemProperties::GetSLRParallelEnabled()) {
861         SLRProc::Parallel(src, dst, slrWeightX, slrWeightY);
862     } else {
863         SLRProc::Serial(src, dst, slrWeightX, slrWeightY);
864     }
865     pixelMap.SetPixelsAddr(m->data.data, m->extend.data, dstBufferSize, m->GetType(), nullptr);
866     imgInfo.size = desiredSize;
867     pixelMap.SetImageInfo(imgInfo, true);
868     if (m->GetType() == AllocatorType::DMA_ALLOC) {
869         ImageUtils::FlushSurfaceBuffer(&pixelMap);
870     }
871     return true;
872 }
873 
ScalePixelMapEx(const Size &desiredSize, PixelMap &pixelMap, const AntiAliasingOption &option)874 bool PostProc::ScalePixelMapEx(const Size &desiredSize, PixelMap &pixelMap, const AntiAliasingOption &option)
875 {
876     ImageTrace imageTrace("PixelMap ScalePixelMapEx");
877     IMAGE_LOGD("ScalePixelMapEx pixelMap: width = %{public}d, height = %{public}d, pixelFormat = %{public}d, "
878         "allocatorType = %{public}d; desiredSize: width = %{public}d, height = %{public}d",
879         pixelMap.GetWidth(), pixelMap.GetHeight(), pixelMap.GetPixelFormat(),
880         pixelMap.GetAllocatorType(), desiredSize.width, desiredSize.height);
881 
882     ImageInfo imgInfo;
883     pixelMap.GetImageInfo(imgInfo);
884     int32_t srcWidth = pixelMap.GetWidth();
885     int32_t srcHeight = pixelMap.GetHeight();
886     if (srcWidth <= 0 || srcHeight <= 0 || !pixelMap.GetWritablePixels()) {
887         IMAGE_LOGE("pixelMap param is invalid, src width:%{public}d, height:%{public}d", srcWidth, srcHeight);
888         return false;
889     }
890     AVPixelFormat pixelFormat;
891     if (!GetScaleFormat(imgInfo.pixelFormat, pixelFormat)) {
892         IMAGE_LOGE("pixelMap format is invalid, format: %{public}d", imgInfo.pixelFormat);
893         return false;
894     }
895     uint64_t dstBufferSizeOverflow =
896         static_cast<uint64_t>(desiredSize.width) * static_cast<uint64_t>(desiredSize.height) *
897         static_cast<uint64_t>(ImageUtils::GetPixelBytes(imgInfo.pixelFormat));
898     if (dstBufferSizeOverflow > UINT_MAX) {
899         IMAGE_LOGE("ScalePixelMapEx target size too large");
900         return false;
901     }
902     uint32_t dstBufferSize = static_cast<uint32_t>(dstBufferSizeOverflow);
903     MemoryData memoryData = {nullptr, dstBufferSize, "ScalePixelMapEx ImageData", desiredSize};
904 
905     auto mem = MemoryManager::CreateMemory(pixelMap.GetAllocatorType() == AllocatorType::CUSTOM_ALLOC ?
906         AllocatorType::DEFAULT : pixelMap.GetAllocatorType(), memoryData);
907     if (mem == nullptr) {
908         IMAGE_LOGE("ScalePixelMapEx CreateMemory failed");
909         return false;
910     }
911 
912     const uint8_t *srcPixels[FFMPEG_NUM] = {};
913     uint8_t *dstPixels[FFMPEG_NUM] = {};
914     srcPixels[0] = pixelMap.GetPixels();
915     dstPixels[0] = reinterpret_cast<uint8_t *>(mem->data.data);
916     int srcRowStride[FFMPEG_NUM] = {};
917     int dstRowStride[FFMPEG_NUM] = {};
918     srcRowStride[0] = pixelMap.GetRowStride();
919     dstRowStride[0] = (mem->GetType() == AllocatorType::DMA_ALLOC) ?
920         reinterpret_cast<SurfaceBuffer*>(mem->extend.data)->GetStride() :
921         desiredSize.width * ImageUtils::GetPixelBytes(imgInfo.pixelFormat);
922 
923     void *inBuf = nullptr;
924     if (srcWidth % HALF != 0 && pixelMap.GetAllocatorType() == AllocatorType::SHARE_MEM_ALLOC) {
925         // Workaround for crash on odd number width, caused by FFmpeg 5.0 upgrade
926         uint64_t byteCount = static_cast<uint64_t>(srcRowStride[0]) * static_cast<uint64_t>(srcHeight);
927         uint64_t allocSize = static_cast<uint64_t>(srcWidth + 1) * static_cast<uint64_t>(srcHeight) *
928             static_cast<uint64_t>(ImageUtils::GetPixelBytes(imgInfo.pixelFormat));
929         if (srcRowStride[0] <= 0 || byteCount > UINT_MAX || allocSize < byteCount) {
930             mem->Release();
931             IMAGE_LOGE("ScalePixelMapEx invalid srcRowStride or pixelMap size too large");
932             return false;
933         }
934         inBuf = malloc(allocSize);
935         srcPixels[0] = reinterpret_cast<uint8_t*>(inBuf);
936         errno_t errRet = memcpy_s(inBuf, allocSize, pixelMap.GetWritablePixels(), byteCount);
937         if (errRet != EOK) {
938             if (inBuf != nullptr) {
939                 free(inBuf);
940             }
941             mem->Release();
942             IMAGE_LOGE("ScalePixelMapEx memcpy_s failed with error code: %{public}d", errRet);
943             return false;
944         }
945     }
946 
947     SwsContext *swsContext = sws_getContext(srcWidth, srcHeight, pixelFormat, desiredSize.width, desiredSize.height,
948         pixelFormat, GetInterpolation(option), nullptr, nullptr, nullptr);
949     if (swsContext == nullptr) {
950         if (inBuf != nullptr) {
951             free(inBuf);
952         }
953         mem->Release();
954         IMAGE_LOGE("sws_getContext failed");
955         return false;
956     }
957     auto res = sws_scale(swsContext, srcPixels, srcRowStride, 0, srcHeight, dstPixels, dstRowStride);
958 
959     sws_freeContext(swsContext);
960     if (inBuf != nullptr) {
961         free(inBuf);
962     }
963     if (!res) {
964         mem->Release();
965         IMAGE_LOGE("sws_scale failed");
966         return false;
967     }
968     pixelMap.SetPixelsAddr(mem->data.data, mem->extend.data, dstBufferSize, mem->GetType(), nullptr);
969     imgInfo.size = desiredSize;
970     pixelMap.SetImageInfo(imgInfo, true);
971     return true;
972 }
973 #endif
974 } // namespace Media
975 } // namespace OHOS
976