2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 * Copyright notice for the EFL:
17 * Copyright (C) EFL developers (see AUTHORS)
21 #include <dali/internal/imaging/common/gif-loading.h>
27 #include <sys/types.h>
32 #include <dali/devel-api/threading/mutex.h>
33 #include <dali/integration-api/debug.h>
34 #include <dali/internal/imaging/common/file-download.h>
35 #include <dali/internal/system/common/file-reader.h>
36 #include <dali/public-api/images/pixel-data.h>
38 #define IMG_TOO_BIG(w, h) \
39 ((static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h)) >= \
40 ((1ULL << (29 * (sizeof(void*) / 4))) - 2048))
57 #if defined(DEBUG_ENABLED)
58 Debug::Filter* gGifLoadingLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_GIF_LOADING");
61 const int IMG_MAX_SIZE = 65000;
62 constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024;
64 constexpr int LOCAL_CACHED_COLOR_GENERATE_THRESHOLD = 64; ///< Generate color map optimize only if colorCount * threshold < width * height, So we don't loop if image is small
67 const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
68 const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
80 dispose(DISPOSE_BACKGROUND),
86 unsigned short delay; // delay time in 1/100ths of a sec
87 short transparent : 10; // -1 == not, anything else == index
88 short dispose : 6; // 0, 1, 2, 3 (others invalid)
89 short interlace : 1; // interlaced or not
106 // De-allocate memory of the frame data.
113 uint32_t* data; /* frame decoding data */
114 FrameInfo info; /* special image type info */
118 struct GifAnimationData
129 std::vector<ImageFrame> frames;
136 struct GifCachedColorData
138 GifCachedColorData() = default;
140 // precalculated colormap table
141 std::vector<std::uint32_t> globalCachedColor{};
142 std::vector<std::uint32_t> localCachedColor{};
145 // Forward declaration
160 isLocalResource(true)
176 bool LoadLocalFile();
177 bool LoadRemoteFile();
180 const char* fileName; /**< The absolute path of the file. */
181 unsigned char* globalMap; /**< A pointer to the entire contents of the file */
182 long long length; /**< The length of the file in bytes. */
183 bool isLocalResource; /**< The flag whether the file is a local resource */
196 int position, length; // yes - gif uses ints for file sizes.
200 GifAnimationData animated;
201 GifCachedColorData cachedColor;
202 std::unique_ptr<GifAccessor> gifAccessor{nullptr};
207 struct ImageProperties
215 * Class to access gif open/close using riaa
221 * @param[in,out] fileInfo Contains ptr to memory, and is updated by DGifOpen
223 GifAccessor(LoaderInfo::FileInfo& fileInfo)
225 // actually ask libgif to open the file
226 #if GIFLIB_MAJOR >= 5
227 gif = DGifOpen(&fileInfo, FileRead, NULL);
229 gif = DGifOpen(&fileInfo, FileRead);
234 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
242 #if(GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
243 DGifCloseFile(gif, NULL);
251 * @brief Copy data from gif file into buffer.
253 * @param[in] gifFileType A pointer pointing to GIF File Type
254 * @param[out] buffer A pointer to buffer containing GIF raw data
255 * @param[in] len The length in bytes to be copied
256 * @return The data length of the image in bytes
258 static int FileRead(GifFileType* gifFileType, GifByteType* buffer, int length)
260 LoaderInfo::FileInfo* fi = reinterpret_cast<LoaderInfo::FileInfo*>(gifFileType->UserData);
262 if(DALI_UNLIKELY(fi->position >= fi->length))
264 return 0; // if at or past end - no
266 if((fi->position + length) >= fi->length)
268 length = fi->length - fi->position;
270 memcpy(buffer, fi->map + fi->position, length);
271 fi->position += length;
275 GifFileType* gif = nullptr;
278 bool LoaderInfo::FileData::LoadFile()
280 bool success = false;
283 success = LoadLocalFile();
287 success = LoadRemoteFile();
292 bool LoaderInfo::FileData::LoadLocalFile()
294 Internal::Platform::FileReader fileReader(fileName);
295 FILE* fp = fileReader.GetFile();
296 if(DALI_UNLIKELY(fp == NULL))
301 if(DALI_UNLIKELY(fseek(fp, 0, SEEK_END) <= -1))
307 if(DALI_UNLIKELY(length <= -1))
312 if(DALI_LIKELY(!fseek(fp, 0, SEEK_SET)))
314 globalMap = reinterpret_cast<GifByteType*>(malloc(sizeof(GifByteType) * length));
315 length = fread(globalMap, sizeof(GifByteType), length, fp);
324 bool LoaderInfo::FileData::LoadRemoteFile()
327 bool succeeded = false;
328 Dali::Vector<uint8_t> dataBuffer;
331 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory(fileName, dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE);
332 if(DALI_LIKELY(succeeded))
334 size_t blobSize = dataBuffer.Size();
335 if(DALI_LIKELY(blobSize > 0U))
337 // Open a file handle on the memory buffer:
338 Dali::Internal::Platform::FileReader fileReader(dataBuffer, blobSize);
339 FILE* const fp = fileReader.GetFile();
340 if(DALI_LIKELY(NULL != fp))
342 if(DALI_LIKELY(!fseek(fp, 0, SEEK_SET)))
344 globalMap = reinterpret_cast<GifByteType*>(malloc(sizeof(GifByteType) * blobSize));
345 length = fread(globalMap, sizeof(GifByteType), blobSize, fp);
350 DALI_LOG_ERROR("Error seeking within file\n");
355 DALI_LOG_ERROR("Error reading file\n");
364 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
366 * @param[in] animated A structure containing GIF animation data
367 * @param[in] index Frame index to be searched in GIF
368 * @return single 32-bit (ABGR) value.
370 inline std::uint32_t CombinePixelABGR(const std::uint32_t& a, const std::uint32_t& r, const std::uint32_t& g, const std::uint32_t& b)
372 return (((a) << 24) + ((b) << 16) + ((g) << 8) + (r));
375 inline std::uint32_t PixelLookup(const ColorMapObject* const& colorMap, int index)
377 return CombinePixelABGR(0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue);
381 * @brief Get the Background Color from frameInfo
383 * @param[in] gif A pointer pointing to GIF File Type
384 * @param[in] frameInfo A pointer pointing to Frame Information data
385 * @return single 32-bit (ABGR) value. of background color
387 std::uint32_t GetBackgroundColor(GifFileType* gif, FrameInfo* frameInfo)
389 if(frameInfo->transparent < 0)
391 ColorMapObject* colorMap;
394 // work out color to use from colorMap
395 if(gif->Image.ColorMap)
397 colorMap = gif->Image.ColorMap;
401 colorMap = gif->SColorMap;
403 backGroundColor = gif->SBackGroundColor;
404 // Get background color from colormap
405 return PixelLookup(colorMap, backGroundColor);
415 * @brief Brute force find frame index - gifs are normally small so ok for now.
417 * @param[in] animated A structure containing GIF animation data
418 * @param[in] index Frame index to be searched in GIF
419 * @return A pointer to the ImageFrame.
421 ImageFrame* FindFrame(const GifAnimationData& animated, int index)
423 for(auto&& elem : animated.frames)
425 if(elem.index == index)
427 return const_cast<ImageFrame*>(&elem);
434 * @brief Fill in an image with a specific rgba color value.
436 * @param[in] data A pointer pointing to an image data
437 * @param[in] stride A int containing the number of stride in an image
438 * @param[in] val A uint32_t containing rgba color value
439 * @param[in] x X-coordinate used an offset to calculate pixel position
440 * @param[in] y Y-coordinate used an offset to calculate pixel position
441 * @param[in] width Width of the image
442 * @param[in] height Height of the image
444 void FillImage(uint32_t* data, int stride, uint32_t val, int x, int y, int width, int height)
446 uint32_t* pixelPosition;
448 // Boost time if stride == width and x == 0. We can assume that all pointer is continuous.
449 if(x == 0 && stride == width)
451 pixelPosition = data + (y * stride);
452 // Clear as white or transparent
453 // Special case. we can use memset.
454 if(val == 0x00 || val == 0xffffffffu)
456 const std::int8_t setupVal = val & 0xff;
457 memset(pixelPosition, setupVal, width * height * sizeof(std::uint32_t));
461 for(int byteCount = 0; byteCount < width * height; ++byteCount)
463 *pixelPosition = val;
470 for(int yAxis = 0; yAxis < height; ++yAxis)
472 pixelPosition = data + ((y + yAxis) * stride) + x;
473 for(int xAxis = 0; xAxis < width; ++xAxis)
475 *pixelPosition = val;
483 * @brief Store common fields from gif file info into frame info
485 * @param[in] gif A pointer pointing to GIF File Type
486 * @param[in] frameInfo A pointer pointing to Frame Information data
488 void StoreFrameInfo(GifFileType* gif, FrameInfo* frameInfo)
490 frameInfo->x = gif->Image.Left;
491 frameInfo->y = gif->Image.Top;
492 frameInfo->w = gif->Image.Width;
493 frameInfo->h = gif->Image.Height;
494 frameInfo->interlace = gif->Image.Interlace;
498 * @brief Check if image fills "screen space" and if so, if it is transparent
499 * at all then the image could be transparent - OR if image doesnt fill,
500 * then it could be trasnparent (full coverage of screen). Some gifs will
501 * be recognized as solid here for faster rendering, but not all.
503 * @param[out] full A boolean to show whether image is transparent or not
504 * @param[in] frameInfo A pointer pointing to Frame Information data
505 * @param[in] width Width of the image
506 * @param[in] height Height of the image
508 void CheckTransparency(bool& full, FrameInfo* frameInfo, int width, int height)
510 if((frameInfo->x == 0) && (frameInfo->y == 0) &&
511 (frameInfo->w == width) && (frameInfo->h == height))
513 if(frameInfo->transparent >= 0)
525 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
527 void ClipCoordinates(int imageWidth, int imageHeight, int* xin, int* yin, int x0, int y0, int w0, int h0, int* x, int* y, int* w, int* h)
535 if((x0 + w0) > imageWidth)
537 w0 = imageWidth - x0;
545 if((y0 + h0) > imageHeight)
547 h0 = imageHeight - y0;
556 * @brief Flush out rgba frame images to save memory but skip current,
557 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
559 * @param[in] animated A structure containing GIF animation data
560 * @param[in] width Width of the image
561 * @param[in] height Height of the image
562 * @param[in] thisframe The current frame
563 * @param[in] prevframe The previous frame
564 * @param[in] lastPreservedFrame The last preserved frame
566 void FlushFrames(GifAnimationData& animated, int width, int height, ImageFrame* thisframe, ImageFrame* prevframe, ImageFrame* lastPreservedFrame)
568 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n");
570 // target is the amount of memory we want to be under for stored frames
571 int total = 0, target = 512 * 1024;
573 // total up the amount of memory used by stored frames for this image
574 for(auto&& frame : animated.frames)
581 total *= (width * height * sizeof(uint32_t));
583 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total);
585 // If we use more than target (512k) for frames - flush
588 // Clean frames (except current and previous) until below target
589 for(auto&& frame : animated.frames)
591 if((frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
592 (!lastPreservedFrame || frame.index != lastPreservedFrame->index))
594 if(frame.data != nullptr)
597 frame.data = nullptr;
599 // subtract memory used and if below target - stop flush
600 total -= (width * height * sizeof(uint32_t));
610 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n");
614 * @brief allocate frame and frame info and append to list and store fields.
616 * @param[in] animated A structure containing GIF animation data
617 * @param[in] transparent Transparent index of the new frame
618 * @param[in] dispose Dispose mode of new frame
619 * @param[in] delay The frame delay of new frame
620 * @param[in] index The index of new frame
622 FrameInfo* NewFrame(GifAnimationData& animated, int transparent, int dispose, int delay, int index)
626 // record transparent index to be used or -1 if none
627 // for this SPECIFIC frame
628 frame.info.transparent = transparent;
629 // record dispose mode (3 bits)
630 frame.info.dispose = dispose;
631 // record delay (2 bytes so max 65546 /100 sec)
632 frame.info.delay = delay;
633 // record the index number we are at
635 // that frame is stored AT image/screen size
637 animated.frames.push_back(frame);
639 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size());
641 return &(animated.frames.back().info);
645 * @brief Decode a gif image into rows then expand to 32bit into the destination
648 bool DecodeImage(GifFileType* gif, GifCachedColorData& gifCachedColor, uint32_t* data, int rowpix, int xin, int yin, int transparent, int x, int y, int w, int h, bool fill, uint32_t fillColor = 0u)
650 int intoffset[] = {0, 4, 2, 1};
651 int intjump[] = {8, 8, 4, 2};
652 int i, xx, yy, pix, gifW, gifH;
653 GifRowType* rows = NULL;
655 ColorMapObject* colorMap;
658 // cached color data.
659 const std::uint32_t* cachedColorPtr = nullptr;
661 // what we need is image size.
663 sp = &gif->SavedImages[gif->ImageCount - 1];
665 gifW = sp->ImageDesc.Width;
666 gifH = sp->ImageDesc.Height;
668 if(DALI_UNLIKELY((gifW < w) || (gifH < h)))
670 DALI_LOG_ERROR("gifW : %d, w : %d, gifH : %d, h : %d\n", gifW, w, gifH, h);
671 DALI_ASSERT_DEBUG(false && "Dimensions are bigger than the Gif image size");
675 // build a blob of memory to have pointers to rows of pixels
676 // AND store the decoded gif pixels (1 byte per pixel) as welll
677 rows = static_cast<GifRowType*>(malloc((gifH * sizeof(GifRowType)) + (gifW * gifH * sizeof(GifPixelType))));
678 if(DALI_UNLIKELY(!rows))
683 // fill in the pointers at the start
684 for(yy = 0; yy < gifH; yy++)
686 rows[yy] = reinterpret_cast<unsigned char*>(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType));
689 // if gif is interlaced, walk interlace pattern and decode into rows
690 if(gif->Image.Interlace)
692 for(i = 0; i < 4; i++)
694 for(yy = intoffset[i]; yy < gifH; yy += intjump[i])
696 if(DALI_UNLIKELY(DGifGetLine(gif, rows[yy], gifW) != GIF_OK))
703 // normal top to bottom - decode into rows
706 for(yy = 0; yy < gifH; yy++)
708 if(DALI_UNLIKELY(DGifGetLine(gif, rows[yy], gifW) != GIF_OK))
715 // work out what colormap to use
716 if(gif->Image.ColorMap)
718 colorMap = gif->Image.ColorMap;
719 // if w * h is big enough, generate local cached color.
720 if(colorMap->ColorCount * LOCAL_CACHED_COLOR_GENERATE_THRESHOLD < w * h)
722 gifCachedColor.localCachedColor.resize(colorMap->ColorCount);
723 for(i = 0; i < colorMap->ColorCount; ++i)
725 gifCachedColor.localCachedColor[i] = PixelLookup(colorMap, i);
728 cachedColorPtr = gifCachedColor.localCachedColor.data();
733 colorMap = gif->SColorMap;
734 cachedColorPtr = gifCachedColor.globalCachedColor.data();
737 // HARD-CODING optimize
738 // if we need to deal with transparent pixels at all...
741 // if we are told to FILL (overwrite with transparency kept)
744 // if we use cachedColor, use it
747 for(yy = 0; yy < h; yy++)
749 p = data + ((y + yy) * rowpix) + x;
750 for(xx = 0; xx < w; xx++)
752 pix = rows[yin + yy][xin + xx];
753 if(pix != transparent)
755 *p = cachedColorPtr[pix];
765 // we don't have cachedColor. use PixelLookup function.
768 for(yy = 0; yy < h; yy++)
770 p = data + ((y + yy) * rowpix) + x;
771 for(xx = 0; xx < w; xx++)
773 pix = rows[yin + yy][xin + xx];
774 if(pix != transparent)
776 *p = PixelLookup(colorMap, pix);
787 // paste on top with transparent pixels untouched
790 // if we use cachedColor, use it
793 for(yy = 0; yy < h; yy++)
795 p = data + ((y + yy) * rowpix) + x;
796 for(xx = 0; xx < w; xx++)
798 pix = rows[yin + yy][xin + xx];
799 if(pix != transparent)
801 *p = cachedColorPtr[pix];
807 // we don't have cachedColor. use PixelLookup function.
810 for(yy = 0; yy < h; yy++)
812 p = data + ((y + yy) * rowpix) + x;
813 for(xx = 0; xx < w; xx++)
815 pix = rows[yin + yy][xin + xx];
816 if(pix != transparent)
818 *p = PixelLookup(colorMap, pix);
828 // if we use cachedColor, use it
831 // walk pixels without worring about transparency at all
832 for(yy = 0; yy < h; yy++)
834 p = data + ((y + yy) * rowpix) + x;
835 for(xx = 0; xx < w; xx++)
837 pix = rows[yin + yy][xin + xx];
838 *p = cachedColorPtr[pix];
843 // we don't have cachedColor. use PixelLookup function.
846 // walk pixels without worring about transparency at all
847 for(yy = 0; yy < h; yy++)
849 p = data + ((y + yy) * rowpix) + x;
850 for(xx = 0; xx < w; xx++)
852 pix = rows[yin + yy][xin + xx];
853 *p = PixelLookup(colorMap, pix);
870 * @brief Reader header from the gif file and populates structures accordingly.
872 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
873 * @param[out] prop A ImageProperties structure for storing information about GIF data.
874 * @return The true or false whether reading was successful or not.
876 bool ReadHeader(LoaderInfo& loaderInfo,
877 ImageProperties& prop)
879 GifAnimationData& animated = loaderInfo.animated;
880 GifCachedColorData& cachedColor = loaderInfo.cachedColor;
881 LoaderInfo::FileData& fileData = loaderInfo.fileData;
882 bool success = false;
883 LoaderInfo::FileInfo fileInfo;
886 // it is possible which gif file have error midle of frames,
887 // in that case we should play gif file until meet error frame.
890 FrameInfo* frameInfo = NULL;
893 success = fileData.LoadFile();
894 if(DALI_UNLIKELY(!success || !fileData.globalMap))
897 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
901 fileInfo.map = fileData.globalMap;
902 fileInfo.length = fileData.length;
903 fileInfo.position = 0;
904 GifAccessor gifAccessor(fileInfo);
908 // get the gif "screen size" (the actual image size)
909 prop.w = gifAccessor.gif->SWidth;
910 prop.h = gifAccessor.gif->SHeight;
912 // if size is invalid - abort here
913 if(DALI_UNLIKELY((prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h)))
915 if(IMG_TOO_BIG(prop.w, prop.h))
918 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
923 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
928 // walk through gif records in file to figure out info
932 if(DGifGetRecordType(gifAccessor.gif, &rec) == GIF_ERROR)
934 // if we have a gif that ends part way through a sequence
935 // (or animation) consider it valid and just break - no error
943 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
948 // get image description section
949 if(rec == IMAGE_DESC_RECORD_TYPE)
955 if(DALI_UNLIKELY(DGifGetImageDesc(gifAccessor.gif) == GIF_ERROR))
958 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
961 // skip decoding and just walk image to next
962 if(DALI_UNLIKELY(DGifGetCode(gifAccessor.gif, &img_code, &img) == GIF_ERROR))
965 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
972 DGifGetCodeNext(gifAccessor.gif, &img);
974 // store geometry in the last frame info data
977 StoreFrameInfo(gifAccessor.gif, frameInfo);
978 CheckTransparency(full, frameInfo, prop.w, prop.h);
980 // or if we dont have a frameInfo entry - create one even for stills
983 // allocate and save frame with field data
984 frameInfo = NewFrame(animated, -1, 0, 0, imageNumber + 1);
985 if(DALI_UNLIKELY(!frameInfo))
988 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
991 // store geometry info from gif image
992 StoreFrameInfo(gifAccessor.gif, frameInfo);
993 // check for transparency/alpha
994 CheckTransparency(full, frameInfo, prop.w, prop.h);
998 // we have an extension code block - for animated gifs for sure
999 else if(rec == EXTENSION_RECORD_TYPE)
1002 GifByteType* ext = NULL;
1004 // get the first extension entry
1005 DGifGetExtension(gifAccessor.gif, &ext_code, &ext);
1008 // graphic control extension - for animated gif data
1009 // and transparent index + flag
1010 if(ext_code == 0xf9)
1012 // create frame and store it in image
1013 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
1014 int disposeMode = (ext[1] >> 2) & 0x7;
1015 int delay = (int(ext[3]) << 8) | int(ext[2]);
1016 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
1017 if(DALI_UNLIKELY(!frameInfo))
1020 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1024 // netscape extension indicating loop count.
1025 else if(ext_code == 0xff) /* application extension */
1027 if(!strncmp(reinterpret_cast<char*>(&ext[1]), "NETSCAPE2.0", 11) ||
1028 !strncmp(reinterpret_cast<char*>(&ext[1]), "ANIMEXTS1.0", 11))
1031 DGifGetExtensionNext(gifAccessor.gif, &ext);
1034 loopCount = (int(ext[3]) << 8) | int(ext[2]);
1043 // and continue onto the next extension entry
1045 DGifGetExtensionNext(gifAccessor.gif, &ext);
1048 } while(rec != TERMINATE_RECORD_TYPE && success);
1052 // if the gif main says we have more than one image or our image counting
1053 // says so, then this image is animated - indicate this
1054 if((gifAccessor.gif->ImageCount > 1) || (imageNumber > 1))
1056 animated.animated = 1;
1057 animated.loopCount = loopCount;
1059 animated.frameCount = std::min(gifAccessor.gif->ImageCount, imageNumber);
1066 animated.currentFrame = 1;
1068 // cache global color map
1069 ColorMapObject* colorMap = gifAccessor.gif->SColorMap;
1072 cachedColor.globalCachedColor.resize(colorMap->ColorCount);
1073 for(int i = 0; i < colorMap->ColorCount; ++i)
1075 cachedColor.globalCachedColor[i] = PixelLookup(colorMap, i);
1086 * @brief Reader next frame of the gif file and populates structures accordingly.
1088 * @param[in,out] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
1089 * @param[in,out] prop A ImageProperties structure containing information about gif data.
1090 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
1091 * @param[out] error Error code
1092 * @return The true or false whether reading was successful or not.
1094 bool ReadNextFrame(LoaderInfo& loaderInfo, ImageProperties& prop, // use for w and h
1095 unsigned char* pixels,
1098 GifAnimationData& animated = loaderInfo.animated;
1099 LoaderInfo::FileData& fileData = loaderInfo.fileData;
1102 int index = 0, imageNumber = 0;
1103 FrameInfo* frameInfo;
1104 ImageFrame* frame = NULL;
1105 ImageFrame* lastPreservedFrame = NULL;
1107 index = animated.currentFrame;
1109 // if index is invalid for animated image - error out
1110 if(DALI_UNLIKELY((animated.animated) && ((index <= 0) || (index > animated.frameCount))))
1112 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
1116 // find the given frame index
1117 frame = FindFrame(animated, index);
1118 if(DALI_UNLIKELY(!frame))
1120 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1123 else if(!(frame->loaded) || !(frame->data))
1125 // if we want to go backwards, we likely need/want to re-decode from the
1126 // start as we have nothing to build on. If there is a gif, imageNumber
1127 // has been set already.
1128 if(loaderInfo.gifAccessor && loaderInfo.imageNumber > 0)
1130 if((index > 0) && (index < loaderInfo.imageNumber) && (animated.animated))
1132 loaderInfo.gifAccessor.reset();
1133 loaderInfo.imageNumber = 0;
1137 // actually ask libgif to open the file
1138 if(!loaderInfo.gifAccessor)
1140 loaderInfo.fileInfo.map = fileData.globalMap;
1141 loaderInfo.fileInfo.length = fileData.length;
1142 loaderInfo.fileInfo.position = 0;
1143 if(DALI_UNLIKELY(!loaderInfo.fileInfo.map))
1145 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1148 std::unique_ptr<GifAccessor> gifAccessor = std::make_unique<GifAccessor>(loaderInfo.fileInfo);
1149 if(DALI_UNLIKELY(!gifAccessor->gif))
1151 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1154 loaderInfo.gifAccessor = std::move(gifAccessor);
1155 loaderInfo.imageNumber = 1;
1158 // our current position is the previous frame we decoded from the file
1159 imageNumber = loaderInfo.imageNumber;
1161 // walk through gif records in file to figure out info
1164 if(DALI_UNLIKELY(DGifGetRecordType(loaderInfo.gifAccessor->gif, &rec) == GIF_ERROR))
1166 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1170 if(rec == EXTENSION_RECORD_TYPE)
1173 GifByteType* ext = NULL;
1174 DGifGetExtension(loaderInfo.gifAccessor->gif, &ext_code, &ext);
1179 DGifGetExtensionNext(loaderInfo.gifAccessor->gif, &ext);
1182 // get image description section
1183 else if(rec == IMAGE_DESC_RECORD_TYPE)
1185 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1188 ImageFrame* previousFrame = NULL;
1189 ImageFrame* thisFrame = NULL;
1192 if(DALI_UNLIKELY(DGifGetImageDesc(loaderInfo.gifAccessor->gif) == GIF_ERROR))
1194 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1198 // get the previous frame entry AND the current one to fill in
1199 previousFrame = FindFrame(animated, imageNumber - 1);
1200 thisFrame = FindFrame(animated, imageNumber);
1202 // if we have a frame AND we're animated AND we have no data...
1203 if((thisFrame) && (!thisFrame->data) && (animated.animated))
1208 thisFrame->data = new uint32_t[prop.w * prop.h];
1210 if(DALI_UNLIKELY(!thisFrame->data))
1212 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1216 // Lazy fill background color feature.
1217 // DecodeImage function draw range is EQUAL with previous FillImage range,
1218 // We don't need to fill background that time.
1219 // It will try to reduce the number of FillImage API call
1220 // Note : We might check overlapping. But that operation looks expensive
1221 // So, just optimize only if EQUAL case.
1222 bool updateBackgroundColorLazy = false;
1223 uint32_t backgroundColor = 0u;
1229 // if we have no prior frame OR prior frame data... empty
1230 if((!previousFrame) || (!previousFrame->data))
1233 frameInfo = &(thisFrame->info);
1234 updateBackgroundColorLazy = true;
1235 backgroundColor = 0u;
1241 // we have a prior frame to copy data from...
1244 frameInfo = &(previousFrame->info);
1246 // fix coords of sub image in case it goes out...
1247 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1249 // if dispose mode is not restore - then copy pre frame
1250 if(frameInfo->dispose != DISPOSE_PREVIOUS)
1252 memcpy(thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t));
1255 // if dispose mode is "background" then fill with bg
1256 if(frameInfo->dispose == DISPOSE_BACKGROUND)
1258 updateBackgroundColorLazy = true;
1259 backgroundColor = GetBackgroundColor(loaderInfo.gifAccessor->gif, frameInfo);
1265 else if(frameInfo->dispose == DISPOSE_PREVIOUS) // GIF_DISPOSE_RESTORE
1270 // Find last preserved frame.
1271 lastPreservedFrame = FindFrame(animated, imageNumber - prevIndex);
1272 if(DALI_UNLIKELY(!lastPreservedFrame))
1274 DALI_LOG_ERROR("LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND");
1278 } while(lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS);
1280 if(lastPreservedFrame)
1282 memcpy(thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t));
1286 // now draw this frame on top
1287 frameInfo = &(thisFrame->info);
1288 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1290 if(updateBackgroundColorLazy)
1292 // If this frame's x,y,w,h is not equal with previous x,y,w,h, FillImage. else, don't fill
1293 if(prevX != x || prevY != y || prevW != w || prevH != h)
1295 FillImage(thisFrame->data, prop.w, backgroundColor, prevX, prevY, prevW, prevH);
1296 // Don't send background color information to DecodeImage function.
1297 updateBackgroundColorLazy = false;
1300 if(DALI_UNLIKELY(!DecodeImage(loaderInfo.gifAccessor->gif, loaderInfo.cachedColor, thisFrame->data, prop.w, xin, yin, frameInfo->transparent, x, y, w, h, first || updateBackgroundColorLazy, backgroundColor)))
1302 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1306 // mark as loaded and done
1307 thisFrame->loaded = true;
1309 FlushFrames(animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame);
1311 // if we have a frame BUT the image is not animated. different
1313 else if((thisFrame) && (!thisFrame->data) && (!animated.animated))
1315 // if we don't have the data decoded yet - decode it
1316 if((!thisFrame->loaded) || (!thisFrame->data))
1318 // use frame info but we WONT allocate frame pixels
1319 frameInfo = &(thisFrame->info);
1320 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1322 // clear out all pixels only if x,y,w,h is not whole image.
1323 if(x != 0 || y != 0 || w != static_cast<int>(prop.w) || h != static_cast<int>(prop.h))
1325 const std::uint32_t backgroundColor = GetBackgroundColor(loaderInfo.gifAccessor->gif, frameInfo);
1326 FillImage(reinterpret_cast<uint32_t*>(pixels), prop.w, backgroundColor, 0, 0, prop.w, prop.h);
1329 // and decode the gif with overwriting
1330 if(DALI_UNLIKELY(!DecodeImage(loaderInfo.gifAccessor->gif, loaderInfo.cachedColor, reinterpret_cast<uint32_t*>(pixels), prop.w, xin, yin, frameInfo->transparent, x, y, w, h, true, 0u)))
1332 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1336 // mark as loaded and done
1337 thisFrame->loaded = true;
1339 // flush mem we don't need (at expense of decode cpu)
1343 // skip decoding and just walk image to next
1344 if(DALI_UNLIKELY(DGifGetCode(loaderInfo.gifAccessor->gif, &img_code, &img) == GIF_ERROR))
1346 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1353 DGifGetCodeNext(loaderInfo.gifAccessor->gif, &img);
1358 // if we found the image we wanted - get out of here
1359 if(imageNumber > index)
1364 } while(rec != TERMINATE_RECORD_TYPE);
1366 // if we are at the end of the animation or not animated, close file
1367 loaderInfo.imageNumber = imageNumber;
1368 if((animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE))
1370 loaderInfo.gifAccessor.reset();
1371 loaderInfo.imageNumber = 0;
1375 // no errors in header scan etc. so set err and return value
1379 // if it was an animated image we need to copy the data to the
1380 // pixels for the image from the frame holding the data
1381 if(animated.animated && frame->data)
1383 memcpy(pixels, frame->data, prop.w * prop.h * sizeof(uint32_t));
1389 } // unnamed namespace
1391 struct GifLoading::Impl
1394 Impl(const std::string& url, bool isLocalResource)
1396 mLoadSucceeded(false),
1399 loaderInfo.gifAccessor = nullptr;
1400 loaderInfo.fileData.fileName = mUrl.c_str();
1401 loaderInfo.fileData.isLocalResource = isLocalResource;
1404 bool LoadGifInformation()
1406 // Block to do not load this file again.
1407 Mutex::ScopedLock lock(mMutex);
1408 if(DALI_LIKELY(mLoadSucceeded))
1410 return mLoadSucceeded;
1413 mLoadSucceeded = ReadHeader(loaderInfo, imageProperties);
1414 return mLoadSucceeded;
1417 // Moveable but not copyable
1418 Impl(const Impl&) = delete;
1419 Impl& operator=(const Impl&) = delete;
1420 Impl(Impl&&) = default;
1421 Impl& operator=(Impl&&) = default;
1424 LoaderInfo loaderInfo;
1425 ImageProperties imageProperties;
1426 bool mLoadSucceeded;
1430 AnimatedImageLoadingPtr GifLoading::New(const std::string& url, bool isLocalResource)
1432 return AnimatedImageLoadingPtr(new GifLoading(url, isLocalResource));
1435 GifLoading::GifLoading(const std::string& url, bool isLocalResource)
1436 : mImpl(new GifLoading::Impl(url, isLocalResource))
1440 GifLoading::~GifLoading()
1445 bool GifLoading::LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector<Dali::PixelData>& pixelData)
1450 if(DALI_UNLIKELY(!mImpl->LoadGifInformation()))
1455 Mutex::ScopedLock lock(mImpl->mMutex);
1456 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof(uint32_t);
1458 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count);
1460 for(int i = 0; i < count; ++i)
1462 auto pixelBuffer = new unsigned char[bufferSize];
1464 mImpl->loaderInfo.animated.currentFrame = 1 + ((frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount);
1466 if(ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error))
1470 pixelData.push_back(Dali::PixelData::New(pixelBuffer, bufferSize, mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY));
1479 Dali::Devel::PixelBuffer GifLoading::LoadFrame(uint32_t frameIndex)
1482 Dali::Devel::PixelBuffer pixelBuffer;
1484 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex);
1486 // If Gif file is still not loaded, Load the information.
1487 if(DALI_UNLIKELY(!mImpl->LoadGifInformation()))
1492 Mutex::ScopedLock lock(mImpl->mMutex);
1493 pixelBuffer = Dali::Devel::PixelBuffer::New(mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888);
1495 mImpl->loaderInfo.animated.currentFrame = 1 + (frameIndex % mImpl->loaderInfo.animated.frameCount);
1496 ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer.GetBuffer(), &error);
1500 pixelBuffer = Dali::Devel::PixelBuffer();
1505 ImageDimensions GifLoading::GetImageSize() const
1507 if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
1509 mImpl->LoadGifInformation();
1511 return ImageDimensions(mImpl->imageProperties.w, mImpl->imageProperties.h);
1514 uint32_t GifLoading::GetImageCount() const
1516 if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
1518 mImpl->LoadGifInformation();
1520 return mImpl->loaderInfo.animated.frameCount;
1523 uint32_t GifLoading::GetFrameInterval(uint32_t frameIndex) const
1525 if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
1527 mImpl->LoadGifInformation();
1530 uint32_t interval = 0u;
1531 if(DALI_LIKELY(mImpl->mLoadSucceeded))
1533 interval = mImpl->loaderInfo.animated.frames[frameIndex].info.delay * 10;
1538 std::string GifLoading::GetUrl() const
1543 bool GifLoading::HasLoadingSucceeded() const
1545 return mImpl->mLoadSucceeded;
1548 } // namespace Adaptor
1550 } // namespace Internal