2 * Copyright (c) 2024 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))
42 #define PRINT_ERROR_AND_EXIT(errorFormat, ...) \
45 DALI_LOG_ERROR(errorFormat, ##__VA_ARGS__); \
61 #if defined(DEBUG_ENABLED)
62 Debug::Filter* gGifLoadingLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_GIF_LOADING");
65 const int IMG_MAX_SIZE = 65000;
66 constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024;
68 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
71 const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
72 const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
84 dispose(DISPOSE_BACKGROUND),
90 unsigned short delay; // delay time in 1/100ths of a sec
91 short transparent : 10; // -1 == not, anything else == index
92 short dispose : 6; // 0, 1, 2, 3 (others invalid)
93 short interlace : 1; // interlaced or not
110 // De-allocate memory of the frame data.
117 uint32_t* data; /* frame decoding data */
118 FrameInfo info; /* special image type info */
122 struct GifAnimationData
133 std::vector<ImageFrame> frames;
140 struct GifCachedColorData
142 GifCachedColorData() = default;
144 // precalculated colormap table
145 std::vector<std::uint32_t> globalCachedColor{};
146 std::vector<std::uint32_t> localCachedColor{};
149 // Forward declaration
164 isLocalResource(true)
180 bool LoadLocalFile();
181 bool LoadRemoteFile();
184 const char* fileName; /**< The absolute path of the file. */
185 unsigned char* globalMap; /**< A pointer to the entire contents of the file */
186 long long length; /**< The length of the file in bytes. */
187 bool isLocalResource; /**< The flag whether the file is a local resource */
200 int position, length; // yes - gif uses ints for file sizes.
204 GifAnimationData animated;
205 GifCachedColorData cachedColor;
206 std::unique_ptr<GifAccessor> gifAccessor{nullptr};
211 struct ImageProperties
219 * Class to access gif open/close using riaa
225 * @param[in,out] fileInfo Contains ptr to memory, and is updated by DGifOpen
227 GifAccessor(LoaderInfo::FileInfo& fileInfo)
229 // actually ask libgif to open the file
230 #if GIFLIB_MAJOR >= 5
231 gif = DGifOpen(&fileInfo, FileRead, NULL);
233 gif = DGifOpen(&fileInfo, FileRead);
238 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
246 #if(GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
247 DGifCloseFile(gif, NULL);
255 * @brief Copy data from gif file into buffer.
257 * @param[in] gifFileType A pointer pointing to GIF File Type
258 * @param[out] buffer A pointer to buffer containing GIF raw data
259 * @param[in] len The length in bytes to be copied
260 * @return The data length of the image in bytes
262 static int FileRead(GifFileType* gifFileType, GifByteType* buffer, int length)
264 LoaderInfo::FileInfo* fi = reinterpret_cast<LoaderInfo::FileInfo*>(gifFileType->UserData);
266 if(DALI_UNLIKELY(fi->position >= fi->length))
268 return 0; // if at or past end - no
270 if((fi->position + length) >= fi->length)
272 length = fi->length - fi->position;
274 memcpy(buffer, fi->map + fi->position, length);
275 fi->position += length;
279 GifFileType* gif = nullptr;
282 bool LoaderInfo::FileData::LoadFile()
284 bool success = false;
287 success = LoadLocalFile();
291 success = LoadRemoteFile();
296 bool LoaderInfo::FileData::LoadLocalFile()
298 Internal::Platform::FileReader fileReader(fileName);
299 FILE* fp = fileReader.GetFile();
300 if(DALI_UNLIKELY(fp == NULL))
305 if(DALI_UNLIKELY(fseek(fp, 0, SEEK_END) <= -1))
311 if(DALI_UNLIKELY(length <= -1))
316 if(DALI_LIKELY(!fseek(fp, 0, SEEK_SET)))
318 globalMap = reinterpret_cast<GifByteType*>(malloc(sizeof(GifByteType) * static_cast<unsigned long long>(length)));
319 if(DALI_UNLIKELY(globalMap == nullptr))
321 DALI_LOG_ERROR("malloc is failed. request malloc size : %llu\n", sizeof(GifByteType) * static_cast<unsigned long long>(length));
324 length = fread(globalMap, sizeof(GifByteType), length, fp);
333 bool LoaderInfo::FileData::LoadRemoteFile()
336 bool succeeded = false;
337 Dali::Vector<uint8_t> dataBuffer;
340 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory(fileName, dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE);
341 if(DALI_LIKELY(succeeded))
343 size_t blobSize = dataBuffer.Size();
344 if(DALI_LIKELY(blobSize > 0U))
346 // Open a file handle on the memory buffer:
347 Dali::Internal::Platform::FileReader fileReader(dataBuffer, blobSize);
348 FILE* const fp = fileReader.GetFile();
349 if(DALI_LIKELY(NULL != fp))
351 if(DALI_LIKELY(!fseek(fp, 0, SEEK_SET)))
353 globalMap = reinterpret_cast<GifByteType*>(malloc(sizeof(GifByteType) * blobSize));
354 if(DALI_UNLIKELY(globalMap == nullptr))
356 DALI_LOG_ERROR("malloc is failed. request malloc size : %zu\n", sizeof(GifByteType) * blobSize);
360 length = fread(globalMap, sizeof(GifByteType), blobSize, fp);
366 DALI_LOG_ERROR("Error seeking within file\n");
371 DALI_LOG_ERROR("Error reading file\n");
380 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
382 * @param[in] animated A structure containing GIF animation data
383 * @param[in] index Frame index to be searched in GIF
384 * @return single 32-bit (ABGR) value.
386 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)
388 return (((a) << 24) + ((b) << 16) + ((g) << 8) + (r));
391 inline std::uint32_t PixelLookup(const ColorMapObject* const& colorMap, int index)
393 return CombinePixelABGR(0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue);
397 * @brief Get the Background Color from frameInfo
399 * @param[in] gif A pointer pointing to GIF File Type
400 * @param[in] frameInfo A pointer pointing to Frame Information data
401 * @return single 32-bit (ABGR) value. of background color
403 std::uint32_t GetBackgroundColor(GifFileType* gif, FrameInfo* frameInfo)
405 if(frameInfo->transparent < 0)
407 ColorMapObject* colorMap;
410 // work out color to use from colorMap
411 if(gif->Image.ColorMap)
413 colorMap = gif->Image.ColorMap;
417 colorMap = gif->SColorMap;
419 backGroundColor = gif->SBackGroundColor;
420 // Get background color from colormap
421 return PixelLookup(colorMap, backGroundColor);
431 * @brief Brute force find frame index - gifs are normally small so ok for now.
433 * @param[in] animated A structure containing GIF animation data
434 * @param[in] index Frame index to be searched in GIF
435 * @return A pointer to the ImageFrame.
437 ImageFrame* FindFrame(const GifAnimationData& animated, int index)
439 for(auto&& elem : animated.frames)
441 if(elem.index == index)
443 return const_cast<ImageFrame*>(&elem);
450 * @brief Fill in an image with a specific rgba color value.
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] val A uint32_t containing rgba color value
455 * @param[in] x X-coordinate used an offset to calculate pixel position
456 * @param[in] y Y-coordinate used an offset to calculate pixel position
457 * @param[in] width Width of the image
458 * @param[in] height Height of the image
460 void FillImage(uint32_t* data, int stride, uint32_t val, int x, int y, int width, int height)
462 uint32_t* pixelPosition;
464 // Boost time if stride == width and x == 0. We can assume that all pointer is continuous.
465 if(x == 0 && stride == width)
467 pixelPosition = data + (y * stride);
468 // Clear as white or transparent
469 // Special case. we can use memset.
470 if(val == 0x00 || val == 0xffffffffu)
472 const std::int8_t setupVal = val & 0xff;
473 memset(pixelPosition, setupVal, width * height * sizeof(std::uint32_t));
477 for(int byteCount = 0; byteCount < width * height; ++byteCount)
479 *pixelPosition = val;
486 for(int yAxis = 0; yAxis < height; ++yAxis)
488 pixelPosition = data + ((y + yAxis) * stride) + x;
489 for(int xAxis = 0; xAxis < width; ++xAxis)
491 *pixelPosition = val;
499 * @brief Store common fields from gif file info into frame info
501 * @param[in] gif A pointer pointing to GIF File Type
502 * @param[in] frameInfo A pointer pointing to Frame Information data
504 void StoreFrameInfo(GifFileType* gif, FrameInfo* frameInfo)
506 frameInfo->x = gif->Image.Left;
507 frameInfo->y = gif->Image.Top;
508 frameInfo->w = gif->Image.Width;
509 frameInfo->h = gif->Image.Height;
510 frameInfo->interlace = gif->Image.Interlace;
514 * @brief Check if image fills "screen space" and if so, if it is transparent
515 * at all then the image could be transparent - OR if image doesnt fill,
516 * then it could be trasnparent (full coverage of screen). Some gifs will
517 * be recognized as solid here for faster rendering, but not all.
519 * @param[out] full A boolean to show whether image is transparent or not
520 * @param[in] frameInfo A pointer pointing to Frame Information data
521 * @param[in] width Width of the image
522 * @param[in] height Height of the image
524 void CheckTransparency(bool& full, FrameInfo* frameInfo, int width, int height)
526 if((frameInfo->x == 0) && (frameInfo->y == 0) &&
527 (frameInfo->w == width) && (frameInfo->h == height))
529 if(frameInfo->transparent >= 0)
541 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
543 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)
551 if((x0 + w0) > imageWidth)
553 w0 = imageWidth - x0;
561 if((y0 + h0) > imageHeight)
563 h0 = imageHeight - y0;
572 * @brief Flush out rgba frame images to save memory but skip current,
573 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
575 * @param[in] animated A structure containing GIF animation data
576 * @param[in] width Width of the image
577 * @param[in] height Height of the image
578 * @param[in] thisframe The current frame
579 * @param[in] prevframe The previous frame
580 * @param[in] lastPreservedFrame The last preserved frame
582 void FlushFrames(GifAnimationData& animated, int width, int height, ImageFrame* thisframe, ImageFrame* prevframe, ImageFrame* lastPreservedFrame)
584 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n");
586 // target is the amount of memory we want to be under for stored frames
587 int total = 0, target = 512 * 1024;
589 // total up the amount of memory used by stored frames for this image
590 for(auto&& frame : animated.frames)
597 total *= (width * height * sizeof(uint32_t));
599 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total);
601 // If we use more than target (512k) for frames - flush
604 // Clean frames (except current and previous) until below target
605 for(auto&& frame : animated.frames)
607 if((frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
608 (!lastPreservedFrame || frame.index != lastPreservedFrame->index))
610 if(frame.data != nullptr)
613 frame.data = nullptr;
615 // subtract memory used and if below target - stop flush
616 total -= (width * height * sizeof(uint32_t));
626 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n");
630 * @brief allocate frame and frame info and append to list and store fields.
632 * @param[in] animated A structure containing GIF animation data
633 * @param[in] transparent Transparent index of the new frame
634 * @param[in] dispose Dispose mode of new frame
635 * @param[in] delay The frame delay of new frame
636 * @param[in] index The index of new frame
638 FrameInfo* NewFrame(GifAnimationData& animated, int transparent, int dispose, int delay, int index)
642 // record transparent index to be used or -1 if none
643 // for this SPECIFIC frame
644 frame.info.transparent = transparent;
645 // record dispose mode (3 bits)
646 frame.info.dispose = dispose;
647 // record delay (2 bytes so max 65546 /100 sec)
648 frame.info.delay = delay;
649 // record the index number we are at
651 // that frame is stored AT image/screen size
653 animated.frames.push_back(frame);
655 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size());
657 return &(animated.frames.back().info);
660 /// FILL (overwrite with transparency kept)
661 void FillOverwriteWithTransparencyKept(
662 const std::uint32_t*& cachedColorPtr,
672 const int transparent,
673 const uint32_t fillColor,
678 ColorMapObject*& colorMap)
680 // if we use cachedColor, use it
683 for(yy = 0; yy < h; yy++)
685 p = data + ((y + yy) * rowpix) + x;
686 for(xx = 0; xx < w; xx++)
688 pix = rows[yin + yy][xin + xx];
689 if(pix != transparent)
691 *p = cachedColorPtr[pix];
701 // we don't have cachedColor. use PixelLookup function.
704 for(yy = 0; yy < h; yy++)
706 p = data + ((y + yy) * rowpix) + x;
707 for(xx = 0; xx < w; xx++)
709 pix = rows[yin + yy][xin + xx];
710 if(pix != transparent)
712 *p = PixelLookup(colorMap, pix);
724 /// Paste on top with transparent pixels untouched
725 void PasteOnTopWithTransparentPixelsUntouched(
726 const std::uint32_t*& cachedColorPtr,
736 const int transparent,
737 const uint32_t fillColor,
742 ColorMapObject*& colorMap)
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];
761 // we don't have cachedColor. use PixelLookup function.
764 for(yy = 0; yy < h; yy++)
766 p = data + ((y + yy) * rowpix) + x;
767 for(xx = 0; xx < w; xx++)
769 pix = rows[yin + yy][xin + xx];
770 if(pix != transparent)
772 *p = PixelLookup(colorMap, pix);
780 void HandleTransparentPixels(
782 const std::uint32_t*& cachedColorPtr,
792 const int transparent,
793 const uint32_t fillColor,
798 ColorMapObject*& colorMap)
802 FillOverwriteWithTransparencyKept(cachedColorPtr, xx, yy, x, y, w, h, xin, yin, rowpix, transparent, fillColor, pix, p, data, rows, colorMap);
806 PasteOnTopWithTransparentPixelsUntouched(cachedColorPtr, xx, yy, x, y, w, h, xin, yin, rowpix, transparent, fillColor, pix, p, data, rows, colorMap);
810 void HandleNonTransparentPixels(
811 const std::uint32_t*& cachedColorPtr,
821 const int transparent,
822 const uint32_t fillColor,
827 ColorMapObject*& colorMap)
829 // if we use cachedColor, use it
832 // walk pixels without worring about transparency at all
833 for(yy = 0; yy < h; yy++)
835 p = data + ((y + yy) * rowpix) + x;
836 for(xx = 0; xx < w; xx++)
838 pix = rows[yin + yy][xin + xx];
839 *p = cachedColorPtr[pix];
844 // we don't have cachedColor. use PixelLookup function.
847 // walk pixels without worring about transparency at all
848 for(yy = 0; yy < h; yy++)
850 p = data + ((y + yy) * rowpix) + x;
851 for(xx = 0; xx < w; xx++)
853 pix = rows[yin + yy][xin + xx];
854 *p = PixelLookup(colorMap, pix);
862 * @brief Decode a gif image into rows then expand to 32bit into the destination
865 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)
867 int intoffset[] = {0, 4, 2, 1};
868 int intjump[] = {8, 8, 4, 2};
869 int i, xx, yy, pix, gifW, gifH;
870 GifRowType* rows = NULL;
872 ColorMapObject* colorMap;
875 // cached color data.
876 const std::uint32_t* cachedColorPtr = nullptr;
878 // what we need is image size.
880 sp = &gif->SavedImages[gif->ImageCount - 1];
882 gifW = sp->ImageDesc.Width;
883 gifH = sp->ImageDesc.Height;
885 if(DALI_UNLIKELY((gifW < w) || (gifH < h)))
887 DALI_LOG_ERROR("gifW : %d, w : %d, gifH : %d, h : %d\n", gifW, w, gifH, h);
888 DALI_ASSERT_DEBUG(false && "Dimensions are bigger than the Gif image size");
889 PRINT_ERROR_AND_EXIT("GIF Loader: Dimensions are bigger than the Gif image size! gifW : %d, w : %d, gifH : %d, h : %d\n", gifW, w, gifH, h);
892 // build a blob of memory to have pointers to rows of pixels
893 // AND store the decoded gif pixels (1 byte per pixel) as welll
894 rows = static_cast<GifRowType*>(malloc((gifH * sizeof(GifRowType)) + (gifW * gifH * sizeof(GifPixelType))));
895 if(DALI_UNLIKELY(!rows))
897 PRINT_ERROR_AND_EXIT("GIF Loader: malloc failed! gifW : %d, w : %d, gifH : %d, h : %d\n", gifW, w, gifH, h);
900 // fill in the pointers at the start
901 for(yy = 0; yy < gifH; yy++)
903 rows[yy] = reinterpret_cast<unsigned char*>(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType));
906 // if gif is interlaced, walk interlace pattern and decode into rows
907 if(gif->Image.Interlace)
909 for(i = 0; i < 4; i++)
911 for(yy = intoffset[i]; yy < gifH; yy += intjump[i])
913 if(DALI_UNLIKELY(DGifGetLine(gif, rows[yy], gifW) != GIF_OK))
915 PRINT_ERROR_AND_EXIT("GIF Loader: Decode failed at line %d! gifW : %d, gifH : %d, rows[yy] : %d, i : %d, intoffset[i] : %d, intjump[i] : %d\n", yy, gifW, gifH, rows[yy], i, intoffset[i], intjump[i]);
920 // normal top to bottom - decode into rows
923 for(yy = 0; yy < gifH; yy++)
925 if(DALI_UNLIKELY(DGifGetLine(gif, rows[yy], gifW) != GIF_OK))
927 PRINT_ERROR_AND_EXIT("GIF Loader: Decode failed at line %d! gifW : %d, gifH : %d, rows[yy] : %d\n", yy, gifW, gifH, rows[yy]);
932 // work out what colormap to use
933 if(gif->Image.ColorMap)
935 colorMap = gif->Image.ColorMap;
936 // if w * h is big enough, generate local cached color.
937 if(colorMap->ColorCount * LOCAL_CACHED_COLOR_GENERATE_THRESHOLD < w * h)
939 gifCachedColor.localCachedColor.resize(colorMap->ColorCount);
940 for(i = 0; i < colorMap->ColorCount; ++i)
942 gifCachedColor.localCachedColor[i] = PixelLookup(colorMap, i);
945 cachedColorPtr = gifCachedColor.localCachedColor.data();
950 colorMap = gif->SColorMap;
951 cachedColorPtr = gifCachedColor.globalCachedColor.data();
954 // HARD-CODING optimize
955 // if we need to deal with transparent pixels at all...
958 HandleTransparentPixels(fill, cachedColorPtr, xx, yy, x, y, w, h, xin, yin, rowpix, transparent, fillColor, pix, p, data, rows, colorMap);
962 HandleNonTransparentPixels(cachedColorPtr, xx, yy, x, y, w, h, xin, yin, rowpix, transparent, fillColor, pix, p, data, rows, colorMap);
973 /// Walk through gif records in file to figure out info while reading the header
974 void WalkThroughGifRecordsWhileReadingHeader(
975 const GifAccessor& gifAccessor,
978 FrameInfo*& frameInfo,
980 const ImageProperties& prop,
981 GifAnimationData& animated,
987 if(DGifGetRecordType(gifAccessor.gif, &rec) == GIF_ERROR)
989 // if we have a gif that ends part way through a sequence
990 // (or animation) consider it valid and just break - no error
998 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1003 // get image description section
1004 if(rec == IMAGE_DESC_RECORD_TYPE)
1010 if(DALI_UNLIKELY(DGifGetImageDesc(gifAccessor.gif) == GIF_ERROR))
1013 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1016 // skip decoding and just walk image to next
1017 if(DALI_UNLIKELY(DGifGetCode(gifAccessor.gif, &img_code, &img) == GIF_ERROR))
1020 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1023 // skip till next...
1027 DGifGetCodeNext(gifAccessor.gif, &img);
1029 // store geometry in the last frame info data
1032 StoreFrameInfo(gifAccessor.gif, frameInfo);
1033 CheckTransparency(full, frameInfo, prop.w, prop.h);
1035 // or if we dont have a frameInfo entry - create one even for stills
1038 // allocate and save frame with field data
1039 frameInfo = NewFrame(animated, -1, 0, 0, imageNumber + 1);
1040 if(DALI_UNLIKELY(!frameInfo))
1043 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1046 // store geometry info from gif image
1047 StoreFrameInfo(gifAccessor.gif, frameInfo);
1048 // check for transparency/alpha
1049 CheckTransparency(full, frameInfo, prop.w, prop.h);
1053 // we have an extension code block - for animated gifs for sure
1054 else if(rec == EXTENSION_RECORD_TYPE)
1057 GifByteType* ext = NULL;
1059 // get the first extension entry
1060 DGifGetExtension(gifAccessor.gif, &ext_code, &ext);
1063 // graphic control extension - for animated gif data
1064 // and transparent index + flag
1065 if(ext_code == 0xf9)
1067 // create frame and store it in image
1068 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
1069 int disposeMode = (ext[1] >> 2) & 0x7;
1070 int delay = (int(ext[3]) << 8) | int(ext[2]);
1071 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
1072 if(DALI_UNLIKELY(!frameInfo))
1075 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1079 // netscape extension indicating loop count.
1080 else if(ext_code == 0xff) /* application extension */
1082 if(!strncmp(reinterpret_cast<char*>(&ext[1]), "NETSCAPE2.0", 11) ||
1083 !strncmp(reinterpret_cast<char*>(&ext[1]), "ANIMEXTS1.0", 11))
1086 DGifGetExtensionNext(gifAccessor.gif, &ext);
1089 loopCount = (int(ext[3]) << 8) | int(ext[2]);
1098 // and continue onto the next extension entry
1100 DGifGetExtensionNext(gifAccessor.gif, &ext);
1103 } while(rec != TERMINATE_RECORD_TYPE && success);
1107 * @brief Reader header from the gif file and populates structures accordingly.
1109 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
1110 * @param[out] prop A ImageProperties structure for storing information about GIF data.
1111 * @return The true or false whether reading was successful or not.
1113 bool ReadHeader(LoaderInfo& loaderInfo,
1114 ImageProperties& prop)
1116 GifAnimationData& animated = loaderInfo.animated;
1117 GifCachedColorData& cachedColor = loaderInfo.cachedColor;
1118 LoaderInfo::FileData& fileData = loaderInfo.fileData;
1119 bool success = false;
1120 LoaderInfo::FileInfo fileInfo;
1123 // it is possible which gif file have error midle of frames,
1124 // in that case we should play gif file until meet error frame.
1125 int imageNumber = 0;
1127 FrameInfo* frameInfo = NULL;
1130 success = fileData.LoadFile();
1131 if(DALI_UNLIKELY(!success || !fileData.globalMap))
1134 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1138 fileInfo.map = fileData.globalMap;
1139 fileInfo.length = fileData.length;
1140 fileInfo.position = 0;
1141 GifAccessor gifAccessor(fileInfo);
1145 // get the gif "screen size" (the actual image size)
1146 prop.w = gifAccessor.gif->SWidth;
1147 prop.h = gifAccessor.gif->SHeight;
1149 // if size is invalid - abort here
1150 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)))
1152 if(IMG_TOO_BIG(prop.w, prop.h))
1155 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1160 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
1166 WalkThroughGifRecordsWhileReadingHeader(gifAccessor, rec, imageNumber, frameInfo, full, prop, animated, loopCount, success);
1170 // if the gif main says we have more than one image or our image counting
1171 // says so, then this image is animated - indicate this
1172 if((gifAccessor.gif->ImageCount > 1) || (imageNumber > 1))
1174 animated.animated = 1;
1175 animated.loopCount = loopCount;
1177 animated.frameCount = std::min(gifAccessor.gif->ImageCount, imageNumber);
1184 animated.currentFrame = 1;
1186 // cache global color map
1187 ColorMapObject* colorMap = gifAccessor.gif->SColorMap;
1190 cachedColor.globalCachedColor.resize(colorMap->ColorCount);
1191 for(int i = 0; i < colorMap->ColorCount; ++i)
1193 cachedColor.globalCachedColor[i] = PixelLookup(colorMap, i);
1202 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1208 /// Walk through gif records in file to figure out info
1209 bool WalkThroughGifRecords(
1211 LoaderInfo& loaderInfo,
1212 GifAnimationData& animated,
1215 FrameInfo*& frameInfo,
1216 const ImageProperties& prop,
1217 ImageFrame*& lastPreservedFrame,
1218 unsigned char*& pixels)
1222 if(DALI_UNLIKELY(DGifGetRecordType(loaderInfo.gifAccessor->gif, &rec) == GIF_ERROR))
1224 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1228 if(rec == EXTENSION_RECORD_TYPE)
1231 GifByteType* ext = NULL;
1232 DGifGetExtension(loaderInfo.gifAccessor->gif, &ext_code, &ext);
1237 DGifGetExtensionNext(loaderInfo.gifAccessor->gif, &ext);
1240 // get image description section
1241 else if(rec == IMAGE_DESC_RECORD_TYPE)
1243 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1246 ImageFrame* previousFrame = NULL;
1247 ImageFrame* thisFrame = NULL;
1250 if(DALI_UNLIKELY(DGifGetImageDesc(loaderInfo.gifAccessor->gif) == GIF_ERROR))
1252 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1256 // get the previous frame entry AND the current one to fill in
1257 previousFrame = FindFrame(animated, imageNumber - 1);
1258 thisFrame = FindFrame(animated, imageNumber);
1260 // if we have a frame AND we're animated AND we have no data...
1261 if((thisFrame) && (!thisFrame->data) && (animated.animated))
1266 thisFrame->data = new uint32_t[prop.w * prop.h];
1268 if(DALI_UNLIKELY(!thisFrame->data))
1270 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1274 // Lazy fill background color feature.
1275 // DecodeImage function draw range is EQUAL with previous FillImage range,
1276 // We don't need to fill background that time.
1277 // It will try to reduce the number of FillImage API call
1278 // Note : We might check overlapping. But that operation looks expensive
1279 // So, just optimize only if EQUAL case.
1280 bool updateBackgroundColorLazy = false;
1281 uint32_t backgroundColor = 0u;
1287 // if we have no prior frame OR prior frame data... empty
1288 if((!previousFrame) || (!previousFrame->data))
1291 frameInfo = &(thisFrame->info);
1292 updateBackgroundColorLazy = true;
1293 backgroundColor = 0u;
1299 // we have a prior frame to copy data from...
1302 frameInfo = &(previousFrame->info);
1304 // fix coords of sub image in case it goes out...
1305 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1307 // if dispose mode is not restore - then copy pre frame
1308 if(frameInfo->dispose != DISPOSE_PREVIOUS)
1310 memcpy(thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t));
1313 // if dispose mode is "background" then fill with bg
1314 if(frameInfo->dispose == DISPOSE_BACKGROUND)
1316 updateBackgroundColorLazy = true;
1317 backgroundColor = GetBackgroundColor(loaderInfo.gifAccessor->gif, frameInfo);
1323 else if(frameInfo->dispose == DISPOSE_PREVIOUS) // GIF_DISPOSE_RESTORE
1328 // Find last preserved frame.
1329 lastPreservedFrame = FindFrame(animated, imageNumber - prevIndex);
1330 if(DALI_UNLIKELY(!lastPreservedFrame))
1332 DALI_LOG_ERROR("LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND");
1336 } while(lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS);
1338 if(lastPreservedFrame)
1340 memcpy(thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t));
1344 // now draw this frame on top
1345 frameInfo = &(thisFrame->info);
1346 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1348 if(updateBackgroundColorLazy)
1350 // If this frame's x,y,w,h is not equal with previous x,y,w,h, FillImage. else, don't fill
1351 if(prevX != x || prevY != y || prevW != w || prevH != h)
1353 FillImage(thisFrame->data, prop.w, backgroundColor, prevX, prevY, prevW, prevH);
1354 // Don't send background color information to DecodeImage function.
1355 updateBackgroundColorLazy = false;
1358 if(DALI_UNLIKELY(!DecodeImage(loaderInfo.gifAccessor->gif, loaderInfo.cachedColor, thisFrame->data, prop.w, xin, yin, frameInfo->transparent, x, y, w, h, first || updateBackgroundColorLazy, backgroundColor)))
1360 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1364 // mark as loaded and done
1365 thisFrame->loaded = true;
1367 FlushFrames(animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame);
1369 // if we have a frame BUT the image is not animated. different
1371 else if((thisFrame) && (!thisFrame->data) && (!animated.animated))
1373 // if we don't have the data decoded yet - decode it
1374 if((!thisFrame->loaded) || (!thisFrame->data))
1376 // use frame info but we WONT allocate frame pixels
1377 frameInfo = &(thisFrame->info);
1378 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1380 // clear out all pixels only if x,y,w,h is not whole image.
1381 if(x != 0 || y != 0 || w != static_cast<int>(prop.w) || h != static_cast<int>(prop.h))
1383 const std::uint32_t backgroundColor = GetBackgroundColor(loaderInfo.gifAccessor->gif, frameInfo);
1384 FillImage(reinterpret_cast<uint32_t*>(pixels), prop.w, backgroundColor, 0, 0, prop.w, prop.h);
1387 // and decode the gif with overwriting
1388 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)))
1390 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1394 // mark as loaded and done
1395 thisFrame->loaded = true;
1397 // flush mem we don't need (at expense of decode cpu)
1401 // skip decoding and just walk image to next
1402 if(DALI_UNLIKELY(DGifGetCode(loaderInfo.gifAccessor->gif, &img_code, &img) == GIF_ERROR))
1404 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1411 DGifGetCodeNext(loaderInfo.gifAccessor->gif, &img);
1416 // if we found the image we wanted - get out of here
1417 if(imageNumber > index)
1422 } while(rec != TERMINATE_RECORD_TYPE);
1428 * @brief Reader next frame of the gif file and populates structures accordingly.
1430 * @param[in,out] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
1431 * @param[in,out] prop A ImageProperties structure containing information about gif data.
1432 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
1433 * @param[out] error Error code
1434 * @return The true or false whether reading was successful or not.
1436 bool ReadNextFrame(LoaderInfo& loaderInfo, ImageProperties& prop, // use for w and h
1437 unsigned char* pixels,
1440 GifAnimationData& animated = loaderInfo.animated;
1441 LoaderInfo::FileData& fileData = loaderInfo.fileData;
1444 int index = 0, imageNumber = 0;
1445 FrameInfo* frameInfo;
1446 ImageFrame* frame = NULL;
1447 ImageFrame* lastPreservedFrame = NULL;
1449 index = animated.currentFrame;
1451 // if index is invalid for animated image - error out
1452 if(DALI_UNLIKELY((animated.animated) && ((index <= 0) || (index > animated.frameCount))))
1454 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
1458 // find the given frame index
1459 frame = FindFrame(animated, index);
1460 if(DALI_UNLIKELY(!frame))
1462 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1465 else if(!(frame->loaded) || !(frame->data))
1467 // if we want to go backwards, we likely need/want to re-decode from the
1468 // start as we have nothing to build on. If there is a gif, imageNumber
1469 // has been set already.
1470 if(loaderInfo.gifAccessor && loaderInfo.imageNumber > 0)
1472 if((index > 0) && (index < loaderInfo.imageNumber) && (animated.animated))
1474 loaderInfo.gifAccessor.reset();
1475 loaderInfo.imageNumber = 0;
1479 // actually ask libgif to open the file
1480 if(!loaderInfo.gifAccessor)
1482 loaderInfo.fileInfo.map = fileData.globalMap;
1483 loaderInfo.fileInfo.length = fileData.length;
1484 loaderInfo.fileInfo.position = 0;
1485 if(DALI_UNLIKELY(!loaderInfo.fileInfo.map))
1487 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1490 std::unique_ptr<GifAccessor> gifAccessor = std::make_unique<GifAccessor>(loaderInfo.fileInfo);
1491 if(DALI_UNLIKELY(!gifAccessor->gif))
1493 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1496 loaderInfo.gifAccessor = std::move(gifAccessor);
1497 loaderInfo.imageNumber = 1;
1500 // our current position is the previous frame we decoded from the file
1501 imageNumber = loaderInfo.imageNumber;
1503 if(!WalkThroughGifRecords(rec, loaderInfo, animated, imageNumber, index, frameInfo, prop, lastPreservedFrame, pixels))
1508 // if we are at the end of the animation or not animated, close file
1509 loaderInfo.imageNumber = imageNumber;
1510 if((animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE))
1512 loaderInfo.gifAccessor.reset();
1513 loaderInfo.imageNumber = 0;
1517 // no errors in header scan etc. so set err and return value
1521 // if it was an animated image we need to copy the data to the
1522 // pixels for the image from the frame holding the data
1523 if(animated.animated && frame->data)
1525 memcpy(pixels, frame->data, prop.w * prop.h * sizeof(uint32_t));
1531 } // unnamed namespace
1533 struct GifLoading::Impl
1536 Impl(const std::string& url, bool isLocalResource)
1538 mLoadSucceeded(false),
1541 loaderInfo.gifAccessor = nullptr;
1542 loaderInfo.fileData.fileName = mUrl.c_str();
1543 loaderInfo.fileData.isLocalResource = isLocalResource;
1546 bool LoadGifInformation()
1548 // Block to do not load this file again.
1549 Mutex::ScopedLock lock(mMutex);
1550 if(DALI_LIKELY(mLoadSucceeded))
1552 return mLoadSucceeded;
1555 mLoadSucceeded = ReadHeader(loaderInfo, imageProperties);
1558 DALI_LOG_ERROR("ReadHeader is failed [%s]\n", mUrl.c_str());
1560 return mLoadSucceeded;
1563 // Moveable but not copyable
1564 Impl(const Impl&) = delete;
1565 Impl& operator=(const Impl&) = delete;
1566 Impl(Impl&&) = default;
1567 Impl& operator=(Impl&&) = default;
1570 LoaderInfo loaderInfo;
1571 ImageProperties imageProperties;
1572 bool mLoadSucceeded;
1576 AnimatedImageLoadingPtr GifLoading::New(const std::string& url, bool isLocalResource)
1578 return AnimatedImageLoadingPtr(new GifLoading(url, isLocalResource));
1581 GifLoading::GifLoading(const std::string& url, bool isLocalResource)
1582 : mImpl(new GifLoading::Impl(url, isLocalResource))
1586 GifLoading::~GifLoading()
1591 Dali::Devel::PixelBuffer GifLoading::LoadFrame(uint32_t frameIndex, ImageDimensions desiredSize)
1594 Dali::Devel::PixelBuffer pixelBuffer;
1596 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex);
1598 // If Gif file is still not loaded, Load the information.
1599 if(DALI_UNLIKELY(!mImpl->LoadGifInformation()))
1604 Mutex::ScopedLock lock(mImpl->mMutex);
1605 pixelBuffer = Dali::Devel::PixelBuffer::New(mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888);
1607 mImpl->loaderInfo.animated.currentFrame = 1 + (frameIndex % mImpl->loaderInfo.animated.frameCount);
1608 ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer.GetBuffer(), &error);
1612 pixelBuffer = Dali::Devel::PixelBuffer();
1617 ImageDimensions GifLoading::GetImageSize() const
1619 if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
1621 mImpl->LoadGifInformation();
1623 return ImageDimensions(mImpl->imageProperties.w, mImpl->imageProperties.h);
1626 uint32_t GifLoading::GetImageCount() const
1628 if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
1630 mImpl->LoadGifInformation();
1632 return mImpl->loaderInfo.animated.frameCount;
1635 uint32_t GifLoading::GetFrameInterval(uint32_t frameIndex) const
1637 if(DALI_UNLIKELY(!mImpl->mLoadSucceeded))
1639 mImpl->LoadGifInformation();
1642 uint32_t interval = 0u;
1643 if(DALI_LIKELY(mImpl->mLoadSucceeded))
1645 interval = mImpl->loaderInfo.animated.frames[frameIndex].info.delay * 10;
1650 std::string GifLoading::GetUrl() const
1655 bool GifLoading::HasLoadingSucceeded() const
1657 return mImpl->mLoadSucceeded;
1660 } // namespace Adaptor
1662 } // namespace Internal