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(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();
302 if(fseek(fp, 0, SEEK_END) <= -1)
313 if((!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);
335 size_t blobSize = dataBuffer.Size();
338 // Open a file handle on the memory buffer:
339 Dali::Internal::Platform::FileReader fileReader(dataBuffer, blobSize);
340 FILE* const fp = fileReader.GetFile();
343 if((!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 int CombinePixelABGR(int a, int r, int g, int b)
373 return (((a) << 24) + ((b) << 16) + ((g) << 8) + (r));
376 inline int PixelLookup(ColorMapObject* 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] row A int containing the number of rows 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 row, uint32_t val, int x, int y, int width, int height)
414 uint32_t* pixelPosition;
416 for(yAxis = 0; yAxis < height; yAxis++)
418 pixelPosition = data + ((y + yAxis) * row) + x;
419 for(xAxis = 0; xAxis < width; xAxis++)
421 *pixelPosition = val;
428 * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
430 * @param[in] data A pointer pointing to an image data
431 * @param[in] row A int containing the number of rows in an image
432 * @param[in] gif A pointer pointing to GIF File Type
433 * @param[in] frameInfo A pointer pointing to Frame Information data
434 * @param[in] x X-coordinate used an offset to calculate pixel position
435 * @param[in] y Y-coordinate used an offset to calculate pixel position
436 * @param[in] width Width of the image
437 * @param[in] height Height of the image
439 void FillFrame(uint32_t* data, int row, GifFileType* gif, FrameInfo* frameInfo, int x, int y, int w, int h)
441 // solid color fill for pre frame region
442 if(frameInfo->transparent < 0)
444 ColorMapObject* colorMap;
447 // work out color to use from colorMap
448 if(gif->Image.ColorMap)
450 colorMap = gif->Image.ColorMap;
454 colorMap = gif->SColorMap;
456 backGroundColor = gif->SBackGroundColor;
458 FillImage(data, row, CombinePixelABGR(0xff, colorMap->Colors[backGroundColor].Red, colorMap->Colors[backGroundColor].Green, colorMap->Colors[backGroundColor].Blue), x, y, w, h);
460 // fill in region with 0 (transparent)
463 FillImage(data, row, 0, x, y, w, h);
468 * @brief Store common fields from gif file info into frame info
470 * @param[in] gif A pointer pointing to GIF File Type
471 * @param[in] frameInfo A pointer pointing to Frame Information data
473 void StoreFrameInfo(GifFileType* gif, FrameInfo* frameInfo)
475 frameInfo->x = gif->Image.Left;
476 frameInfo->y = gif->Image.Top;
477 frameInfo->w = gif->Image.Width;
478 frameInfo->h = gif->Image.Height;
479 frameInfo->interlace = gif->Image.Interlace;
483 * @brief Check if image fills "screen space" and if so, if it is transparent
484 * at all then the image could be transparent - OR if image doesnt fill,
485 * then it could be trasnparent (full coverage of screen). Some gifs will
486 * be recognized as solid here for faster rendering, but not all.
488 * @param[out] full A boolean to show whether image is transparent or not
489 * @param[in] frameInfo A pointer pointing to Frame Information data
490 * @param[in] width Width of the image
491 * @param[in] height Height of the image
493 void CheckTransparency(bool& full, FrameInfo* frameInfo, int width, int height)
495 if((frameInfo->x == 0) && (frameInfo->y == 0) &&
496 (frameInfo->w == width) && (frameInfo->h == height))
498 if(frameInfo->transparent >= 0)
510 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
512 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)
520 if((x0 + w0) > imageWidth)
522 w0 = imageWidth - x0;
530 if((y0 + h0) > imageHeight)
532 h0 = imageHeight - y0;
541 * @brief Flush out rgba frame images to save memory but skip current,
542 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
544 * @param[in] animated A structure containing GIF animation data
545 * @param[in] width Width of the image
546 * @param[in] height Height of the image
547 * @param[in] thisframe The current frame
548 * @param[in] prevframe The previous frame
549 * @param[in] lastPreservedFrame The last preserved frame
551 void FlushFrames(GifAnimationData& animated, int width, int height, ImageFrame* thisframe, ImageFrame* prevframe, ImageFrame* lastPreservedFrame)
553 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n");
555 // target is the amount of memory we want to be under for stored frames
556 int total = 0, target = 512 * 1024;
558 // total up the amount of memory used by stored frames for this image
559 for(auto&& frame : animated.frames)
566 total *= (width * height * sizeof(uint32_t));
568 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total);
570 // If we use more than target (512k) for frames - flush
573 // Clean frames (except current and previous) until below target
574 for(auto&& frame : animated.frames)
576 if((frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
577 (!lastPreservedFrame || frame.index != lastPreservedFrame->index))
579 if(frame.data != nullptr)
582 frame.data = nullptr;
584 // subtract memory used and if below target - stop flush
585 total -= (width * height * sizeof(uint32_t));
595 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n");
599 * @brief allocate frame and frame info and append to list and store fields.
601 * @param[in] animated A structure containing GIF animation data
602 * @param[in] transparent Transparent index of the new frame
603 * @param[in] dispose Dispose mode of new frame
604 * @param[in] delay The frame delay of new frame
605 * @param[in] index The index of new frame
607 FrameInfo* NewFrame(GifAnimationData& animated, int transparent, int dispose, int delay, int index)
611 // record transparent index to be used or -1 if none
612 // for this SPECIFIC frame
613 frame.info.transparent = transparent;
614 // record dispose mode (3 bits)
615 frame.info.dispose = dispose;
616 // record delay (2 bytes so max 65546 /100 sec)
617 frame.info.delay = delay;
618 // record the index number we are at
620 // that frame is stored AT image/screen size
622 animated.frames.push_back(frame);
624 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size());
626 return &(animated.frames.back().info);
630 * @brief Decode a gif image into rows then expand to 32bit into the destination
633 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)
635 int intoffset[] = {0, 4, 2, 1};
636 int intjump[] = {8, 8, 4, 2};
637 int i, xx, yy, pix, gifW, gifH;
638 GifRowType* rows = NULL;
640 ColorMapObject* colorMap;
643 // cached color data.
644 const std::uint32_t* cachedColorPtr = nullptr;
646 // what we need is image size.
648 sp = &gif->SavedImages[gif->ImageCount - 1];
650 gifW = sp->ImageDesc.Width;
651 gifH = sp->ImageDesc.Height;
653 if((gifW < w) || (gifH < h))
655 DALI_LOG_ERROR("gifW : %d, w : %d, gifH : %d, h : %d\n", gifW, w, gifH, h);
656 DALI_ASSERT_DEBUG(false && "Dimensions are bigger than the Gif image size");
660 // build a blob of memory to have pointers to rows of pixels
661 // AND store the decoded gif pixels (1 byte per pixel) as welll
662 rows = static_cast<GifRowType*>(malloc((gifH * sizeof(GifRowType)) + (gifW * gifH * sizeof(GifPixelType))));
668 // fill in the pointers at the start
669 for(yy = 0; yy < gifH; yy++)
671 rows[yy] = reinterpret_cast<unsigned char*>(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType));
674 // if gif is interlaced, walk interlace pattern and decode into rows
675 if(gif->Image.Interlace)
677 for(i = 0; i < 4; i++)
679 for(yy = intoffset[i]; yy < gifH; yy += intjump[i])
681 if(DGifGetLine(gif, rows[yy], gifW) != GIF_OK)
688 // normal top to bottom - decode into rows
691 for(yy = 0; yy < gifH; yy++)
693 if(DGifGetLine(gif, rows[yy], gifW) != GIF_OK)
700 // work out what colormap to use
701 if(gif->Image.ColorMap)
703 colorMap = gif->Image.ColorMap;
704 // use local cached color map without re-calculate cache.
705 if(gifCachedColor.localCachedColorMap == colorMap)
707 cachedColorPtr = gifCachedColor.localCachedColor.data();
709 // else if w * h is big enough, generate local cached color.
710 else if(colorMap->ColorCount * LOCAL_CACHED_COLOR_GENERATE_THRESHOLD < w * h)
712 gifCachedColor.localCachedColor.resize(colorMap->ColorCount);
713 for(i = 0; i < colorMap->ColorCount; ++i)
715 gifCachedColor.localCachedColor[i] = PixelLookup(colorMap, i);
717 gifCachedColor.localCachedColorMap = colorMap;
719 cachedColorPtr = gifCachedColor.localCachedColor.data();
724 colorMap = gif->SColorMap;
725 cachedColorPtr = gifCachedColor.globalCachedColor.data();
728 // HARD-CODING optimize
729 // if we need to deal with transparent pixels at all...
732 // if we are told to FILL (overwrite with transparency kept)
735 // if we use cachedColor, use it
738 for(yy = 0; yy < h; yy++)
740 p = data + ((y + yy) * rowpix) + x;
741 for(xx = 0; xx < w; xx++)
743 pix = rows[yin + yy][xin + xx];
744 if(pix != transparent)
746 *p = cachedColorPtr[pix];
756 // we don't have cachedColor. use PixelLookup function.
759 for(yy = 0; yy < h; yy++)
761 p = data + ((y + yy) * rowpix) + x;
762 for(xx = 0; xx < w; xx++)
764 pix = rows[yin + yy][xin + xx];
765 if(pix != transparent)
767 *p = PixelLookup(colorMap, pix);
778 // paste on top with transparent pixels untouched
781 // if we use cachedColor, use it
784 for(yy = 0; yy < h; yy++)
786 p = data + ((y + yy) * rowpix) + x;
787 for(xx = 0; xx < w; xx++)
789 pix = rows[yin + yy][xin + xx];
790 if(pix != transparent)
792 *p = cachedColorPtr[pix];
798 // we don't have cachedColor. use PixelLookup function.
801 for(yy = 0; yy < h; yy++)
803 p = data + ((y + yy) * rowpix) + x;
804 for(xx = 0; xx < w; xx++)
806 pix = rows[yin + yy][xin + xx];
807 if(pix != transparent)
809 *p = PixelLookup(colorMap, pix);
819 // if we use cachedColor, use it
822 // walk pixels without worring about transparency at all
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 *p = cachedColorPtr[pix];
834 // we don't have cachedColor. use PixelLookup function.
837 // walk pixels without worring about transparency at all
838 for(yy = 0; yy < h; yy++)
840 p = data + ((y + yy) * rowpix) + x;
841 for(xx = 0; xx < w; xx++)
843 pix = rows[yin + yy][xin + xx];
844 *p = PixelLookup(colorMap, pix);
861 * @brief Reader header from the gif file and populates structures accordingly.
863 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
864 * @param[out] prop A ImageProperties structure for storing information about GIF data.
865 * @param[out] error Error code
866 * @return The true or false whether reading was successful or not.
868 bool ReadHeader(LoaderInfo& loaderInfo,
869 ImageProperties& prop, //output struct
872 GifAnimationData& animated = loaderInfo.animated;
873 GifCachedColorData& cachedColor = loaderInfo.cachedColor;
874 LoaderInfo::FileData& fileData = loaderInfo.fileData;
875 bool success = false;
876 LoaderInfo::FileInfo fileInfo;
879 // it is possible which gif file have error midle of frames,
880 // in that case we should play gif file until meet error frame.
883 FrameInfo* frameInfo = NULL;
886 success = fileData.LoadFile();
887 if(!success || !fileData.globalMap)
890 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
894 fileInfo.map = fileData.globalMap;
895 fileInfo.length = fileData.length;
896 fileInfo.position = 0;
897 GifAccessor gifAccessor(fileInfo);
901 // get the gif "screen size" (the actual image size)
902 prop.w = gifAccessor.gif->SWidth;
903 prop.h = gifAccessor.gif->SHeight;
905 // if size is invalid - abort here
906 if((prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h))
908 if(IMG_TOO_BIG(prop.w, prop.h))
911 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
916 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
921 // walk through gif records in file to figure out info
925 if(DGifGetRecordType(gifAccessor.gif, &rec) == GIF_ERROR)
927 // if we have a gif that ends part way through a sequence
928 // (or animation) consider it valid and just break - no error
936 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
941 // get image description section
942 if(rec == IMAGE_DESC_RECORD_TYPE)
948 if(DGifGetImageDesc(gifAccessor.gif) == GIF_ERROR)
951 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
954 // skip decoding and just walk image to next
955 if(DGifGetCode(gifAccessor.gif, &img_code, &img) == GIF_ERROR)
958 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
965 DGifGetCodeNext(gifAccessor.gif, &img);
967 // store geometry in the last frame info data
970 StoreFrameInfo(gifAccessor.gif, frameInfo);
971 CheckTransparency(full, frameInfo, prop.w, prop.h);
973 // or if we dont have a frameInfo entry - create one even for stills
976 // allocate and save frame with field data
977 frameInfo = NewFrame(animated, -1, 0, 0, imageNumber + 1);
981 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
984 // store geometry info from gif image
985 StoreFrameInfo(gifAccessor.gif, frameInfo);
986 // check for transparency/alpha
987 CheckTransparency(full, frameInfo, prop.w, prop.h);
991 // we have an extension code block - for animated gifs for sure
992 else if(rec == EXTENSION_RECORD_TYPE)
995 GifByteType* ext = NULL;
997 // get the first extension entry
998 DGifGetExtension(gifAccessor.gif, &ext_code, &ext);
1001 // graphic control extension - for animated gif data
1002 // and transparent index + flag
1003 if(ext_code == 0xf9)
1005 // create frame and store it in image
1006 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
1007 int disposeMode = (ext[1] >> 2) & 0x7;
1008 int delay = (int(ext[3]) << 8) | int(ext[2]);
1009 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
1013 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1017 // netscape extension indicating loop count.
1018 else if(ext_code == 0xff) /* application extension */
1020 if(!strncmp(reinterpret_cast<char*>(&ext[1]), "NETSCAPE2.0", 11) ||
1021 !strncmp(reinterpret_cast<char*>(&ext[1]), "ANIMEXTS1.0", 11))
1024 DGifGetExtensionNext(gifAccessor.gif, &ext);
1027 loopCount = (int(ext[3]) << 8) | int(ext[2]);
1036 // and continue onto the next extension entry
1038 DGifGetExtensionNext(gifAccessor.gif, &ext);
1041 } while(rec != TERMINATE_RECORD_TYPE && success);
1045 // if the gif main says we have more than one image or our image counting
1046 // says so, then this image is animated - indicate this
1047 if((gifAccessor.gif->ImageCount > 1) || (imageNumber > 1))
1049 animated.animated = 1;
1050 animated.loopCount = loopCount;
1052 animated.frameCount = std::min(gifAccessor.gif->ImageCount, imageNumber);
1059 animated.currentFrame = 1;
1061 // cache global color map
1062 ColorMapObject* colorMap = gifAccessor.gif->SColorMap;
1065 cachedColor.globalCachedColor.resize(colorMap->ColorCount);
1066 for(int i = 0; i < colorMap->ColorCount; ++i)
1068 cachedColor.globalCachedColor[i] = PixelLookup(colorMap, i);
1071 cachedColor.localCachedColorMap = nullptr;
1073 // no errors in header scan etc. so set err and return value
1083 * @brief Reader next frame of the gif file and populates structures accordingly.
1085 * @param[in,out] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
1086 * @param[in,out] prop A ImageProperties structure containing information about gif data.
1087 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
1088 * @param[out] error Error code
1089 * @return The true or false whether reading was successful or not.
1091 bool ReadNextFrame(LoaderInfo& loaderInfo, ImageProperties& prop, // use for w and h
1092 unsigned char* pixels,
1095 GifAnimationData& animated = loaderInfo.animated;
1096 LoaderInfo::FileData& fileData = loaderInfo.fileData;
1099 int index = 0, imageNumber = 0;
1100 FrameInfo* frameInfo;
1101 ImageFrame* frame = NULL;
1102 ImageFrame* lastPreservedFrame = NULL;
1104 index = animated.currentFrame;
1106 // if index is invalid for animated image - error out
1107 if((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
1109 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
1113 // find the given frame index
1114 frame = FindFrame(animated, index);
1117 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1120 else if(!(frame->loaded) || !(frame->data))
1122 // if we want to go backwards, we likely need/want to re-decode from the
1123 // start as we have nothing to build on. If there is a gif, imageNumber
1124 // has been set already.
1125 if(loaderInfo.gifAccessor && loaderInfo.imageNumber > 0)
1127 if((index > 0) && (index < loaderInfo.imageNumber) && (animated.animated))
1129 loaderInfo.gifAccessor.reset();
1130 loaderInfo.imageNumber = 0;
1134 // actually ask libgif to open the file
1135 if(!loaderInfo.gifAccessor)
1137 loaderInfo.fileInfo.map = fileData.globalMap;
1138 loaderInfo.fileInfo.length = fileData.length;
1139 loaderInfo.fileInfo.position = 0;
1140 if(!loaderInfo.fileInfo.map)
1142 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1145 std::unique_ptr<GifAccessor> gifAccessor = std::make_unique<GifAccessor>(loaderInfo.fileInfo);
1146 if(!gifAccessor->gif)
1148 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1151 loaderInfo.gifAccessor = std::move(gifAccessor);
1152 loaderInfo.imageNumber = 1;
1155 // our current position is the previous frame we decoded from the file
1156 imageNumber = loaderInfo.imageNumber;
1158 // walk through gif records in file to figure out info
1161 if(DGifGetRecordType(loaderInfo.gifAccessor->gif, &rec) == GIF_ERROR)
1163 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1167 if(rec == EXTENSION_RECORD_TYPE)
1170 GifByteType* ext = NULL;
1171 DGifGetExtension(loaderInfo.gifAccessor->gif, &ext_code, &ext);
1176 DGifGetExtensionNext(loaderInfo.gifAccessor->gif, &ext);
1179 // get image description section
1180 else if(rec == IMAGE_DESC_RECORD_TYPE)
1182 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1185 ImageFrame* previousFrame = NULL;
1186 ImageFrame* thisFrame = NULL;
1189 if(DGifGetImageDesc(loaderInfo.gifAccessor->gif) == GIF_ERROR)
1191 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1195 // get the previous frame entry AND the current one to fill in
1196 previousFrame = FindFrame(animated, imageNumber - 1);
1197 thisFrame = FindFrame(animated, imageNumber);
1199 // if we have a frame AND we're animated AND we have no data...
1200 if((thisFrame) && (!thisFrame->data) && (animated.animated))
1205 thisFrame->data = new uint32_t[prop.w * prop.h];
1207 if(!thisFrame->data)
1209 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1213 // if we have no prior frame OR prior frame data... empty
1214 if((!previousFrame) || (!previousFrame->data))
1217 frameInfo = &(thisFrame->info);
1218 memset(thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t));
1220 // we have a prior frame to copy data from...
1223 frameInfo = &(previousFrame->info);
1225 // fix coords of sub image in case it goes out...
1226 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1228 // if dispose mode is not restore - then copy pre frame
1229 if(frameInfo->dispose != DISPOSE_PREVIOUS)
1231 memcpy(thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t));
1234 // if dispose mode is "background" then fill with bg
1235 if(frameInfo->dispose == DISPOSE_BACKGROUND)
1237 FillFrame(thisFrame->data, prop.w, loaderInfo.gifAccessor->gif, frameInfo, x, y, w, h);
1239 else if(frameInfo->dispose == DISPOSE_PREVIOUS) // GIF_DISPOSE_RESTORE
1244 // Find last preserved frame.
1245 lastPreservedFrame = FindFrame(animated, imageNumber - prevIndex);
1246 if(!lastPreservedFrame)
1248 DALI_LOG_ERROR("LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND");
1252 } while(lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS);
1254 if(lastPreservedFrame)
1256 memcpy(thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t));
1260 // now draw this frame on top
1261 frameInfo = &(thisFrame->info);
1262 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1263 if(!DecodeImage(loaderInfo.gifAccessor->gif, loaderInfo.cachedColor, thisFrame->data, prop.w, xin, yin, frameInfo->transparent, x, y, w, h, first))
1265 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1269 // mark as loaded and done
1270 thisFrame->loaded = true;
1272 FlushFrames(animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame);
1274 // if we have a frame BUT the image is not animated. different
1276 else if((thisFrame) && (!thisFrame->data) && (!animated.animated))
1278 // if we don't have the data decoded yet - decode it
1279 if((!thisFrame->loaded) || (!thisFrame->data))
1281 // use frame info but we WONT allocate frame pixels
1282 frameInfo = &(thisFrame->info);
1283 ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h);
1285 // clear out all pixels
1286 FillFrame(reinterpret_cast<uint32_t*>(pixels), prop.w, loaderInfo.gifAccessor->gif, frameInfo, 0, 0, prop.w, prop.h);
1288 // and decode the gif with overwriting
1289 if(!DecodeImage(loaderInfo.gifAccessor->gif, loaderInfo.cachedColor, reinterpret_cast<uint32_t*>(pixels), prop.w, xin, yin, frameInfo->transparent, x, y, w, h, true))
1291 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE\n");
1295 // mark as loaded and done
1296 thisFrame->loaded = true;
1298 // flush mem we don't need (at expense of decode cpu)
1302 // skip decoding and just walk image to next
1303 if(DGifGetCode(loaderInfo.gifAccessor->gif, &img_code, &img) == GIF_ERROR)
1305 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT\n");
1312 DGifGetCodeNext(loaderInfo.gifAccessor->gif, &img);
1317 // if we found the image we wanted - get out of here
1318 if(imageNumber > index)
1323 } while(rec != TERMINATE_RECORD_TYPE);
1325 // if we are at the end of the animation or not animated, close file
1326 loaderInfo.imageNumber = imageNumber;
1327 if((animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE))
1329 loaderInfo.gifAccessor.reset();
1330 loaderInfo.imageNumber = 0;
1334 // no errors in header scan etc. so set err and return value
1338 // if it was an animated image we need to copy the data to the
1339 // pixels for the image from the frame holding the data
1340 if(animated.animated && frame->data)
1342 memcpy(pixels, frame->data, prop.w * prop.h * sizeof(uint32_t));
1348 } // unnamed namespace
1350 struct GifLoading::Impl
1353 Impl(const std::string& url, bool isLocalResource)
1355 mLoadSucceeded(true),
1358 loaderInfo.gifAccessor = nullptr;
1360 loaderInfo.fileData.fileName = mUrl.c_str();
1361 loaderInfo.fileData.isLocalResource = isLocalResource;
1363 mLoadSucceeded = ReadHeader(loaderInfo, imageProperties, &error);
1366 // Moveable but not copyable
1367 Impl(const Impl&) = delete;
1368 Impl& operator=(const Impl&) = delete;
1369 Impl(Impl&&) = default;
1370 Impl& operator=(Impl&&) = default;
1373 LoaderInfo loaderInfo;
1374 ImageProperties imageProperties;
1375 bool mLoadSucceeded;
1379 AnimatedImageLoadingPtr GifLoading::New(const std::string& url, bool isLocalResource)
1381 return AnimatedImageLoadingPtr(new GifLoading(url, isLocalResource));
1384 GifLoading::GifLoading(const std::string& url, bool isLocalResource)
1385 : mImpl(new GifLoading::Impl(url, isLocalResource))
1389 GifLoading::~GifLoading()
1394 bool GifLoading::LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector<Dali::PixelData>& pixelData)
1399 Mutex::ScopedLock lock(mImpl->mMutex);
1400 if(!mImpl->mLoadSucceeded)
1405 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof(uint32_t);
1407 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count);
1409 for(int i = 0; i < count; ++i)
1411 auto pixelBuffer = new unsigned char[bufferSize];
1413 mImpl->loaderInfo.animated.currentFrame = 1 + ((frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount);
1415 if(ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error))
1419 pixelData.push_back(Dali::PixelData::New(pixelBuffer, bufferSize, mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY));
1428 Dali::Devel::PixelBuffer GifLoading::LoadFrame(uint32_t frameIndex)
1431 Dali::Devel::PixelBuffer pixelBuffer;
1432 if(!mImpl->mLoadSucceeded)
1437 Mutex::ScopedLock lock(mImpl->mMutex);
1438 DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex);
1440 pixelBuffer = Dali::Devel::PixelBuffer::New(mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888);
1442 mImpl->loaderInfo.animated.currentFrame = 1 + (frameIndex % mImpl->loaderInfo.animated.frameCount);
1443 ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer.GetBuffer(), &error);
1447 pixelBuffer = Dali::Devel::PixelBuffer();
1452 ImageDimensions GifLoading::GetImageSize() const
1454 return ImageDimensions(mImpl->imageProperties.w, mImpl->imageProperties.h);
1457 uint32_t GifLoading::GetImageCount() const
1459 return mImpl->loaderInfo.animated.frameCount;
1462 uint32_t GifLoading::GetFrameInterval(uint32_t frameIndex) const
1464 return mImpl->loaderInfo.animated.frames[frameIndex].info.delay * 10;
1467 std::string GifLoading::GetUrl() const
1472 bool GifLoading::HasLoadingSucceeded() const
1474 return mImpl->mLoadSucceeded;
1477 } // namespace Adaptor
1479 } // namespace Internal