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 = 16; ///< 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{};
143 ColorMapObject* localCachedColorMap{nullptr}; // Weak-pointer of ColorMapObject. should be nullptr if image changed
146 // Forward declaration
161 isLocalResource(true)
177 bool LoadLocalFile();
178 bool LoadRemoteFile();
181 const char* fileName; /**< The absolute path of the file. */
182 unsigned char* globalMap; /**< A pointer to the entire contents of the file */
183 long long length; /**< The length of the file in bytes. */
184 bool isLocalResource; /**< The flag whether the file is a local resource */
197 int position, length; // yes - gif uses ints for file sizes.
201 GifAnimationData animated;
202 GifCachedColorData cachedColor;
203 std::unique_ptr<GifAccessor> gifAccessor{nullptr};
208 struct ImageProperties
216 * Class to access gif open/close using riaa
222 * @param[in,out] fileInfo Contains ptr to memory, and is updated by DGifOpen
224 GifAccessor(LoaderInfo::FileInfo& fileInfo)
226 // actually ask libgif to open the file
227 #if GIFLIB_MAJOR >= 5
228 gif = DGifOpen(&fileInfo, FileRead, NULL);
230 gif = DGifOpen(&fileInfo, FileRead);
235 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
243 #if(GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
244 DGifCloseFile(gif, NULL);
252 * @brief Copy data from gif file into buffer.
254 * @param[in] gifFileType A pointer pointing to GIF File Type
255 * @param[out] buffer A pointer to buffer containing GIF raw data
256 * @param[in] len The length in bytes to be copied
257 * @return The data length of the image in bytes
259 static int FileRead(GifFileType* gifFileType, GifByteType* buffer, int length)
261 LoaderInfo::FileInfo* fi = reinterpret_cast<LoaderInfo::FileInfo*>(gifFileType->UserData);
263 if(DALI_UNLIKELY(fi->position >= fi->length))
265 return 0; // if at or past end - no
267 if((fi->position + length) >= fi->length)
269 length = fi->length - fi->position;
271 memcpy(buffer, fi->map + fi->position, length);
272 fi->position += length;
276 GifFileType* gif = nullptr;
279 bool LoaderInfo::FileData::LoadFile()
281 bool success = false;
284 success = LoadLocalFile();
288 success = LoadRemoteFile();
293 bool LoaderInfo::FileData::LoadLocalFile()
295 Internal::Platform::FileReader fileReader(fileName);
296 FILE* fp = fileReader.GetFile();
297 if(DALI_UNLIKELY(fp == NULL))
302 if(DALI_UNLIKELY(fseek(fp, 0, SEEK_END) <= -1))
308 if(DALI_UNLIKELY(length <= -1))
313 if(DALI_LIKELY(!fseek(fp, 0, SEEK_SET)))
315 globalMap = reinterpret_cast<GifByteType*>(malloc(sizeof(GifByteType) * length));
316 length = fread(globalMap, sizeof(GifByteType), length, fp);
325 bool LoaderInfo::FileData::LoadRemoteFile()
328 bool succeeded = false;
329 Dali::Vector<uint8_t> dataBuffer;
332 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory(fileName, dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE);
333 if(DALI_LIKELY(succeeded))
335 size_t blobSize = dataBuffer.Size();
336 if(DALI_LIKELY(blobSize > 0U))
338 // Open a file handle on the memory buffer:
339 Dali::Internal::Platform::FileReader fileReader(dataBuffer, blobSize);
340 FILE* const fp = fileReader.GetFile();
341 if(DALI_LIKELY(NULL != fp))
343 if(DALI_LIKELY(!fseek(fp, 0, SEEK_SET)))
345 globalMap = reinterpret_cast<GifByteType*>(malloc(sizeof(GifByteType) * blobSize));
346 length = fread(globalMap, sizeof(GifByteType), blobSize, fp);
351 DALI_LOG_ERROR("Error seeking within file\n");
356 DALI_LOG_ERROR("Error reading file\n");
365 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
367 * @param[in] animated A structure containing GIF animation data
368 * @param[in] index Frame index to be searched in GIF
369 * @return A pointer to the ImageFrame.
371 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)
373 return (((a) << 24) + ((b) << 16) + ((g) << 8) + (r));
376 inline std::uint32_t PixelLookup(const ColorMapObject* const& colorMap, int index)
378 return CombinePixelABGR(0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue);
382 * @brief Brute force find frame index - gifs are normally small so ok for now.
384 * @param[in] animated A structure containing GIF animation data
385 * @param[in] index Frame index to be searched in GIF
386 * @return A pointer to the ImageFrame.
388 ImageFrame* FindFrame(const GifAnimationData& animated, int index)
390 for(auto&& elem : animated.frames)
392 if(elem.index == index)
394 return const_cast<ImageFrame*>(&elem);
401 * @brief Fill in an image with a specific rgba color value.
403 * @param[in] data A pointer pointing to an image data
404 * @param[in] stride A int containing the number of stride in an image
405 * @param[in] val A uint32_t containing rgba color value
406 * @param[in] x X-coordinate used an offset to calculate pixel position
407 * @param[in] y Y-coordinate used an offset to calculate pixel position
408 * @param[in] width Width of the image
409 * @param[in] height Height of the image
411 void FillImage(uint32_t* data, int stride, uint32_t val, int x, int y, int width, int height)
413 uint32_t* pixelPosition;
415 // Boost time if stride == width and x == 0. We can assume that all pointer is continuous.
416 if(x == 0 && stride == width)
418 pixelPosition = data + (y * stride);
419 // Clear as white or transparent
420 // Special case. we can use memset.
421 if(val == 0x00 || val == 0xffffffffu)
423 const std::int8_t setupVal = val & 0xff;
424 memset(pixelPosition, setupVal, width * height * sizeof(std::uint32_t));
428 for(int byteCount = 0; byteCount < width * height; ++byteCount)
430 *pixelPosition = val;
437 for(int yAxis = 0; yAxis < height; ++yAxis)
439 pixelPosition = data + ((y + yAxis) * stride) + x;
440 for(int xAxis = 0; xAxis < width; ++xAxis)
442 *pixelPosition = val;
450 * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
452 * @param[in] data A pointer pointing to an image data
453 * @param[in] stride A int containing the number of stride in an image
454 * @param[in] gif A pointer pointing to GIF File Type
455 * @param[in] frameInfo A pointer pointing to Frame Information data
456 * @param[in] x X-coordinate used an offset to calculate pixel position
457 * @param[in] y Y-coordinate used an offset to calculate pixel position
458 * @param[in] width Width of the image
459 * @param[in] height Height of the image
461 void FillFrame(uint32_t* data, int stride, GifFileType* gif, FrameInfo* frameInfo, int x, int y, int w, int h)
463 // solid color fill for pre frame region
464 if(frameInfo->transparent < 0)
466 ColorMapObject* colorMap;
469 // work out color to use from colorMap
470 if(gif->Image.ColorMap)
472 colorMap = gif->Image.ColorMap;
476 colorMap = gif->SColorMap;
478 backGroundColor = gif->SBackGroundColor;
480 FillImage(data, stride, CombinePixelABGR(0xff, colorMap->Colors[backGroundColor].Red, colorMap->Colors[backGroundColor].Green, colorMap->Colors[backGroundColor].Blue), x, y, w, h);
482 // fill in region with 0 (transparent)
485 FillImage(data, stride, 0, x, y, w, h);
490 * @brief Store common fields from gif file info into frame info
492 * @param[in] gif A pointer pointing to GIF File Type
493 * @param[in] frameInfo A pointer pointing to Frame Information data
495 void StoreFrameInfo(GifFileType* gif, FrameInfo* frameInfo)
497 frameInfo->x = gif->Image.Left;
498 frameInfo->y = gif->Image.Top;
499 frameInfo->w = gif->Image.Width;
500 frameInfo->h = gif->Image.Height;
501 frameInfo->interlace = gif->Image.Interlace;
505 * @brief Check if image fills "screen space" and if so, if it is transparent
506 * at all then the image could be transparent - OR if image doesnt fill,
507 * then it could be trasnparent (full coverage of screen). Some gifs will
508 * be recognized as solid here for faster rendering, but not all.
510 * @param[out] full A boolean to show whether image is transparent or not
511 * @param[in] frameInfo A pointer pointing to Frame Information data
512 * @param[in] width Width of the image
513 * @param[in] height Height of the image
515 void CheckTransparency(bool& full, FrameInfo* frameInfo, int width, int height)
517 if((frameInfo->x == 0) && (frameInfo->y == 0) &&
518 (frameInfo->w == width) && (frameInfo->h == height))
520 if(frameInfo->transparent >= 0)
532 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
534 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)
542 if((x0 + w0) > imageWidth)
544 w0 = imageWidth - x0;
552 if((y0 + h0) > imageHeight)
554 h0 = imageHeight - y0;
563 * @brief Flush out rgba frame images to save memory but skip current,
564 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
566 * @param[in] animated A structure containing GIF animation data
567 * @param[in] width Width of the image
568 * @param[in] height Height of the image
569 * @param[in] thisframe The current frame
570 * @param[in] prevframe The previous frame
571 * @param[in] lastPreservedFrame The last preserved frame
573 void FlushFrames(GifAnimationData& animated, int width, int height, ImageFrame* thisframe, ImageFrame* prevframe, ImageFrame* lastPreservedFrame)
575 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n");
577 // target is the amount of memory we want to be under for stored frames
578 int total = 0, target = 512 * 1024;
580 // total up the amount of memory used by stored frames for this image
581 for(auto&& frame : animated.frames)
588 total *= (width * height * sizeof(uint32_t));
590 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total);
592 // If we use more than target (512k) for frames - flush
595 // Clean frames (except current and previous) until below target
596 for(auto&& frame : animated.frames)
598 if((frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
599 (!lastPreservedFrame || frame.index != lastPreservedFrame->index))
601 if(frame.data != nullptr)
604 frame.data = nullptr;
606 // subtract memory used and if below target - stop flush
607 total -= (width * height * sizeof(uint32_t));
617 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n");
621 * @brief allocate frame and frame info and append to list and store fields.
623 * @param[in] animated A structure containing GIF animation data
624 * @param[in] transparent Transparent index of the new frame
625 * @param[in] dispose Dispose mode of new frame
626 * @param[in] delay The frame delay of new frame
627 * @param[in] index The index of new frame
629 FrameInfo* NewFrame(GifAnimationData& animated, int transparent, int dispose, int delay, int index)
633 // record transparent index to be used or -1 if none
634 // for this SPECIFIC frame
635 frame.info.transparent = transparent;
636 // record dispose mode (3 bits)
637 frame.info.dispose = dispose;
638 // record delay (2 bytes so max 65546 /100 sec)
639 frame.info.delay = delay;
640 // record the index number we are at
642 // that frame is stored AT image/screen size
644 animated.frames.push_back(frame);
646 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size());
648 return &(animated.frames.back().info);
652 * @brief Decode a gif image into rows then expand to 32bit into the destination
655 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)
657 int intoffset[] = {0, 4, 2, 1};
658 int intjump[] = {8, 8, 4, 2};
659 int i, xx, yy, pix, gifW, gifH;
660 GifRowType* rows = NULL;
662 ColorMapObject* colorMap;
665 // cached color data.
666 const std::uint32_t* cachedColorPtr = nullptr;
668 // what we need is image size.
670 sp = &gif->SavedImages[gif->ImageCount - 1];
672 gifW = sp->ImageDesc.Width;
673 gifH = sp->ImageDesc.Height;
675 if(DALI_UNLIKELY((gifW < w) || (gifH < h)))
677 DALI_LOG_ERROR("gifW : %d, w : %d, gifH : %d, h : %d\n", gifW, w, gifH, h);
678 DALI_ASSERT_DEBUG(false && "Dimensions are bigger than the Gif image size");
682 // build a blob of memory to have pointers to rows of pixels
683 // AND store the decoded gif pixels (1 byte per pixel) as welll
684 rows = static_cast<GifRowType*>(malloc((gifH * sizeof(GifRowType)) + (gifW * gifH * sizeof(GifPixelType))));
685 if(DALI_UNLIKELY(!rows))
690 // fill in the pointers at the start
691 for(yy = 0; yy < gifH; yy++)
693 rows[yy] = reinterpret_cast<unsigned char*>(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType));
696 // if gif is interlaced, walk interlace pattern and decode into rows
697 if(gif->Image.Interlace)
699 for(i = 0; i < 4; i++)
701 for(yy = intoffset[i]; yy < gifH; yy += intjump[i])
703 if(DALI_UNLIKELY(DGifGetLine(gif, rows[yy], gifW) != GIF_OK))
710 // normal top to bottom - decode into rows
713 for(yy = 0; yy < gifH; yy++)
715 if(DALI_UNLIKELY(DGifGetLine(gif, rows[yy], gifW) != GIF_OK))
722 // work out what colormap to use
723 if(gif->Image.ColorMap)
725 colorMap = gif->Image.ColorMap;
726 // use local cached color map without re-calculate cache.
727 if(gifCachedColor.localCachedColorMap == colorMap)
729 cachedColorPtr = gifCachedColor.localCachedColor.data();
731 // else if w * h is big enough, generate local cached color.
732 else if(colorMap->ColorCount * LOCAL_CACHED_COLOR_GENERATE_THRESHOLD < w * h)
734 gifCachedColor.localCachedColor.resize(colorMap->ColorCount);
735 for(i = 0; i < colorMap->ColorCount; ++i)
737 gifCachedColor.localCachedColor[i] = PixelLookup(colorMap, i);
739 gifCachedColor.localCachedColorMap = colorMap;
741 cachedColorPtr = gifCachedColor.localCachedColor.data();
746 colorMap = gif->SColorMap;
747 cachedColorPtr = gifCachedColor.globalCachedColor.data();
750 // HARD-CODING optimize
751 // if we need to deal with transparent pixels at all...
754 // if we are told to FILL (overwrite with transparency kept)
757 // if we use cachedColor, use it
760 for(yy = 0; yy < h; yy++)
762 p = data + ((y + yy) * rowpix) + x;
763 for(xx = 0; xx < w; xx++)
765 pix = rows[yin + yy][xin + xx];
766 if(pix != transparent)
768 *p = cachedColorPtr[pix];
778 // we don't have cachedColor. use PixelLookup function.
781 for(yy = 0; yy < h; yy++)
783 p = data + ((y + yy) * rowpix) + x;
784 for(xx = 0; xx < w; xx++)
786 pix = rows[yin + yy][xin + xx];
787 if(pix != transparent)
789 *p = PixelLookup(colorMap, pix);
800 // paste on top with transparent pixels untouched
803 // if we use cachedColor, use it
806 for(yy = 0; yy < h; yy++)
808 p = data + ((y + yy) * rowpix) + x;
809 for(xx = 0; xx < w; xx++)
811 pix = rows[yin + yy][xin + xx];
812 if(pix != transparent)
814 *p = cachedColorPtr[pix];
820 // we don't have cachedColor. use PixelLookup function.
823 for(yy = 0; yy < h; yy++)
825 p = data + ((y + yy) * rowpix) + x;
826 for(xx = 0; xx < w; xx++)
828 pix = rows[yin + yy][xin + xx];
829 if(pix != transparent)
831 *p = PixelLookup(colorMap, pix);
841 // if we use cachedColor, use it
844 // walk pixels without worring about transparency at all
845 for(yy = 0; yy < h; yy++)
847 p = data + ((y + yy) * rowpix) + x;
848 for(xx = 0; xx < w; xx++)
850 pix = rows[yin + yy][xin + xx];
851 *p = cachedColorPtr[pix];
856 // we don't have cachedColor. use PixelLookup function.
859 // walk pixels without worring about transparency at all
860 for(yy = 0; yy < h; yy++)
862 p = data + ((y + yy) * rowpix) + x;
863 for(xx = 0; xx < w; xx++)
865 pix = rows[yin + yy][xin + xx];
866 *p = PixelLookup(colorMap, pix);
883 * @brief Reader header from the gif file and populates structures accordingly.
885 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
886 * @param[out] prop A ImageProperties structure for storing information about GIF data.
887 * @param[out] error Error code
888 * @return The true or false whether reading was successful or not.
890 bool ReadHeader(LoaderInfo& loaderInfo,
891 ImageProperties& prop, //output struct
894 GifAnimationData& animated = loaderInfo.animated;
895 GifCachedColorData& cachedColor = loaderInfo.cachedColor;
896 LoaderInfo::FileData& fileData = loaderInfo.fileData;
897 bool success = false;
898 LoaderInfo::FileInfo fileInfo;
901 // it is possible which gif file have error midle of frames,
902 // in that case we should play gif file until meet error frame.
905 FrameInfo* frameInfo = NULL;
908 success = fileData.LoadFile();
909 if(DALI_UNLIKELY(!success || !fileData.globalMap))
912 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
916 fileInfo.map = fileData.globalMap;
917 fileInfo.length = fileData.length;
918 fileInfo.position = 0;
919 GifAccessor gifAccessor(fileInfo);
923 // get the gif "screen size" (the actual image size)
924 prop.w = gifAccessor.gif->SWidth;
925 prop.h = gifAccessor.gif->SHeight;
927 // if size is invalid - abort here
928 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)))
930 if(IMG_TOO_BIG(prop.w, prop.h))
933 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
938 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
943 // walk through gif records in file to figure out info
947 if(DGifGetRecordType(gifAccessor.gif, &rec) == GIF_ERROR)
949 // if we have a gif that ends part way through a sequence
950 // (or animation) consider it valid and just break - no error
958 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
963 // get image description section
964 if(rec == IMAGE_DESC_RECORD_TYPE)
970 if(DALI_UNLIKELY(DGifGetImageDesc(gifAccessor.gif) == GIF_ERROR))
973 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
976 // skip decoding and just walk image to next
977 if(DALI_UNLIKELY(DGifGetCode(gifAccessor.gif, &img_code, &img) == GIF_ERROR))
980 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
987 DGifGetCodeNext(gifAccessor.gif, &img);
989 // store geometry in the last frame info data
992 StoreFrameInfo(gifAccessor.gif, frameInfo);
993 CheckTransparency(full, frameInfo, prop.w, prop.h);
995 // or if we dont have a frameInfo entry - create one even for stills
998 // allocate and save frame with field data
999 frameInfo = NewFrame(animated, -1, 0, 0, imageNumber + 1);
1000 if(DALI_UNLIKELY(!frameInfo))
1003 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1006 // store geometry info from gif image
1007 StoreFrameInfo(gifAccessor.gif, frameInfo);
1008 // check for transparency/alpha
1009 CheckTransparency(full, frameInfo, prop.w, prop.h);
1013 // we have an extension code block - for animated gifs for sure
1014 else if(rec == EXTENSION_RECORD_TYPE)
1017 GifByteType* ext = NULL;
1019 // get the first extension entry
1020 DGifGetExtension(gifAccessor.gif, &ext_code, &ext);
1023 // graphic control extension - for animated gif data
1024 // and transparent index + flag
1025 if(ext_code == 0xf9)
1027 // create frame and store it in image
1028 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
1029 int disposeMode = (ext[1] >> 2) & 0x7;
1030 int delay = (int(ext[3]) << 8) | int(ext[2]);
1031 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
1032 if(DALI_UNLIKELY(!frameInfo))
1035 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1039 // netscape extension indicating loop count.
1040 else if(ext_code == 0xff) /* application extension */
1042 if(!strncmp(reinterpret_cast<char*>(&ext[1]), "NETSCAPE2.0", 11) ||
1043 !strncmp(reinterpret_cast<char*>(&ext[1]), "ANIMEXTS1.0", 11))
1046 DGifGetExtensionNext(gifAccessor.gif, &ext);
1049 loopCount = (int(ext[3]) << 8) | int(ext[2]);
1058 // and continue onto the next extension entry
1060 DGifGetExtensionNext(gifAccessor.gif, &ext);
1063 } while(rec != TERMINATE_RECORD_TYPE && success);
1067 // if the gif main says we have more than one image or our image counting
1068 // says so, then this image is animated - indicate this
1069 if((gifAccessor.gif->ImageCount > 1) || (imageNumber > 1))
1071 animated.animated = 1;
1072 animated.loopCount = loopCount;
1074 animated.frameCount = std::min(gifAccessor.gif->ImageCount, imageNumber);
1081 animated.currentFrame = 1;
1083 // cache global color map
1084 ColorMapObject* colorMap = gifAccessor.gif->SColorMap;
1087 cachedColor.globalCachedColor.resize(colorMap->ColorCount);
1088 for(int i = 0; i < colorMap->ColorCount; ++i)
1090 cachedColor.globalCachedColor[i] = PixelLookup(colorMap, i);
1093 cachedColor.localCachedColorMap = nullptr;
1095 // no errors in header scan etc. so set err and return value
1105 * @brief Reader next frame of the gif file and populates structures accordingly.
1107 * @param[in,out] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
1108 * @param[in,out] prop A ImageProperties structure containing information about gif data.
1109 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
1110 * @param[out] error Error code
1111 * @return The true or false whether reading was successful or not.
1113 bool ReadNextFrame(LoaderInfo& loaderInfo, ImageProperties& prop, // use for w and h
1114 unsigned char* pixels,
1117 GifAnimationData& animated = loaderInfo.animated;
1118 LoaderInfo::FileData& fileData = loaderInfo.fileData;
1121 int index = 0, imageNumber = 0;
1122 FrameInfo* frameInfo;
1123 ImageFrame* frame = NULL;
1124 ImageFrame* lastPreservedFrame = NULL;
1126 index = animated.currentFrame;
1128 // if index is invalid for animated image - error out
1129 if(DALI_UNLIKELY((animated.animated) && ((index <= 0) || (index > animated.frameCount))))
1131 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
1135 // find the given frame index
1136 frame = FindFrame(animated, index);
1137 if(DALI_UNLIKELY(!frame))
1139 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1142 else if(!(frame->loaded) || !(frame->data))
1144 // if we want to go backwards, we likely need/want to re-decode from the
1145 // start as we have nothing to build on. If there is a gif, imageNumber
1146 // has been set already.
1147 if(loaderInfo.gifAccessor && loaderInfo.imageNumber > 0)
1149 if((index > 0) && (index < loaderInfo.imageNumber) && (animated.animated))
1151 loaderInfo.gifAccessor.reset();
1152 loaderInfo.imageNumber = 0;
1156 // actually ask libgif to open the file
1157 if(!loaderInfo.gifAccessor)
1159 loaderInfo.fileInfo.map = fileData.globalMap;
1160 loaderInfo.fileInfo.length = fileData.length;
1161 loaderInfo.fileInfo.position = 0;
1162 if(DALI_UNLIKELY(!loaderInfo.fileInfo.map))
1164 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1167 std::unique_ptr<GifAccessor> gifAccessor = std::make_unique<GifAccessor>(loaderInfo.fileInfo);
1168 if(DALI_UNLIKELY(!gifAccessor->gif))
1170 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1173 loaderInfo.gifAccessor = std::move(gifAccessor);
1174 loaderInfo.imageNumber = 1;
1177 // our current position is the previous frame we decoded from the file
1178 imageNumber = loaderInfo.imageNumber;
1180 // walk through gif records in file to figure out info
1183 if(DALI_UNLIKELY(DGifGetRecordType(loaderInfo.gifAccessor->gif, &rec) == GIF_ERROR))
1185 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1189 if(rec == EXTENSION_RECORD_TYPE)
1192 GifByteType* ext = NULL;
1193 DGifGetExtension(loaderInfo.gifAccessor->gif, &ext_code, &ext);
1198 DGifGetExtensionNext(loaderInfo.gifAccessor->gif, &ext);
1201 // get image description section
1202 else if(rec == IMAGE_DESC_RECORD_TYPE)
1204 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1207 ImageFrame* previousFrame = NULL;
1208 ImageFrame* thisFrame = NULL;
1211 if(DALI_UNLIKELY(DGifGetImageDesc(loaderInfo.gifAccessor->gif) == GIF_ERROR))
1213 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1217 // get the previous frame entry AND the current one to fill in
1218 previousFrame = FindFrame(animated, imageNumber - 1);
1219 thisFrame = FindFrame(animated, imageNumber);
1221 // if we have a frame AND we're animated AND we have no data...
1222 if((thisFrame) && (!thisFrame->data) && (animated.animated))
1227 thisFrame->data = new uint32_t[prop.w * prop.h];
1229 if(DALI_UNLIKELY(!thisFrame->data))
1231 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1235 // if we have no prior frame OR prior frame data... empty
1236 if((!previousFrame) || (!previousFrame->data))
1239 frameInfo = &(thisFrame->info);
1240 memset(thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t));
1242 // we have a prior frame to copy data from...
1245 frameInfo = &(previousFrame->info);
1247 // fix coords of sub image in case it goes out...
1248 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1250 // if dispose mode is not restore - then copy pre frame
1251 if(frameInfo->dispose != DISPOSE_PREVIOUS)
1253 memcpy(thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t));
1256 // if dispose mode is "background" then fill with bg
1257 if(frameInfo->dispose == DISPOSE_BACKGROUND)
1259 FillFrame(thisFrame->data, prop.w, loaderInfo.gifAccessor->gif, frameInfo, x, y, w, h);
1261 else if(frameInfo->dispose == DISPOSE_PREVIOUS) // GIF_DISPOSE_RESTORE
1266 // Find last preserved frame.
1267 lastPreservedFrame = FindFrame(animated, imageNumber - prevIndex);
1268 if(DALI_UNLIKELY(!lastPreservedFrame))
1270 DALI_LOG_ERROR("LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND");
1274 } while(lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS);
1276 if(lastPreservedFrame)
1278 memcpy(thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t));
1282 // now draw this frame on top
1283 frameInfo = &(thisFrame->info);
1284 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1285 if(DALI_UNLIKELY(!DecodeImage(loaderInfo.gifAccessor->gif, loaderInfo.cachedColor, thisFrame->data, prop.w, xin, yin, frameInfo->transparent, x, y, w, h, first)))
1287 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1291 // mark as loaded and done
1292 thisFrame->loaded = true;
1294 FlushFrames(animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame);
1296 // if we have a frame BUT the image is not animated. different
1298 else if((thisFrame) && (!thisFrame->data) && (!animated.animated))
1300 // if we don't have the data decoded yet - decode it
1301 if((!thisFrame->loaded) || (!thisFrame->data))
1303 // use frame info but we WONT allocate frame pixels
1304 frameInfo = &(thisFrame->info);
1305 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1307 // clear out all pixels
1308 FillFrame(reinterpret_cast<uint32_t*>(pixels), prop.w, loaderInfo.gifAccessor->gif, frameInfo, 0, 0, prop.w, prop.h);
1310 // and decode the gif with overwriting
1311 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)))
1313 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1317 // mark as loaded and done
1318 thisFrame->loaded = true;
1320 // flush mem we don't need (at expense of decode cpu)
1324 // skip decoding and just walk image to next
1325 if(DALI_UNLIKELY(DGifGetCode(loaderInfo.gifAccessor->gif, &img_code, &img) == GIF_ERROR))
1327 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1334 DGifGetCodeNext(loaderInfo.gifAccessor->gif, &img);
1339 // if we found the image we wanted - get out of here
1340 if(imageNumber > index)
1345 } while(rec != TERMINATE_RECORD_TYPE);
1347 // if we are at the end of the animation or not animated, close file
1348 loaderInfo.imageNumber = imageNumber;
1349 if((animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE))
1351 loaderInfo.gifAccessor.reset();
1352 loaderInfo.imageNumber = 0;
1356 // no errors in header scan etc. so set err and return value
1360 // if it was an animated image we need to copy the data to the
1361 // pixels for the image from the frame holding the data
1362 if(animated.animated && frame->data)
1364 memcpy(pixels, frame->data, prop.w * prop.h * sizeof(uint32_t));
1370 } // unnamed namespace
1372 struct GifLoading::Impl
1375 Impl(const std::string& url, bool isLocalResource)
1377 mLoadSucceeded(true),
1380 loaderInfo.gifAccessor = nullptr;
1382 loaderInfo.fileData.fileName = mUrl.c_str();
1383 loaderInfo.fileData.isLocalResource = isLocalResource;
1385 mLoadSucceeded = ReadHeader(loaderInfo, imageProperties, &error);
1388 // Moveable but not copyable
1389 Impl(const Impl&) = delete;
1390 Impl& operator=(const Impl&) = delete;
1391 Impl(Impl&&) = default;
1392 Impl& operator=(Impl&&) = default;
1395 LoaderInfo loaderInfo;
1396 ImageProperties imageProperties;
1397 bool mLoadSucceeded;
1401 AnimatedImageLoadingPtr GifLoading::New(const std::string& url, bool isLocalResource)
1403 return AnimatedImageLoadingPtr(new GifLoading(url, isLocalResource));
1406 GifLoading::GifLoading(const std::string& url, bool isLocalResource)
1407 : mImpl(new GifLoading::Impl(url, isLocalResource))
1411 GifLoading::~GifLoading()
1416 bool GifLoading::LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector<Dali::PixelData>& pixelData)
1421 Mutex::ScopedLock lock(mImpl->mMutex);
1422 if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
1427 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof(uint32_t);
1429 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count);
1431 for(int i = 0; i < count; ++i)
1433 auto pixelBuffer = new unsigned char[bufferSize];
1435 mImpl->loaderInfo.animated.currentFrame = 1 + ((frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount);
1437 if(ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error))
1441 pixelData.push_back(Dali::PixelData::New(pixelBuffer, bufferSize, mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY));
1450 Dali::Devel::PixelBuffer GifLoading::LoadFrame(uint32_t frameIndex)
1453 Dali::Devel::PixelBuffer pixelBuffer;
1454 if(!mImpl->mLoadSucceeded)
1459 Mutex::ScopedLock lock(mImpl->mMutex);
1460 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex);
1462 pixelBuffer = Dali::Devel::PixelBuffer::New(mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888);
1464 mImpl->loaderInfo.animated.currentFrame = 1 + (frameIndex % mImpl->loaderInfo.animated.frameCount);
1465 ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer.GetBuffer(), &error);
1469 pixelBuffer = Dali::Devel::PixelBuffer();
1474 ImageDimensions GifLoading::GetImageSize() const
1476 return ImageDimensions(mImpl->imageProperties.w, mImpl->imageProperties.h);
1479 uint32_t GifLoading::GetImageCount() const
1481 return mImpl->loaderInfo.animated.frameCount;
1484 uint32_t GifLoading::GetFrameInterval(uint32_t frameIndex) const
1486 return mImpl->loaderInfo.animated.frames[frameIndex].info.delay * 10;
1489 std::string GifLoading::GetUrl() const
1494 bool GifLoading::HasLoadingSucceeded() const
1496 return mImpl->mLoadSucceeded;
1499 } // namespace Adaptor
1501 } // namespace Internal