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 ];
498 gifW = sp->ImageDesc.Width;
499 gifH = sp->ImageDesc.Height;
501 if( ( gifW < w ) || ( gifH < h ) )
503 DALI_ASSERT_DEBUG( false && "Dimensions are bigger than the Gif image size");
507 // build a blob of memory to have pointers to rows of pixels
508 // AND store the decoded gif pixels (1 byte per pixel) as welll
509 rows = static_cast<GifRowType *>(malloc( (gifH * sizeof(GifRowType) ) + ( gifW * gifH * sizeof(GifPixelType) )));
515 // fill in the pointers at the start
516 for( yy = 0; yy < gifH; yy++ )
518 rows[yy] = reinterpret_cast<unsigned char *>(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType));
521 // if gif is interlaced, walk interlace pattern and decode into rows
522 if( gif->Image.Interlace )
524 for( i = 0; i < 4; i++ )
526 for( yy = intoffset[i]; yy < gifH; yy += intjump[i] )
528 if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK )
535 // normal top to bottom - decode into rows
538 for( yy = 0; yy < gifH; yy++ )
540 if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK )
547 // work out what colormap to use
548 if( gif->Image.ColorMap )
550 colorMap = gif->Image.ColorMap;
554 colorMap = gif->SColorMap;
557 // if we need to deal with transparent pixels at all...
558 if( transparent >= 0 )
560 // if we are told to FILL (overwrite with transparency kept)
563 for( yy = 0; yy < h; yy++ )
565 p = data + ((y + yy) * rowpix) + x;
566 for( xx = 0; xx < w; xx++ )
568 pix = rows[yin + yy][xin + xx];
569 if( pix != transparent )
571 *p = PixelLookup( colorMap, pix );
581 // paste on top with transparent pixels untouched
584 for( yy = 0; yy < h; yy++ )
586 p = data + ((y + yy) * rowpix) + x;
587 for( xx = 0; xx < w; xx++ )
589 pix = rows[yin + yy][xin + xx];
590 if( pix != transparent )
592 *p = PixelLookup( colorMap, pix );
601 // walk pixels without worring about transparency at all
602 for( yy = 0; yy < h; yy++ )
604 p = data + ((y + yy) * rowpix) + x;
605 for( xx = 0; xx < w; xx++ )
607 pix = rows[yin + yy][xin + xx];
608 *p = PixelLookup( colorMap, pix );
624 * @brief Reader header from the gif file and populates structures accordingly.
626 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
627 * @param[out] prop A ImageProperties structure for storing information about GIF data.
628 * @param[out] error Error code
629 * @return The true or false whether reading was successful or not.
631 bool ReadHeader( LoaderInfo &loaderInfo,
632 ImageProperties &prop, //output struct
635 GifAnimationData &animated = loaderInfo.animated;
636 LoaderInfo::FileData &fileData = loaderInfo.fileData;
638 LoaderInfo::FileInfo fileInfo;
640 GifFileType *gif = NULL;
641 // it is possible which gif file have error midle of frames,
642 // in that case we should play gif file until meet error frame.
645 FrameInfo *frameInfo = NULL;
648 if( fileData.isLocalResource )
650 Internal::Platform::FileReader fileReader( fileData.fileName );
651 FILE *fp = fileReader.GetFile();
657 if( fseek( fp, 0, SEEK_END ) <= -1 )
662 fileData.length = ftell( fp );
663 if( fileData.length <= -1 )
668 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
670 fileData.globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * fileData.length ) );
671 fileData.length = fread( fileData.globalMap, sizeof( GifByteType ), fileData.length, fp);
672 fileInfo.map = fileData.globalMap;
683 Dali::Vector<uint8_t> dataBuffer;
686 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( fileData.fileName, dataBuffer, dataSize,
687 MAXIMUM_DOWNLOAD_IMAGE_SIZE );
690 size_t blobSize = dataBuffer.Size();
693 // Open a file handle on the memory buffer:
694 Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize );
695 FILE * const fp = fileReader.GetFile();
698 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
700 fileData.globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * blobSize ) );
701 fileData.length = fread( fileData.globalMap, sizeof( GifByteType ), blobSize, fp);
702 fileInfo.map = fileData.globalMap;
706 DALI_LOG_ERROR( "Error seeking within file\n" );
711 DALI_LOG_ERROR( "Error reading file\n" );
719 LOADERR("LOAD_ERROR_CORRUPT_FILE");
721 fileInfo.length = fileData.length;
722 fileInfo.position = 0;
724 // actually ask libgif to open the file
725 #if GIFLIB_MAJOR >= 5
726 gif = DGifOpen( &fileInfo, FileRead, NULL );
728 gif = DGifOpen( &fileInfo, FileRead );
733 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
736 // get the gif "screen size" (the actual image size)
737 prop.w = gif->SWidth;
738 prop.h = gif->SHeight;
740 // if size is invalid - abort here
741 if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
743 if( IMG_TOO_BIG(prop.w, prop.h) )
745 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
747 LOADERR("LOAD_ERROR_GENERIC");
749 // walk through gif records in file to figure out info
752 if( DGifGetRecordType(gif, &rec) == GIF_ERROR )
754 // if we have a gif that ends part way through a sequence
755 // (or animation) consider it valid and just break - no error
756 if( imageNumber > 1 )
760 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
763 // get image description section
764 if( rec == IMAGE_DESC_RECORD_TYPE )
770 if( DGifGetImageDesc(gif) == GIF_ERROR )
772 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
774 // skip decoding and just walk image to next
775 if( DGifGetCode(gif, &img_code, &img) == GIF_ERROR )
777 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
783 DGifGetCodeNext( gif, &img );
785 // store geometry in the last frame info data
788 StoreFrameInfo( gif, frameInfo );
789 CheckTransparency( full, frameInfo, prop.w, prop.h );
791 // or if we dont have a frameInfo entry - create one even for stills
794 // allocate and save frame with field data
795 frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
798 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
800 // store geometry info from gif image
801 StoreFrameInfo( gif, frameInfo );
802 // check for transparency/alpha
803 CheckTransparency( full, frameInfo, prop.w, prop.h );
807 // we have an extension code block - for animated gifs for sure
808 else if( rec == EXTENSION_RECORD_TYPE )
814 // get the first extension entry
815 DGifGetExtension( gif, &ext_code, &ext );
818 // graphic control extension - for animated gif data
819 // and transparent index + flag
820 if( ext_code == 0xf9 )
822 // create frame and store it in image
823 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
824 int disposeMode = (ext[1] >> 2) & 0x7;
825 int delay = (int(ext[3]) << 8) | int(ext[2]);
826 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
829 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
832 // netscape extension indicating loop count.
833 else if( ext_code == 0xff ) /* application extension */
835 if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
836 !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
839 DGifGetExtensionNext( gif, &ext );
842 loopCount = (int(ext[3]) << 8) | int(ext[2]);
850 // and continue onto the next extension entry
852 DGifGetExtensionNext( gif, &ext );
855 } while( rec != TERMINATE_RECORD_TYPE );
857 // if the gif main says we have more than one image or our image counting
858 // says so, then this image is animated - indicate this
859 if( (gif->ImageCount > 1) || (imageNumber > 1) )
861 animated.animated = 1;
862 animated.loopCount = loopCount;
864 animated.frameCount = std::min( gif->ImageCount, imageNumber );
871 animated.currentFrame = 1;
873 // no errors in header scan etc. so set err and return value
877 on_error: // jump here on any errors to clean up
878 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
881 DGifCloseFile( gif, NULL );
886 DGifCloseFile( gif );
894 * @brief Reader next frame of the gif file and populates structures accordingly.
896 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
897 * @param[in/out] prop A ImageProperties structure containing information about gif data.
898 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
899 * @param[out] error Error code
900 * @return The true or false whether reading was successful or not.
902 bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
903 unsigned char *pixels, int *error )
905 GifAnimationData &animated = loaderInfo.animated;
906 LoaderInfo::FileData &fileData = loaderInfo.fileData;
909 GifFileType *gif = NULL;
910 int index = 0, imageNumber = 0;
911 FrameInfo *frameInfo;
912 ImageFrame *frame = NULL;
913 ImageFrame *lastPreservedFrame = NULL;
915 index = animated.currentFrame;
917 // if index is invalid for animated image - error out
918 if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
920 LOADERR("LOAD_ERROR_GENERIC");
923 // find the given frame index
924 frame = FindFrame( animated, index );
927 if( (frame->loaded) && (frame->data) )
929 // frame is already there and decoded - jump to end
935 LOADERR("LOAD_ERROR_CORRUPT_FILE");
939 // actually ask libgif to open the file
940 gif = loaderInfo.gif;
943 loaderInfo.fileInfo.map = fileData.globalMap ;
944 if( !loaderInfo.fileInfo.map )
946 LOADERR("LOAD_ERROR_CORRUPT_FILE");
948 loaderInfo.fileInfo.length = fileData.length;
949 loaderInfo.fileInfo.position = 0;
951 #if GIFLIB_MAJOR >= 5
952 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead, NULL );
954 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead );
956 // if gif open failed... get out of here
959 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
961 loaderInfo.gif = gif;
962 loaderInfo.imageNumber = 1;
965 // if we want to go backwards, we likely need/want to re-decode from the
966 // start as we have nothing to build on
967 if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
969 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
971 DGifCloseFile( loaderInfo.gif, NULL );
974 DGifCloseFile( loaderInfo.gif );
976 loaderInfo.gif = NULL;
977 loaderInfo.imageNumber = 0;
981 // our current position is the previous frame we decoded from the file
982 imageNumber = loaderInfo.imageNumber;
984 // walk through gif records in file to figure out info
987 if( DGifGetRecordType( gif, &rec ) == GIF_ERROR )
989 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
992 if( rec == EXTENSION_RECORD_TYPE )
995 GifByteType *ext = NULL;
996 DGifGetExtension( gif, &ext_code, &ext );
1001 DGifGetExtensionNext( gif, &ext );
1004 // get image description section
1005 else if( rec == IMAGE_DESC_RECORD_TYPE )
1007 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1010 ImageFrame *previousFrame = NULL;
1011 ImageFrame *thisFrame = NULL;
1014 if( DGifGetImageDesc(gif) == GIF_ERROR )
1016 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1019 // get the previous frame entry AND the current one to fill in
1020 previousFrame = FindFrame(animated, imageNumber - 1);
1021 thisFrame = FindFrame(animated, imageNumber);
1023 // if we have a frame AND we're animated AND we have no data...
1024 if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
1029 thisFrame->data = new uint32_t[prop.w * prop.h];
1031 if( !thisFrame->data )
1033 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1036 // if we have no prior frame OR prior frame data... empty
1037 if( (!previousFrame) || (!previousFrame->data) )
1040 frameInfo = &(thisFrame->info);
1041 memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
1043 // we have a prior frame to copy data from...
1046 frameInfo = &( previousFrame->info );
1048 // fix coords of sub image in case it goes out...
1049 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1050 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1053 // if dispose mode is not restore - then copy pre frame
1054 if( frameInfo->dispose != DISPOSE_PREVIOUS )
1056 memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1059 // if dispose mode is "background" then fill with bg
1060 if( frameInfo->dispose == DISPOSE_BACKGROUND )
1062 FillFrame( thisFrame->data, prop.w, gif, frameInfo, x, y, w, h );
1064 else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
1069 // Find last preserved frame.
1070 lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
1071 if( ! lastPreservedFrame )
1073 LOADERR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
1076 } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
1078 if ( lastPreservedFrame )
1080 memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1084 // now draw this frame on top
1085 frameInfo = &( thisFrame->info );
1086 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1087 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1089 if( !DecodeImage( gif, thisFrame->data, prop.w,
1090 xin, yin, frameInfo->transparent,
1091 x, y, w, h, first) )
1093 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1096 // mark as loaded and done
1097 thisFrame->loaded = true;
1099 FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
1101 // if we have a frame BUT the image is not animated. different
1103 else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
1105 // if we don't have the data decoded yet - decode it
1106 if( (!thisFrame->loaded) || (!thisFrame->data) )
1108 // use frame info but we WONT allocate frame pixels
1109 frameInfo = &( thisFrame->info );
1110 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1111 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1114 // clear out all pixels
1115 FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, gif, frameInfo, 0, 0, prop.w, prop.h );
1117 // and decode the gif with overwriting
1118 if( !DecodeImage( gif, reinterpret_cast<uint32_t *>(pixels), prop.w,
1119 xin, yin, frameInfo->transparent, x, y, w, h, true) )
1121 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1124 // mark as loaded and done
1125 thisFrame->loaded = true;
1127 // flush mem we don't need (at expense of decode cpu)
1131 // skip decoding and just walk image to next
1132 if( DGifGetCode( gif, &img_code, &img ) == GIF_ERROR )
1134 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1140 DGifGetCodeNext( gif, &img );
1145 // if we found the image we wanted - get out of here
1146 if( imageNumber > index )
1151 } while( rec != TERMINATE_RECORD_TYPE );
1153 // if we are at the end of the animation or not animated, close file
1154 loaderInfo.imageNumber = imageNumber;
1155 if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
1157 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
1158 if( loaderInfo.gif )
1160 DGifCloseFile( loaderInfo.gif, NULL );
1163 if( loaderInfo.gif )
1165 DGifCloseFile( loaderInfo.gif );
1169 loaderInfo.gif = NULL;
1170 loaderInfo.imageNumber = 0;
1174 // no errors in header scan etc. so set err and return value
1178 // if it was an animated image we need to copy the data to the
1179 // pixels for the image from the frame holding the data
1180 if( animated.animated && frame->data )
1182 memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
1185 on_error: // jump here on any errors to clean up
1189 } // unnamed namespace
1191 struct GifLoading::Impl
1194 Impl( const std::string& url, bool isLocalResource )
1197 loaderInfo.gif = nullptr;
1199 loaderInfo.fileData.fileName = mUrl.c_str();
1200 loaderInfo.fileData.isLocalResource = isLocalResource;
1202 ReadHeader( loaderInfo, imageProperties, &error );
1205 // Moveable but not copyable
1207 Impl( const Impl& ) = delete;
1208 Impl& operator=( const Impl& ) = delete;
1209 Impl( Impl&& ) = default;
1210 Impl& operator=( Impl&& ) = default;
1214 if( loaderInfo.fileData.globalMap )
1216 free( loaderInfo.fileData.globalMap );
1217 loaderInfo.fileData.globalMap = nullptr;
1220 // Delete all image frames
1221 for( auto &&frame : loaderInfo.animated.frames )
1223 if( frame.data != nullptr )
1225 // De-allocate memory of the frame data.
1226 delete[] frame.data;
1227 frame.data = nullptr;
1233 LoaderInfo loaderInfo;
1234 ImageProperties imageProperties;
1237 AnimatedImageLoadingPtr GifLoading::New( const std::string &url, bool isLocalResource )
1239 return AnimatedImageLoadingPtr( new GifLoading( url, isLocalResource ) );
1242 GifLoading::GifLoading( const std::string &url, bool isLocalResource )
1243 : mImpl( new GifLoading::Impl( url, isLocalResource ) )
1248 GifLoading::~GifLoading()
1253 bool GifLoading::LoadNextNFrames( uint32_t frameStartIndex, int count, std::vector<Dali::PixelData> &pixelData )
1258 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t );
1260 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count );
1262 for( int i = 0; i < count; ++i )
1264 auto pixelBuffer = new unsigned char[ bufferSize ];
1266 mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount );
1268 if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) )
1272 pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize,
1273 mImpl->imageProperties.w, mImpl->imageProperties.h,
1274 Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) );
1283 Dali::Devel::PixelBuffer GifLoading::LoadFrame( uint32_t frameIndex )
1286 Dali::Devel::PixelBuffer pixelBuffer;
1288 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex );
1290 pixelBuffer = Dali::Devel::PixelBuffer::New( mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888 );
1292 mImpl->loaderInfo.animated.currentFrame = 1 + ( frameIndex % mImpl->loaderInfo.animated.frameCount );
1293 ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer.GetBuffer(), &error );
1297 pixelBuffer = Dali::Devel::PixelBuffer();
1302 ImageDimensions GifLoading::GetImageSize() const
1304 return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.h );
1307 uint32_t GifLoading::GetImageCount() const
1309 return mImpl->loaderInfo.animated.frameCount;
1312 uint32_t GifLoading::GetFrameInterval( uint32_t frameIndex ) const
1314 return mImpl->loaderInfo.animated.frames[frameIndex].info.delay * 10;
1317 std::string GifLoading::GetUrl() const
1322 } // namespace Adaptor
1324 } // namespace Internal