2 * Copyright (c) 2020 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>
24 #include <sys/types.h>
30 #include <dali/integration-api/debug.h>
31 #include <dali/public-api/images/pixel-data.h>
32 #include <dali/internal/imaging/common/file-download.h>
33 #include <dali/internal/system/common/file-reader.h>
35 #define IMG_TOO_BIG( w, h ) \
36 ( ( static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h) ) >= \
37 ( (1ULL << (29 * (sizeof(void *) / 4))) - 2048) )
39 #define LOADERR( x ) \
41 DALI_LOG_ERROR( x ); \
56 #if defined(DEBUG_ENABLED)
57 Debug::Filter *gGifLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" );
60 const int IMG_MAX_SIZE = 65000;
61 constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024;
64 const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
65 const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
77 dispose( DISPOSE_BACKGROUND ),
83 unsigned short delay; // delay time in 1/100ths of a sec
84 short transparent : 10; // -1 == not, anything else == index
85 short dispose : 6; // 0, 1, 2, 3 (others invalid)
86 short interlace : 1; // interlaced or not
104 uint32_t *data; /* frame decoding data */
105 FrameInfo info; /* special image type info */
109 struct GifAnimationData
120 std::vector<ImageFrame> frames;
138 : fileName( nullptr ),
139 globalMap ( nullptr ),
141 isLocalResource( true )
145 const char *fileName; /**< The absolute path of the file. */
146 unsigned char *globalMap ; /**< A pointer to the entire contents of the file that have been mapped with mmap(2). */
147 long long length; /**< The length of the file in bytes. */
148 bool isLocalResource; /**< The flag whether the file is a local resource */
161 int position, length; // yes - gif uses ints for file sizes.
165 GifAnimationData animated;
171 struct ImageProperties
186 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
188 * @param[in] animated A structure containing GIF animation data
189 * @param[in] index Frame index to be searched in GIF
190 * @return A pointer to the ImageFrame.
192 inline int CombinePixelABGR( int a, int r, int g, int b )
194 return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) );
197 inline int PixelLookup( ColorMapObject *colorMap, int index )
199 return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue );
203 * @brief Brute force find frame index - gifs are normally small so ok for now.
205 * @param[in] animated A structure containing GIF animation data
206 * @param[in] index Frame index to be searched in GIF
207 * @return A pointer to the ImageFrame.
209 ImageFrame *FindFrame( const GifAnimationData &animated, int index )
211 for( auto &&elem : animated.frames )
213 if( elem.index == index )
215 return const_cast<ImageFrame *>( &elem );
222 * @brief Fill in an image with a specific rgba color value.
224 * @param[in] data A pointer pointing to an image data
225 * @param[in] row A int containing the number of rows in an image
226 * @param[in] val A uint32_t containing rgba color value
227 * @param[in] x X-coordinate used an offset to calculate pixel position
228 * @param[in] y Y-coordinate used an offset to calculate pixel position
229 * @param[in] width Width of the image
230 * @param[in] height Height of the image
232 void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height )
235 uint32_t *pixelPosition;
237 for( yAxis = 0; yAxis < height; yAxis++ )
239 pixelPosition = data + ((y + yAxis) * row) + x;
240 for( xAxis = 0; xAxis < width; xAxis++ )
242 *pixelPosition = val;
249 * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
251 * @param[in] data A pointer pointing to an image data
252 * @param[in] row A int containing the number of rows in an image
253 * @param[in] gif A pointer pointing to GIF File Type
254 * @param[in] frameInfo A pointer pointing to Frame Information data
255 * @param[in] x X-coordinate used an offset to calculate pixel position
256 * @param[in] y Y-coordinate used an offset to calculate pixel position
257 * @param[in] width Width of the image
258 * @param[in] height Height of the image
260 void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h )
262 // solid color fill for pre frame region
263 if( frameInfo->transparent < 0 )
265 ColorMapObject *colorMap;
268 // work out color to use from colorMap
269 if( gif->Image.ColorMap )
271 colorMap = gif->Image.ColorMap;
275 colorMap = gif->SColorMap;
277 backGroundColor = gif->SBackGroundColor;
279 FillImage( data, row,
280 CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red,
281 colorMap->Colors[backGroundColor].Green,
282 colorMap->Colors[backGroundColor].Blue ),
285 // fill in region with 0 (transparent)
288 FillImage( data, row, 0, x, y, w, h );
293 * @brief Store common fields from gif file info into frame info
295 * @param[in] gif A pointer pointing to GIF File Type
296 * @param[in] frameInfo A pointer pointing to Frame Information data
298 void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo )
300 frameInfo->x = gif->Image.Left;
301 frameInfo->y = gif->Image.Top;
302 frameInfo->w = gif->Image.Width;
303 frameInfo->h = gif->Image.Height;
304 frameInfo->interlace = gif->Image.Interlace;
308 * @brief Check if image fills "screen space" and if so, if it is transparent
309 * at all then the image could be transparent - OR if image doesnt fill,
310 * then it could be trasnparent (full coverage of screen). Some gifs will
311 * be recognized as solid here for faster rendering, but not all.
313 * @param[out] full A boolean to show whether image is transparent or not
314 * @param[in] frameInfo A pointer pointing to Frame Information data
315 * @param[in] width Width of the image
316 * @param[in] height Height of the image
318 void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height )
320 if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) &&
321 ( frameInfo->w == width ) && ( frameInfo->h == height ) )
323 if( frameInfo->transparent >= 0 )
335 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
337 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 )
345 if( (x0 + w0) > imageWidth )
347 w0 = imageWidth - x0;
355 if( (y0 + h0) > imageHeight )
357 h0 = imageHeight - y0;
366 * @brief Flush out rgba frame images to save memory but skip current,
367 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
369 * @param[in] animated A structure containing GIF animation data
370 * @param[in] width Width of the image
371 * @param[in] height Height of the image
372 * @param[in] thisframe The current frame
373 * @param[in] prevframe The previous frame
374 * @param[in] lastPreservedFrame The last preserved frame
376 void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame )
378 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" );
380 // target is the amount of memory we want to be under for stored frames
381 int total = 0, target = 512 * 1024;
383 // total up the amount of memory used by stored frames for this image
384 for( auto &&frame : animated.frames )
391 total *= ( width * height * sizeof( uint32_t ) );
393 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total );
395 // If we use more than target (512k) for frames - flush
398 // Clean frames (except current and previous) until below target
399 for( auto &&frame : animated.frames )
401 if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
402 (!lastPreservedFrame || frame.index != lastPreservedFrame->index) )
404 if( frame.data != nullptr )
407 frame.data = nullptr;
409 // subtract memory used and if below target - stop flush
410 total -= ( width * height * sizeof( uint32_t ) );
420 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" );
424 * @brief allocate frame and frame info and append to list and store fields.
426 * @param[in] animated A structure containing GIF animation data
427 * @param[in] transparent Transparent index of the new frame
428 * @param[in] dispose Dispose mode of new frame
429 * @param[in] delay The frame delay of new frame
430 * @param[in] index The index of new frame
432 FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index )
436 // record transparent index to be used or -1 if none
437 // for this SPECIFIC frame
438 frame.info.transparent = transparent;
439 // record dispose mode (3 bits)
440 frame.info.dispose = dispose;
441 // record delay (2 bytes so max 65546 /100 sec)
442 frame.info.delay = delay;
443 // record the index number we are at
445 // that frame is stored AT image/screen size
447 animated.frames.push_back( frame );
449 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() );
451 return &( animated.frames.back().info );
455 * @brief Copy data from gif file into buffer.
457 * @param[in] gifFileType A pointer pointing to GIF File Type
458 * @param[out] buffer A pointer to buffer containing GIF raw data
459 * @param[in] len The length in bytes to be copied
460 * @return The data length of the image in bytes
462 int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length )
464 LoaderInfo::FileInfo *fi = reinterpret_cast<LoaderInfo::FileInfo *>( gifFileType->UserData );
466 if( fi->position >= fi->length )
468 return 0; // if at or past end - no
470 if( (fi->position + length) >= fi->length )
472 length = fi->length - fi->position;
474 memcpy( buffer, fi->map + fi->position, length );
475 fi->position += length;
480 * @brief Decode a gif image into rows then expand to 32bit into the destination
483 bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin,
484 int transparent, int x, int y, int w, int h, bool fill )
486 int intoffset[] = {0, 4, 2, 1};
487 int intjump[] = {8, 8, 4, 2};
488 int i, xx, yy, pix, gifW, gifH;
489 GifRowType *rows = NULL;
491 ColorMapObject *colorMap;
494 // what we need is image size.
496 sp = &gif->SavedImages[ gif->ImageCount - 1 ];
502 gifW = sp->ImageDesc.Width;
503 gifH = sp->ImageDesc.Height;
505 if( ( gifW < w ) || ( gifH < h ) )
507 DALI_ASSERT_DEBUG( false && "Dimensions are bigger than the Gif image size");
511 // build a blob of memory to have pointers to rows of pixels
512 // AND store the decoded gif pixels (1 byte per pixel) as welll
513 rows = static_cast<GifRowType *>(malloc( (gifH * sizeof(GifRowType) ) + ( gifW * gifH * sizeof(GifPixelType) )));
519 // fill in the pointers at the start
520 for( yy = 0; yy < gifH; yy++ )
522 rows[yy] = reinterpret_cast<unsigned char *>(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType));
525 // if gif is interlaced, walk interlace pattern and decode into rows
526 if( gif->Image.Interlace )
528 for( i = 0; i < 4; i++ )
530 for( yy = intoffset[i]; yy < gifH; yy += intjump[i] )
532 if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK )
539 // normal top to bottom - decode into rows
542 for( yy = 0; yy < gifH; yy++ )
544 if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK )
551 // work out what colormap to use
552 if( gif->Image.ColorMap )
554 colorMap = gif->Image.ColorMap;
558 colorMap = gif->SColorMap;
561 // if we need to deal with transparent pixels at all...
562 if( transparent >= 0 )
564 // if we are told to FILL (overwrite with transparency kept)
567 for( yy = 0; yy < h; yy++ )
569 p = data + ((y + yy) * rowpix) + x;
570 for( xx = 0; xx < w; xx++ )
572 pix = rows[yin + yy][xin + xx];
573 if( pix != transparent )
575 *p = PixelLookup( colorMap, pix );
585 // paste on top with transparent pixels untouched
588 for( yy = 0; yy < h; yy++ )
590 p = data + ((y + yy) * rowpix) + x;
591 for( xx = 0; xx < w; xx++ )
593 pix = rows[yin + yy][xin + xx];
594 if( pix != transparent )
596 *p = PixelLookup( colorMap, pix );
605 // walk pixels without worring about transparency at all
606 for( yy = 0; yy < h; yy++ )
608 p = data + ((y + yy) * rowpix) + x;
609 for( xx = 0; xx < w; xx++ )
611 pix = rows[yin + yy][xin + xx];
612 *p = PixelLookup( colorMap, pix );
628 * @brief Reader header from the gif file and populates structures accordingly.
630 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
631 * @param[out] prop A ImageProperties structure for storing information about GIF data.
632 * @param[out] error Error code
633 * @return The true or false whether reading was successful or not.
635 bool ReadHeader( LoaderInfo &loaderInfo,
636 ImageProperties &prop, //output struct
639 GifAnimationData &animated = loaderInfo.animated;
640 LoaderInfo::FileData &fileData = loaderInfo.fileData;
642 LoaderInfo::FileInfo fileInfo;
644 GifFileType *gif = NULL;
645 // it is possible which gif file have error midle of frames,
646 // in that case we should play gif file until meet error frame.
649 FrameInfo *frameInfo = NULL;
652 if( fileData.isLocalResource )
654 Internal::Platform::FileReader fileReader( fileData.fileName );
655 FILE *fp = fileReader.GetFile();
661 if( fseek( fp, 0, SEEK_END ) <= -1 )
666 fileData.length = ftell( fp );
667 if( fileData.length <= -1 )
672 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
674 fileData.globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * fileData.length ) );
675 fileData.length = fread( fileData.globalMap, sizeof( GifByteType ), fileData.length, fp);
676 fileInfo.map = fileData.globalMap;
687 Dali::Vector<uint8_t> dataBuffer;
690 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( fileData.fileName, dataBuffer, dataSize,
691 MAXIMUM_DOWNLOAD_IMAGE_SIZE );
694 size_t blobSize = dataBuffer.Size();
697 // Open a file handle on the memory buffer:
698 Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize );
699 FILE * const fp = fileReader.GetFile();
702 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
704 fileData.globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * blobSize ) );
705 fileData.length = fread( fileData.globalMap, sizeof( GifByteType ), blobSize, fp);
706 fileInfo.map = fileData.globalMap;
710 DALI_LOG_ERROR( "Error seeking within file\n" );
715 DALI_LOG_ERROR( "Error reading file\n" );
723 LOADERR("LOAD_ERROR_CORRUPT_FILE");
725 fileInfo.length = fileData.length;
726 fileInfo.position = 0;
728 // actually ask libgif to open the file
729 #if GIFLIB_MAJOR >= 5
730 gif = DGifOpen( &fileInfo, FileRead, NULL );
732 gif = DGifOpen( &fileInfo, FileRead );
737 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
740 // get the gif "screen size" (the actual image size)
741 prop.w = gif->SWidth;
742 prop.h = gif->SHeight;
744 // if size is invalid - abort here
745 if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
747 if( IMG_TOO_BIG(prop.w, prop.h) )
749 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
751 LOADERR("LOAD_ERROR_GENERIC");
753 // walk through gif records in file to figure out info
756 if( DGifGetRecordType(gif, &rec) == GIF_ERROR )
758 // if we have a gif that ends part way through a sequence
759 // (or animation) consider it valid and just break - no error
760 if( imageNumber > 1 )
764 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
767 // get image description section
768 if( rec == IMAGE_DESC_RECORD_TYPE )
774 if( DGifGetImageDesc(gif) == GIF_ERROR )
776 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
778 // skip decoding and just walk image to next
779 if( DGifGetCode(gif, &img_code, &img) == GIF_ERROR )
781 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
787 DGifGetCodeNext( gif, &img );
789 // store geometry in the last frame info data
792 StoreFrameInfo( gif, frameInfo );
793 CheckTransparency( full, frameInfo, prop.w, prop.h );
795 // or if we dont have a frameInfo entry - create one even for stills
798 // allocate and save frame with field data
799 frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
802 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
804 // store geometry info from gif image
805 StoreFrameInfo( gif, frameInfo );
806 // check for transparency/alpha
807 CheckTransparency( full, frameInfo, prop.w, prop.h );
811 // we have an extension code block - for animated gifs for sure
812 else if( rec == EXTENSION_RECORD_TYPE )
818 // get the first extension entry
819 DGifGetExtension( gif, &ext_code, &ext );
822 // graphic control extension - for animated gif data
823 // and transparent index + flag
824 if( ext_code == 0xf9 )
826 // create frame and store it in image
827 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
828 int disposeMode = (ext[1] >> 2) & 0x7;
829 int delay = (int(ext[3]) << 8) | int(ext[2]);
830 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
833 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
836 // netscape extension indicating loop count.
837 else if( ext_code == 0xff ) /* application extension */
839 if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
840 !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
843 DGifGetExtensionNext( gif, &ext );
846 loopCount = (int(ext[3]) << 8) | int(ext[2]);
854 // and continue onto the next extension entry
856 DGifGetExtensionNext( gif, &ext );
859 } while( rec != TERMINATE_RECORD_TYPE );
861 // if the gif main says we have more than one image or our image counting
862 // says so, then this image is animated - indicate this
863 if( (gif->ImageCount > 1) || (imageNumber > 1) )
865 animated.animated = 1;
866 animated.loopCount = loopCount;
868 animated.frameCount = std::min( gif->ImageCount, imageNumber );
875 animated.currentFrame = 1;
877 // no errors in header scan etc. so set err and return value
881 on_error: // jump here on any errors to clean up
882 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
885 DGifCloseFile( gif, NULL );
890 DGifCloseFile( gif );
898 * @brief Reader next frame of the gif file and populates structures accordingly.
900 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
901 * @param[in/out] prop A ImageProperties structure containing information about gif data.
902 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
903 * @param[out] error Error code
904 * @return The true or false whether reading was successful or not.
906 bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
907 unsigned char *pixels, int *error )
909 GifAnimationData &animated = loaderInfo.animated;
910 LoaderInfo::FileData &fileData = loaderInfo.fileData;
913 GifFileType *gif = NULL;
914 int index = 0, imageNumber = 0;
915 FrameInfo *frameInfo;
916 ImageFrame *frame = NULL;
917 ImageFrame *lastPreservedFrame = NULL;
919 index = animated.currentFrame;
921 // if index is invalid for animated image - error out
922 if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
924 LOADERR("LOAD_ERROR_GENERIC");
927 // find the given frame index
928 frame = FindFrame( animated, index );
931 if( (frame->loaded) && (frame->data) )
933 // frame is already there and decoded - jump to end
939 LOADERR("LOAD_ERROR_CORRUPT_FILE");
943 // actually ask libgif to open the file
944 gif = loaderInfo.gif;
947 loaderInfo.fileInfo.map = fileData.globalMap ;
948 if( !loaderInfo.fileInfo.map )
950 LOADERR("LOAD_ERROR_CORRUPT_FILE");
952 loaderInfo.fileInfo.length = fileData.length;
953 loaderInfo.fileInfo.position = 0;
955 #if GIFLIB_MAJOR >= 5
956 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead, NULL );
958 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead );
960 // if gif open failed... get out of here
963 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
965 loaderInfo.gif = gif;
966 loaderInfo.imageNumber = 1;
969 // if we want to go backwards, we likely need/want to re-decode from the
970 // start as we have nothing to build on
971 if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
973 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
975 DGifCloseFile( loaderInfo.gif, NULL );
978 DGifCloseFile( loaderInfo.gif );
980 loaderInfo.gif = NULL;
981 loaderInfo.imageNumber = 0;
985 // our current position is the previous frame we decoded from the file
986 imageNumber = loaderInfo.imageNumber;
988 // walk through gif records in file to figure out info
991 if( DGifGetRecordType( gif, &rec ) == GIF_ERROR )
993 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
996 if( rec == EXTENSION_RECORD_TYPE )
999 GifByteType *ext = NULL;
1000 DGifGetExtension( gif, &ext_code, &ext );
1005 DGifGetExtensionNext( gif, &ext );
1008 // get image description section
1009 else if( rec == IMAGE_DESC_RECORD_TYPE )
1011 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1014 ImageFrame *previousFrame = NULL;
1015 ImageFrame *thisFrame = NULL;
1018 if( DGifGetImageDesc(gif) == GIF_ERROR )
1020 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1023 // get the previous frame entry AND the current one to fill in
1024 previousFrame = FindFrame(animated, imageNumber - 1);
1025 thisFrame = FindFrame(animated, imageNumber);
1027 // if we have a frame AND we're animated AND we have no data...
1028 if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
1033 thisFrame->data = new uint32_t[prop.w * prop.h];
1035 if( !thisFrame->data )
1037 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1040 // if we have no prior frame OR prior frame data... empty
1041 if( (!previousFrame) || (!previousFrame->data) )
1044 frameInfo = &(thisFrame->info);
1045 memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
1047 // we have a prior frame to copy data from...
1050 frameInfo = &( previousFrame->info );
1052 // fix coords of sub image in case it goes out...
1053 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1054 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1057 // if dispose mode is not restore - then copy pre frame
1058 if( frameInfo->dispose != DISPOSE_PREVIOUS )
1060 memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1063 // if dispose mode is "background" then fill with bg
1064 if( frameInfo->dispose == DISPOSE_BACKGROUND )
1066 FillFrame( thisFrame->data, prop.w, gif, frameInfo, x, y, w, h );
1068 else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
1073 // Find last preserved frame.
1074 lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
1075 if( ! lastPreservedFrame )
1077 LOADERR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
1080 } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
1082 if ( lastPreservedFrame )
1084 memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1088 // now draw this frame on top
1089 frameInfo = &( thisFrame->info );
1090 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1091 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1093 if( !DecodeImage( gif, thisFrame->data, prop.w,
1094 xin, yin, frameInfo->transparent,
1095 x, y, w, h, first) )
1097 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1100 // mark as loaded and done
1101 thisFrame->loaded = true;
1103 FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
1105 // if we have a frame BUT the image is not animated. different
1107 else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
1109 // if we don't have the data decoded yet - decode it
1110 if( (!thisFrame->loaded) || (!thisFrame->data) )
1112 // use frame info but we WONT allocate frame pixels
1113 frameInfo = &( thisFrame->info );
1114 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1115 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1118 // clear out all pixels
1119 FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, gif, frameInfo, 0, 0, prop.w, prop.h );
1121 // and decode the gif with overwriting
1122 if( !DecodeImage( gif, reinterpret_cast<uint32_t *>(pixels), prop.w,
1123 xin, yin, frameInfo->transparent, x, y, w, h, true) )
1125 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1128 // mark as loaded and done
1129 thisFrame->loaded = true;
1131 // flush mem we don't need (at expense of decode cpu)
1135 // skip decoding and just walk image to next
1136 if( DGifGetCode( gif, &img_code, &img ) == GIF_ERROR )
1138 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1144 DGifGetCodeNext( gif, &img );
1149 // if we found the image we wanted - get out of here
1150 if( imageNumber > index )
1155 } while( rec != TERMINATE_RECORD_TYPE );
1157 // if we are at the end of the animation or not animated, close file
1158 loaderInfo.imageNumber = imageNumber;
1159 if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
1161 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
1162 if( loaderInfo.gif )
1164 DGifCloseFile( loaderInfo.gif, NULL );
1167 if( loaderInfo.gif )
1169 DGifCloseFile( loaderInfo.gif );
1173 loaderInfo.gif = NULL;
1174 loaderInfo.imageNumber = 0;
1178 // no errors in header scan etc. so set err and return value
1182 // if it was an animated image we need to copy the data to the
1183 // pixels for the image from the frame holding the data
1184 if( animated.animated && frame->data )
1186 memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
1189 on_error: // jump here on any errors to clean up
1193 } // unnamed namespace
1195 struct GifLoading::Impl
1198 Impl( const std::string& url, bool isLocalResource )
1201 loaderInfo.gif = nullptr;
1203 loaderInfo.fileData.fileName = mUrl.c_str();
1204 loaderInfo.fileData.isLocalResource = isLocalResource;
1206 ReadHeader( loaderInfo, imageProperties, &error );
1209 // Moveable but not copyable
1211 Impl( const Impl& ) = delete;
1212 Impl& operator=( const Impl& ) = delete;
1213 Impl( Impl&& ) = default;
1214 Impl& operator=( Impl&& ) = default;
1218 if( loaderInfo.fileData.globalMap )
1220 free( loaderInfo.fileData.globalMap );
1221 loaderInfo.fileData.globalMap = nullptr;
1224 // Delete all image frames
1225 for( auto &&frame : loaderInfo.animated.frames )
1227 if( frame.data != nullptr )
1229 // De-allocate memory of the frame data.
1230 delete[] frame.data;
1231 frame.data = nullptr;
1237 LoaderInfo loaderInfo;
1238 ImageProperties imageProperties;
1241 AnimatedImageLoadingPtr GifLoading::New( const std::string &url, bool isLocalResource )
1243 return AnimatedImageLoadingPtr( new GifLoading( url, isLocalResource ) );
1246 GifLoading::GifLoading( const std::string &url, bool isLocalResource )
1247 : mImpl( new GifLoading::Impl( url, isLocalResource ) )
1252 GifLoading::~GifLoading()
1257 bool GifLoading::LoadNextNFrames( uint32_t frameStartIndex, int count, std::vector<Dali::PixelData> &pixelData )
1262 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t );
1264 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count );
1266 for( int i = 0; i < count; ++i )
1268 auto pixelBuffer = new unsigned char[ bufferSize ];
1270 mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount );
1272 if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) )
1276 pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize,
1277 mImpl->imageProperties.w, mImpl->imageProperties.h,
1278 Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) );
1287 ImageDimensions GifLoading::GetImageSize() const
1289 return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.h );
1292 uint32_t GifLoading::GetImageCount() const
1294 return mImpl->loaderInfo.animated.frameCount;
1297 uint32_t GifLoading::GetFrameInterval( uint32_t frameIndex ) const
1299 return mImpl->loaderInfo.animated.frames[frameIndex].info.delay * 10;
1302 } // namespace Adaptor
1304 } // namespace Internal