Merge "[Tizen] Make undefined macro do not be used." into tizen_6.5
[platform/core/uifw/dali-adaptor.git] / dali / internal / imaging / common / webp-loading.cpp
1 /*
2  * Copyright (c) 2021 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
46 typedef unsigned char WebPByteType;
47
48 namespace Dali
49 {
50 namespace Internal
51 {
52 namespace Adaptor
53 {
54 namespace
55 {
56 #if defined(DEBUG_ENABLED)
57 Debug::Filter* gWebPLoadingLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_GIF_LOADING");
58 #endif
59
60 static constexpr int32_t INITIAL_INDEX               = -1;
61 static constexpr size_t  MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024;
62
63 } // namespace
64
65 struct WebPLoading::Impl
66 {
67 public:
68   Impl(const std::string& url, bool isLocalResource)
69   : mUrl(url),
70     mFrameCount(1u),
71     mMutex(),
72     mBuffer(nullptr),
73     mBufferSize(0u),
74     mImageSize(),
75     mLoadSucceeded(false),
76     mIsLocalResource(isLocalResource)
77   {
78   }
79
80   bool LoadWebPInformation()
81   {
82     // mFrameCount will be 1 if the input image is non-animated image or animated image with single frame.
83     if(ReadWebPInformation())
84     {
85       mLoadSucceeded = true;
86 #ifdef DALI_ANIMATED_WEBP_ENABLED
87       WebPDataInit(&mWebPData);
88       mWebPData.size  = mBufferSize;
89       mWebPData.bytes = mBuffer;
90       WebPAnimDecoderOptions webPAnimDecoderOptions;
91       WebPAnimDecoderOptionsInit(&webPAnimDecoderOptions);
92       webPAnimDecoderOptions.color_mode = MODE_RGBA;
93       mWebPAnimDecoder                  = WebPAnimDecoderNew(&mWebPData, &webPAnimDecoderOptions);
94       WebPAnimDecoderGetInfo(mWebPAnimDecoder, &mWebPAnimInfo);
95       mTimeStamp.assign(mWebPAnimInfo.frame_count, 0);
96       mFrameCount = mWebPAnimInfo.frame_count;
97       mImageSize  = ImageDimensions(mWebPAnimInfo.canvas_width, mWebPAnimInfo.canvas_height);
98 #elif DALI_WEBP_AVAILABLE
99       int32_t imageWidth, imageHeight;
100       if(WebPGetInfo(mBuffer, mBufferSize, &imageWidth, &imageHeight))
101       {
102         mImageSize = ImageDimensions(imageWidth, imageHeight);
103       }
104 #endif
105 #ifndef DALI_WEBP_AVAILABLE
106       // If the system doesn't support webp, loading will be failed.
107       mFrameCount    = 0u;
108       mLoadSucceeded = false;
109 #endif
110     }
111     else
112     {
113       mFrameCount    = 0u;
114       mLoadSucceeded = false;
115       DALI_LOG_ERROR("Image loading failed for: \"%s\".\n", mUrl.c_str());
116     }
117
118     return mLoadSucceeded;
119   }
120
121   bool ReadWebPInformation()
122   {
123     FILE* fp = nullptr;
124     if(mIsLocalResource)
125     {
126       Internal::Platform::FileReader fileReader(mUrl);
127       fp = fileReader.GetFile();
128       if(fp == nullptr)
129       {
130         return false;
131       }
132
133       if(fseek(fp, 0, SEEK_END) <= -1)
134       {
135         return false;
136       }
137
138       mBufferSize = ftell(fp);
139       if(!fseek(fp, 0, SEEK_SET))
140       {
141         mBuffer     = reinterpret_cast<WebPByteType*>(malloc(sizeof(WebPByteType) * mBufferSize));
142         mBufferSize = fread(mBuffer, sizeof(WebPByteType), mBufferSize, fp);
143         return true;
144       }
145     }
146     else
147     {
148       // remote file
149       bool                  succeeded;
150       Dali::Vector<uint8_t> dataBuffer;
151       size_t                dataSize;
152
153       succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory(mUrl, dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE);
154       if(succeeded)
155       {
156         mBufferSize = dataBuffer.Size();
157         if(mBufferSize > 0U)
158         {
159           // Open a file handle on the memory buffer:
160           Internal::Platform::FileReader fileReader(dataBuffer, mBufferSize);
161           fp = fileReader.GetFile();
162           if(fp != nullptr)
163           {
164             if(!fseek(fp, 0, SEEK_SET))
165             {
166               mBuffer     = reinterpret_cast<WebPByteType*>(malloc(sizeof(WebPByteType) * mBufferSize));
167               mBufferSize = fread(mBuffer, sizeof(WebPByteType), mBufferSize, fp);
168               return true;
169             }
170           }
171         }
172       }
173     }
174     return false;
175   }
176
177   void ReleaseResource()
178   {
179 #ifdef DALI_ANIMATED_WEBP_ENABLED
180     if(&mWebPData != nullptr)
181     {
182       mWebPData.bytes = nullptr;
183       WebPDataInit(&mWebPData);
184     }
185     if(mWebPAnimDecoder != nullptr)
186     {
187       WebPAnimDecoderDelete(mWebPAnimDecoder);
188       mWebPAnimDecoder = nullptr;
189     }
190 #endif
191     if(mBuffer != nullptr)
192     {
193       free((void*)mBuffer);
194       mBuffer = nullptr;
195     }
196   }
197
198   // Moveable but not copyable
199
200   Impl(const Impl&) = delete;
201   Impl& operator=(const Impl&) = delete;
202   Impl(Impl&&)                 = default;
203   Impl& operator=(Impl&&) = default;
204
205   ~Impl()
206   {
207     ReleaseResource();
208   }
209
210   std::string           mUrl;
211   std::vector<uint32_t> mTimeStamp;
212   int32_t               mLatestLoadedFrame{INITIAL_INDEX};
213   uint32_t              mFrameCount;
214   Mutex                 mMutex;
215   // For the case the system doesn't support DALI_ANIMATED_WEBP_ENABLED
216   unsigned char*  mBuffer;
217   uint32_t        mBufferSize;
218   ImageDimensions mImageSize;
219   bool            mLoadSucceeded;
220   bool            mIsLocalResource;
221
222 #ifdef DALI_ANIMATED_WEBP_ENABLED
223   WebPData                 mWebPData{0};
224   WebPAnimDecoder*         mWebPAnimDecoder{nullptr};
225   WebPAnimInfo             mWebPAnimInfo{0};
226   Dali::Devel::PixelBuffer mPreLoadedFrame{};
227 #endif
228 };
229
230 AnimatedImageLoadingPtr WebPLoading::New(const std::string& url, bool isLocalResource)
231 {
232 #ifndef DALI_ANIMATED_WEBP_ENABLED
233   DALI_LOG_ERROR("The system does not support Animated WebP format.\n");
234 #endif
235   return AnimatedImageLoadingPtr(new WebPLoading(url, isLocalResource));
236 }
237
238 WebPLoading::WebPLoading(const std::string& url, bool isLocalResource)
239 : mImpl(new WebPLoading::Impl(url, isLocalResource))
240 {
241 }
242
243 WebPLoading::~WebPLoading()
244 {
245   delete mImpl;
246 }
247
248 bool WebPLoading::LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector<Dali::PixelData>& pixelData)
249 {
250   for(int i = 0; i < count; ++i)
251   {
252     Dali::Devel::PixelBuffer pixelBuffer = LoadFrame((frameStartIndex + i) % mImpl->mFrameCount);
253     if(!pixelBuffer)
254     {
255       return false;
256     }
257
258     Dali::PixelData imageData = Devel::PixelBuffer::Convert(pixelBuffer);
259     pixelData.push_back(imageData);
260   }
261   if(pixelData.size() != static_cast<uint32_t>(count))
262   {
263     return false;
264   }
265   return true;
266 }
267
268 Dali::Devel::PixelBuffer WebPLoading::LoadFrame(uint32_t frameIndex)
269 {
270   Dali::Devel::PixelBuffer pixelBuffer;
271
272   // If WebP file is still not loaded, Load the information.
273   if(!mImpl->mLoadSucceeded)
274   {
275     if(!mImpl->LoadWebPInformation())
276     {
277       return pixelBuffer;
278     }
279   }
280
281   // WebPDecodeRGBA is faster than to use demux API for loading non-animated image.
282   // If frame count is 1, use WebPDecodeRGBA api.
283 #ifdef DALI_WEBP_AVAILABLE
284   if(mImpl->mFrameCount == 1)
285   {
286     int32_t width, height;
287     if(!WebPGetInfo(mImpl->mBuffer, mImpl->mBufferSize, &width, &height))
288     {
289       return pixelBuffer;
290     }
291
292     WebPBitstreamFeatures features;
293     if(VP8_STATUS_NOT_ENOUGH_DATA == WebPGetFeatures(mImpl->mBuffer, mImpl->mBufferSize, &features))
294     {
295       return pixelBuffer;
296     }
297
298     uint32_t      channelNumber = (features.has_alpha) ? 4 : 3;
299     Pixel::Format pixelFormat   = (channelNumber == 4) ? Pixel::RGBA8888 : Pixel::RGB888;
300     pixelBuffer                 = Dali::Devel::PixelBuffer::New(width, height, pixelFormat);
301     uint8_t* frameBuffer        = nullptr;
302     if(channelNumber == 4)
303     {
304       frameBuffer = WebPDecodeRGBA(mImpl->mBuffer, mImpl->mBufferSize, &width, &height);
305     }
306     else
307     {
308       frameBuffer = WebPDecodeRGB(mImpl->mBuffer, mImpl->mBufferSize, &width, &height);
309     }
310
311     if(frameBuffer != nullptr)
312     {
313       const int32_t imageBufferSize = width * height * sizeof(uint8_t) * channelNumber;
314       memcpy(pixelBuffer.GetBuffer(), frameBuffer, imageBufferSize);
315       free((void*)frameBuffer);
316     }
317     mImpl->ReleaseResource();
318     return pixelBuffer;
319   }
320 #endif
321
322 #ifdef DALI_ANIMATED_WEBP_ENABLED
323   Mutex::ScopedLock lock(mImpl->mMutex);
324   if(frameIndex >= mImpl->mWebPAnimInfo.frame_count || !mImpl->mLoadSucceeded)
325   {
326     return pixelBuffer;
327   }
328
329   DALI_LOG_INFO(gWebPLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex);
330
331   if(mImpl->mPreLoadedFrame && mImpl->mLatestLoadedFrame == static_cast<int32_t>(frameIndex))
332   {
333     pixelBuffer = mImpl->mPreLoadedFrame;
334   }
335   else
336   {
337     pixelBuffer = DecodeFrame(frameIndex);
338   }
339   mImpl->mPreLoadedFrame.Reset();
340
341   // If time stamp of next frame is unknown, load a frame more to know it.
342   if(frameIndex + 1 < mImpl->mWebPAnimInfo.frame_count && mImpl->mTimeStamp[frameIndex + 1] == 0u)
343   {
344     mImpl->mPreLoadedFrame = DecodeFrame(frameIndex + 1);
345   }
346
347 #endif
348   return pixelBuffer;
349 }
350
351 Dali::Devel::PixelBuffer WebPLoading::DecodeFrame(uint32_t frameIndex)
352 {
353   Dali::Devel::PixelBuffer pixelBuffer;
354 #ifdef DALI_ANIMATED_WEBP_ENABLED
355   if(mImpl->mLatestLoadedFrame >= static_cast<int32_t>(frameIndex))
356   {
357     mImpl->mLatestLoadedFrame = INITIAL_INDEX;
358     WebPAnimDecoderReset(mImpl->mWebPAnimDecoder);
359   }
360
361   int32_t timestamp;
362   uint8_t* frameBuffer = nullptr;
363   for(; mImpl->mLatestLoadedFrame < static_cast<int32_t>(frameIndex);)
364   {
365     WebPAnimDecoderGetNext(mImpl->mWebPAnimDecoder, &frameBuffer, &timestamp);
366     mImpl->mTimeStamp[++mImpl->mLatestLoadedFrame] = timestamp;
367   }
368
369   if(frameBuffer != nullptr)
370   {
371     const int bufferSize = mImpl->mWebPAnimInfo.canvas_width * mImpl->mWebPAnimInfo.canvas_height * sizeof(uint32_t);
372     pixelBuffer          = Dali::Devel::PixelBuffer::New(mImpl->mWebPAnimInfo.canvas_width, mImpl->mWebPAnimInfo.canvas_height, Dali::Pixel::RGBA8888);
373     memcpy(pixelBuffer.GetBuffer(), frameBuffer, bufferSize);
374   }
375
376 #endif
377   return pixelBuffer;
378 }
379
380 ImageDimensions WebPLoading::GetImageSize() const
381 {
382   if(!mImpl->mLoadSucceeded)
383   {
384     DALI_LOG_ERROR("WebP file is still not loaded, this image size could not be correct value.\n");
385   }
386   return mImpl->mImageSize;
387 }
388
389 uint32_t WebPLoading::GetImageCount() const
390 {
391   if(!mImpl->mLoadSucceeded)
392   {
393     DALI_LOG_ERROR("WebP file is still not loaded, this image count could not be correct value.\n");
394   }
395   return mImpl->mFrameCount;
396 }
397
398 uint32_t WebPLoading::GetFrameInterval(uint32_t frameIndex) const
399 {
400   if(!mImpl->mLoadSucceeded)
401   {
402     DALI_LOG_ERROR("WebP file is still not loaded, this frame interval could not be correct value.\n");
403   }
404   if(frameIndex >= GetImageCount())
405   {
406     DALI_LOG_ERROR("Input frameIndex exceeded frame count of the WebP.");
407     return 0u;
408   }
409   else
410   {
411     int32_t interval = 0u;
412     if(GetImageCount() == 1u)
413     {
414       return 0u;
415     }
416     else if(frameIndex + 1 == GetImageCount())
417     {
418       // For the interval between last frame and first frame, use last interval again.
419       interval = mImpl->mTimeStamp[frameIndex] - mImpl->mTimeStamp[frameIndex - 1];
420     }
421     else
422     {
423       interval = mImpl->mTimeStamp[frameIndex + 1] - mImpl->mTimeStamp[frameIndex];
424     }
425
426     if(interval < 0)
427     {
428       return 0u;
429     }
430     return static_cast<uint32_t>(interval);
431   }
432 }
433
434 std::string WebPLoading::GetUrl() const
435 {
436   return mImpl->mUrl;
437 }
438
439 bool WebPLoading::HasLoadingSucceeded() const
440 {
441   return mImpl->mLoadSucceeded;
442 }
443
444 } // namespace Adaptor
445
446 } // namespace Internal
447
448 } // namespace Dali