[Tizen] Fix WebPLoading memory leak
[platform/core/uifw/dali-adaptor.git] / dali / internal / imaging / common / webp-loading.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/imaging/common/webp-loading.h>
20
21 // EXTERNAL INCLUDES
22 #ifdef DALI_WEBP_AVAILABLE
23 #include <webp/decode.h>
24 #include <webp/demux.h>
25
26 #if WEBP_DEMUX_ABI_VERSION > 0x0101
27 #define DALI_ANIMATED_WEBP_ENABLED 1
28 #endif
29
30 #endif
31 #include <dali/integration-api/debug.h>
32 #include <dali/public-api/images/pixel-data.h>
33
34 #include <dali/devel-api/threading/mutex.h>
35 #include <dali/internal/imaging/common/file-download.h>
36 #include <dali/internal/system/common/file-reader.h>
37 #include <fcntl.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <unistd.h>
41 #include <cstring>
42
43 // INTERNAL INCLUDES
44 #include <dali/devel-api/adaptor-framework/image-loading.h>
45 #include <dali/internal/imaging/common/pixel-buffer-impl.h>
46
47 typedef uint8_t WebPByteType;
48
49 namespace Dali
50 {
51 namespace Internal
52 {
53 namespace Adaptor
54 {
55 namespace
56 {
57 #if defined(DEBUG_ENABLED)
58 Debug::Filter* gWebPLoadingLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_GIF_LOADING");
59 #endif
60
61 static constexpr int32_t INITIAL_INDEX               = -1;
62 static constexpr size_t  MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024;
63
64 } // namespace
65
66 struct WebPLoading::Impl
67 {
68 public:
69   Impl(const std::string& url, bool isLocalResource)
70   : mFile(nullptr),
71     mUrl(url),
72     mFrameCount(1u),
73     mMutex(),
74     mBuffer(nullptr),
75     mBufferSize(0u),
76     mImageSize(),
77     mLoadSucceeded(false),
78     mIsAnimatedImage(false),
79     mIsLocalResource(isLocalResource)
80   {
81   }
82
83   Impl(FILE* const fp)
84   : mFile(fp),
85     mUrl(),
86     mFrameCount(1u),
87     mMutex(),
88     mBuffer(nullptr),
89     mBufferSize(0u),
90     mImageSize(),
91     mLoadSucceeded(false),
92     mIsAnimatedImage(false),
93     mIsLocalResource(true)
94   {
95   }
96
97   bool LoadWebPInformation()
98   {
99     // Block to do not load this file again.
100     Mutex::ScopedLock lock(mMutex);
101     if(DALI_UNLIKELY(mLoadSucceeded))
102     {
103       return mLoadSucceeded;
104     }
105
106 #ifndef DALI_WEBP_AVAILABLE
107     // If the system doesn't support webp, loading will be failed.
108     mFrameCount    = 0u;
109     mLoadSucceeded = false;
110     return mLoadSucceeded;
111 #endif
112
113     // mFrameCount will be 1 if the input image is non-animated image or animated image with single frame.
114     if(DALI_LIKELY(ReadWebPInformation()))
115     {
116 #ifdef DALI_WEBP_AVAILABLE
117       WebPDataInit(&mWebPData);
118       mWebPData.size  = mBufferSize;
119       mWebPData.bytes = mBuffer;
120
121       WebPDemuxer* demuxer = WebPDemux(&mWebPData);
122       uint32_t     flags   = WebPDemuxGetI(demuxer, WEBP_FF_FORMAT_FLAGS);
123       if(flags & ANIMATION_FLAG)
124       {
125         mIsAnimatedImage = true;
126       }
127       WebPDemuxDelete(demuxer);
128
129       if(!mIsAnimatedImage)
130       {
131         int32_t imageWidth, imageHeight;
132         if(WebPGetInfo(mBuffer, mBufferSize, &imageWidth, &imageHeight))
133         {
134           mImageSize = ImageDimensions(imageWidth, imageHeight);
135         }
136       }
137 #endif
138 #ifdef DALI_ANIMATED_WEBP_ENABLED
139       if(mIsAnimatedImage)
140       {
141         WebPAnimDecoderOptions webPAnimDecoderOptions;
142         WebPAnimDecoderOptionsInit(&webPAnimDecoderOptions);
143         webPAnimDecoderOptions.color_mode = MODE_RGBA;
144         mWebPAnimDecoder                  = WebPAnimDecoderNew(&mWebPData, &webPAnimDecoderOptions);
145         WebPAnimDecoderGetInfo(mWebPAnimDecoder, &mWebPAnimInfo);
146         mTimeStamp.assign(mWebPAnimInfo.frame_count, 0);
147         mFrameCount = mWebPAnimInfo.frame_count;
148         mImageSize  = ImageDimensions(mWebPAnimInfo.canvas_width, mWebPAnimInfo.canvas_height);
149       }
150 #endif
151       mLoadSucceeded = true;
152     }
153     else
154     {
155       mFrameCount    = 0u;
156       mLoadSucceeded = false;
157       DALI_LOG_ERROR("Image loading failed for: \"%s\".\n", mUrl.c_str());
158     }
159
160     return mLoadSucceeded;
161   }
162
163   bool ReadWebPInformation()
164   {
165     mBufferSize = 0;
166
167     FILE*                                           fp = mFile;
168     std::unique_ptr<Internal::Platform::FileReader> fileReader;
169     Dali::Vector<uint8_t>                           dataBuffer;
170     if(fp == nullptr)
171     {
172       if(mIsLocalResource)
173       {
174         fileReader = std::make_unique<Internal::Platform::FileReader>(mUrl);
175       }
176       else
177       {
178         size_t dataSize;
179         if(DALI_LIKELY(TizenPlatform::Network::DownloadRemoteFileIntoMemory(mUrl, dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE)))
180         {
181           mBufferSize = dataBuffer.Size();
182           if(DALI_LIKELY(mBufferSize > 0U))
183           {
184             // Open a file handle on the memory buffer:
185             fileReader = std::make_unique<Internal::Platform::FileReader>(dataBuffer, mBufferSize);
186           }
187         }
188       }
189
190       if(fileReader)
191       {
192         fp = fileReader->GetFile();
193       }
194     }
195
196     if(DALI_LIKELY(fp != nullptr))
197     {
198       if(mBufferSize == 0)
199       {
200         if(DALI_UNLIKELY(fseek(fp, 0, SEEK_END) <= -1))
201         {
202           return false;
203         }
204         mBufferSize = ftell(fp);
205       }
206
207       if(DALI_LIKELY(!fseek(fp, 0, SEEK_SET)))
208       {
209         mBuffer     = reinterpret_cast<WebPByteType*>(malloc(sizeof(WebPByteType) * mBufferSize));
210         mBufferSize = fread(mBuffer, sizeof(WebPByteType), mBufferSize, fp);
211         return true;
212       }
213     }
214     return false;
215   }
216
217   void ReleaseResource()
218   {
219 #ifdef DALI_WEBP_AVAILABLE
220     if(&mWebPData != nullptr)
221     {
222       mWebPData.bytes = nullptr;
223       WebPDataInit(&mWebPData);
224     }
225 #endif
226 #ifdef DALI_ANIMATED_WEBP_ENABLED
227     if(mIsAnimatedImage)
228     {
229       if(mWebPAnimDecoder != nullptr)
230       {
231         WebPAnimDecoderDelete(mWebPAnimDecoder);
232         mWebPAnimDecoder = nullptr;
233       }
234     }
235 #endif
236     if(mBuffer != nullptr)
237     {
238       free((void*)mBuffer);
239       mBuffer = nullptr;
240     }
241
242     mLoadSucceeded = false;
243   }
244
245   // Moveable but not copyable
246
247   Impl(const Impl&) = delete;
248   Impl& operator=(const Impl&) = delete;
249   Impl(Impl&&)                 = default;
250   Impl& operator=(Impl&&) = default;
251
252   ~Impl()
253   {
254     ReleaseResource();
255   }
256
257   FILE*                 mFile;
258   std::string           mUrl;
259   std::vector<uint32_t> mTimeStamp;
260   int32_t               mLatestLoadedFrame{INITIAL_INDEX};
261   uint32_t              mFrameCount;
262   Mutex                 mMutex;
263   // For the case the system doesn't support DALI_ANIMATED_WEBP_ENABLED
264   unsigned char*  mBuffer;
265   uint32_t        mBufferSize;
266   ImageDimensions mImageSize;
267   bool            mLoadSucceeded;
268   bool            mIsAnimatedImage;
269   bool            mIsLocalResource;
270
271 #ifdef DALI_WEBP_AVAILABLE
272   WebPData mWebPData{0};
273 #endif
274
275 #ifdef DALI_ANIMATED_WEBP_ENABLED
276   WebPAnimDecoder*         mWebPAnimDecoder{nullptr};
277   WebPAnimInfo             mWebPAnimInfo{0};
278   Dali::Devel::PixelBuffer mPreLoadedFrame{};
279 #endif
280 };
281
282 AnimatedImageLoadingPtr WebPLoading::New(const std::string& url, bool isLocalResource)
283 {
284 #ifndef DALI_ANIMATED_WEBP_ENABLED
285   DALI_LOG_ERROR("The system does not support Animated WebP format.\n");
286 #endif
287   return AnimatedImageLoadingPtr(new WebPLoading(url, isLocalResource));
288 }
289
290 AnimatedImageLoadingPtr WebPLoading::New(FILE* const fp)
291 {
292 #ifndef DALI_ANIMATED_WEBP_ENABLED
293   DALI_LOG_ERROR("The system does not support Animated WebP format.\n");
294 #endif
295   return AnimatedImageLoadingPtr(new WebPLoading(fp));
296 }
297
298 WebPLoading::WebPLoading(const std::string& url, bool isLocalResource)
299 : mImpl(new WebPLoading::Impl(url, isLocalResource))
300 {
301 }
302
303 WebPLoading::WebPLoading(FILE* const fp)
304 : mImpl(new WebPLoading::Impl(fp))
305 {
306 }
307
308 WebPLoading::~WebPLoading()
309 {
310   delete mImpl;
311 }
312
313 Dali::Devel::PixelBuffer WebPLoading::LoadFrame(uint32_t frameIndex)
314 {
315   Dali::Devel::PixelBuffer pixelBuffer;
316
317   // If WebP file is still not loaded, Load the information.
318   if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
319   {
320     if(DALI_UNLIKELY(!mImpl->LoadWebPInformation()))
321     {
322       mImpl->ReleaseResource();
323       return pixelBuffer;
324     }
325   }
326
327   // WebPDecodeRGBA is faster than to use demux API for loading non-animated image.
328   // If frame count is 1, use WebPDecodeRGBA api.
329 #ifdef DALI_WEBP_AVAILABLE
330   if(!mImpl->mIsAnimatedImage)
331   {
332     int32_t width, height;
333     if(DALI_LIKELY(WebPGetInfo(mImpl->mBuffer, mImpl->mBufferSize, &width, &height)))
334     {
335       WebPBitstreamFeatures features;
336       if(DALI_LIKELY(VP8_STATUS_NOT_ENOUGH_DATA != WebPGetFeatures(mImpl->mBuffer, mImpl->mBufferSize, &features)))
337       {
338         uint32_t channelNumber = (features.has_alpha) ? 4 : 3;
339         uint8_t* frameBuffer   = nullptr;
340         if(channelNumber == 4)
341         {
342           frameBuffer = WebPDecodeRGBA(mImpl->mBuffer, mImpl->mBufferSize, &width, &height);
343         }
344         else
345         {
346           frameBuffer = WebPDecodeRGB(mImpl->mBuffer, mImpl->mBufferSize, &width, &height);
347         }
348
349         if(frameBuffer != nullptr)
350         {
351           Pixel::Format                     pixelFormat = (channelNumber == 4) ? Pixel::RGBA8888 : Pixel::RGB888;
352           int32_t                           bufferSize  = width * height * Dali::Pixel::GetBytesPerPixel(pixelFormat);
353           Internal::Adaptor::PixelBufferPtr internal =
354             Internal::Adaptor::PixelBuffer::New(frameBuffer, bufferSize, width, height, width, pixelFormat);
355           pixelBuffer = Devel::PixelBuffer(internal.Get());
356         }
357       }
358     }
359     // The single frame resource should be released after loading.
360     mImpl->ReleaseResource();
361   }
362 #endif
363
364 #ifdef DALI_ANIMATED_WEBP_ENABLED
365   if(mImpl->mIsAnimatedImage && mImpl->mBuffer != nullptr)
366   {
367     Mutex::ScopedLock lock(mImpl->mMutex);
368     if(DALI_LIKELY(frameIndex < mImpl->mWebPAnimInfo.frame_count && mImpl->mLoadSucceeded))
369     {
370       DALI_LOG_INFO(gWebPLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex);
371
372       if(mImpl->mPreLoadedFrame && mImpl->mLatestLoadedFrame == static_cast<int32_t>(frameIndex))
373       {
374         pixelBuffer = mImpl->mPreLoadedFrame;
375       }
376       else
377       {
378         pixelBuffer = DecodeFrame(frameIndex);
379       }
380       mImpl->mPreLoadedFrame.Reset();
381
382       // If time stamp of next frame is unknown, load a frame more to know it.
383       if(frameIndex + 1 < mImpl->mWebPAnimInfo.frame_count && mImpl->mTimeStamp[frameIndex + 1] == 0u)
384       {
385         mImpl->mPreLoadedFrame = DecodeFrame(frameIndex + 1);
386       }
387     }
388     else
389     {
390       mImpl->ReleaseResource();
391     }
392   }
393 #endif
394   return pixelBuffer;
395 }
396
397 Dali::Devel::PixelBuffer WebPLoading::DecodeFrame(uint32_t frameIndex)
398 {
399   Dali::Devel::PixelBuffer pixelBuffer;
400 #ifdef DALI_ANIMATED_WEBP_ENABLED
401   if(mImpl->mLatestLoadedFrame >= static_cast<int32_t>(frameIndex))
402   {
403     mImpl->mLatestLoadedFrame = INITIAL_INDEX;
404     WebPAnimDecoderReset(mImpl->mWebPAnimDecoder);
405   }
406
407   uint8_t* frameBuffer = nullptr;
408   int32_t  timestamp   = 0u;
409   for(; mImpl->mLatestLoadedFrame < static_cast<int32_t>(frameIndex);)
410   {
411     WebPAnimDecoderGetNext(mImpl->mWebPAnimDecoder, &frameBuffer, &timestamp);
412     mImpl->mTimeStamp[++mImpl->mLatestLoadedFrame] = timestamp;
413   }
414
415   if(frameBuffer != nullptr)
416   {
417     const int bufferSize = mImpl->mWebPAnimInfo.canvas_width * mImpl->mWebPAnimInfo.canvas_height * sizeof(uint32_t);
418     pixelBuffer          = Dali::Devel::PixelBuffer::New(mImpl->mWebPAnimInfo.canvas_width, mImpl->mWebPAnimInfo.canvas_height, Dali::Pixel::RGBA8888);
419     memcpy(pixelBuffer.GetBuffer(), frameBuffer, bufferSize);
420   }
421
422 #endif
423   return pixelBuffer;
424 }
425
426 ImageDimensions WebPLoading::GetImageSize() const
427 {
428   if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
429   {
430     mImpl->LoadWebPInformation();
431   }
432   return mImpl->mImageSize;
433 }
434
435 uint32_t WebPLoading::GetImageCount() const
436 {
437   if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
438   {
439     mImpl->LoadWebPInformation();
440   }
441   return mImpl->mFrameCount;
442 }
443
444 uint32_t WebPLoading::GetFrameInterval(uint32_t frameIndex) const
445 {
446   if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
447   {
448     DALI_LOG_ERROR("WebP file is still not loaded, this frame interval could not be correct value.\n");
449   }
450   if(frameIndex >= GetImageCount())
451   {
452     DALI_LOG_ERROR("Input frameIndex exceeded frame count of the WebP.");
453     return 0u;
454   }
455   else
456   {
457     int32_t interval = 0u;
458     if(GetImageCount() == 1u)
459     {
460       return 0u;
461     }
462     else if(frameIndex + 1 == GetImageCount())
463     {
464       // For the interval between last frame and first frame, use last interval again.
465       interval = mImpl->mTimeStamp[frameIndex] - mImpl->mTimeStamp[frameIndex - 1];
466     }
467     else
468     {
469       interval = mImpl->mTimeStamp[frameIndex + 1] - mImpl->mTimeStamp[frameIndex];
470     }
471
472     if(DALI_UNLIKELY(interval < 0))
473     {
474       DALI_LOG_ERROR("This interval value is not correct, because the frame still hasn't ever been decoded.");
475       return 0u;
476     }
477     return static_cast<uint32_t>(interval);
478   }
479 }
480
481 std::string WebPLoading::GetUrl() const
482 {
483   return mImpl->mUrl;
484 }
485
486 bool WebPLoading::HasLoadingSucceeded() const
487 {
488   return mImpl->mLoadSucceeded;
489 }
490
491 } // namespace Adaptor
492
493 } // namespace Internal
494
495 } // namespace Dali