2 * Copyright (c) 2019 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/devel-api/adaptor-framework/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 ); \
50 #if defined(DEBUG_ENABLED)
51 Debug::Filter *gGifLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" );
54 const int IMG_MAX_SIZE = 65000;
55 constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024;
58 const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
59 const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
71 dispose( DISPOSE_BACKGROUND ),
77 unsigned short delay; // delay time in 1/100ths of a sec
78 short transparent : 10; // -1 == not, anything else == index
79 short dispose : 6; // 0, 1, 2, 3 (others invalid)
80 short interlace : 1; // interlaced or not
98 uint32_t *data; /* frame decoding data */
99 FrameInfo info; /* special image type info */
103 struct GifAnimationData
114 std::vector<ImageFrame> frames;
132 : fileName( nullptr ),
133 globalMap ( nullptr ),
135 isLocalResource( true )
139 const char *fileName; /**< The absolute path of the file. */
140 unsigned char *globalMap ; /**< A pointer to the entire contents of the file that have been mapped with mmap(2). */
141 long long length; /**< The length of the file in bytes. */
142 bool isLocalResource; /**< The flag whether the file is a local resource */
155 int position, length; // yes - gif uses ints for file sizes.
159 GifAnimationData animated;
165 struct ImageProperties
180 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
182 * @param[in] animated A structure containing GIF animation data
183 * @param[in] index Frame index to be searched in GIF
184 * @return A pointer to the ImageFrame.
186 inline int CombinePixelABGR( int a, int r, int g, int b )
188 return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) );
191 inline int PixelLookup( ColorMapObject *colorMap, int index )
193 return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue );
197 * @brief Brute force find frame index - gifs are normally small so ok for now.
199 * @param[in] animated A structure containing GIF animation data
200 * @param[in] index Frame index to be searched in GIF
201 * @return A pointer to the ImageFrame.
203 ImageFrame *FindFrame( const GifAnimationData &animated, int index )
205 for( auto &&elem : animated.frames )
207 if( elem.index == index )
209 return const_cast<ImageFrame *>( &elem );
216 * @brief Fill in an image with a specific rgba color value.
218 * @param[in] data A pointer pointing to an image data
219 * @param[in] row A int containing the number of rows in an image
220 * @param[in] val A uint32_t containing rgba color value
221 * @param[in] x X-coordinate used an offset to calculate pixel position
222 * @param[in] y Y-coordinate used an offset to calculate pixel position
223 * @param[in] width Width of the image
224 * @param[in] height Height of the image
226 void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height )
229 uint32_t *pixelPosition;
231 for( yAxis = 0; yAxis < height; yAxis++ )
233 pixelPosition = data + ((y + yAxis) * row) + x;
234 for( xAxis = 0; xAxis < width; xAxis++ )
236 *pixelPosition = val;
243 * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
245 * @param[in] data A pointer pointing to an image data
246 * @param[in] row A int containing the number of rows in an image
247 * @param[in] gif A pointer pointing to GIF File Type
248 * @param[in] frameInfo A pointer pointing to Frame Information data
249 * @param[in] x X-coordinate used an offset to calculate pixel position
250 * @param[in] y Y-coordinate used an offset to calculate pixel position
251 * @param[in] width Width of the image
252 * @param[in] height Height of the image
254 void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h )
256 // solid color fill for pre frame region
257 if( frameInfo->transparent < 0 )
259 ColorMapObject *colorMap;
262 // work out color to use from colorMap
263 if( gif->Image.ColorMap )
265 colorMap = gif->Image.ColorMap;
269 colorMap = gif->SColorMap;
271 backGroundColor = gif->SBackGroundColor;
273 FillImage( data, row,
274 CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red,
275 colorMap->Colors[backGroundColor].Green,
276 colorMap->Colors[backGroundColor].Blue ),
279 // fill in region with 0 (transparent)
282 FillImage( data, row, 0, x, y, w, h );
287 * @brief Store common fields from gif file info into frame info
289 * @param[in] gif A pointer pointing to GIF File Type
290 * @param[in] frameInfo A pointer pointing to Frame Information data
292 void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo )
294 frameInfo->x = gif->Image.Left;
295 frameInfo->y = gif->Image.Top;
296 frameInfo->w = gif->Image.Width;
297 frameInfo->h = gif->Image.Height;
298 frameInfo->interlace = gif->Image.Interlace;
302 * @brief Check if image fills "screen space" and if so, if it is transparent
303 * at all then the image could be transparent - OR if image doesnt fill,
304 * then it could be trasnparent (full coverage of screen). Some gifs will
305 * be recognized as solid here for faster rendering, but not all.
307 * @param[out] full A boolean to show whether image is transparent or not
308 * @param[in] frameInfo A pointer pointing to Frame Information data
309 * @param[in] width Width of the image
310 * @param[in] height Height of the image
312 void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height )
314 if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) &&
315 ( frameInfo->w == width ) && ( frameInfo->h == height ) )
317 if( frameInfo->transparent >= 0 )
329 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
331 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 )
339 if( (x0 + w0) > imageWidth )
341 w0 = imageWidth - x0;
349 if( (y0 + h0) > imageHeight )
351 h0 = imageHeight - y0;
360 * @brief Flush out rgba frame images to save memory but skip current,
361 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
363 * @param[in] animated A structure containing GIF animation data
364 * @param[in] width Width of the image
365 * @param[in] height Height of the image
366 * @param[in] thisframe The current frame
367 * @param[in] prevframe The previous frame
368 * @param[in] lastPreservedFrame The last preserved frame
370 void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame )
372 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" );
374 // target is the amount of memory we want to be under for stored frames
375 int total = 0, target = 512 * 1024;
377 // total up the amount of memory used by stored frames for this image
378 for( auto &&frame : animated.frames )
385 total *= ( width * height * sizeof( uint32_t ) );
387 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total );
389 // If we use more than target (512k) for frames - flush
392 // Clean frames (except current and previous) until below target
393 for( auto &&frame : animated.frames )
395 if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
396 (!lastPreservedFrame || frame.index != lastPreservedFrame->index) )
398 if( frame.data != nullptr )
401 frame.data = nullptr;
403 // subtract memory used and if below target - stop flush
404 total -= ( width * height * sizeof( uint32_t ) );
414 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" );
418 * @brief allocate frame and frame info and append to list and store fields.
420 * @param[in] animated A structure containing GIF animation data
421 * @param[in] transparent Transparent index of the new frame
422 * @param[in] dispose Dispose mode of new frame
423 * @param[in] delay The frame delay of new frame
424 * @param[in] index The index of new frame
426 FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index )
430 // record transparent index to be used or -1 if none
431 // for this SPECIFIC frame
432 frame.info.transparent = transparent;
433 // record dispose mode (3 bits)
434 frame.info.dispose = dispose;
435 // record delay (2 bytes so max 65546 /100 sec)
436 frame.info.delay = delay;
437 // record the index number we are at
439 // that frame is stored AT image/screen size
441 animated.frames.push_back( frame );
443 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() );
445 return &( animated.frames.back().info );
449 * @brief Copy data from gif file into buffer.
451 * @param[in] gifFileType A pointer pointing to GIF File Type
452 * @param[out] buffer A pointer to buffer containing GIF raw data
453 * @param[in] len The length in bytes to be copied
454 * @return The data length of the image in bytes
456 int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length )
458 LoaderInfo::FileInfo *fi = reinterpret_cast<LoaderInfo::FileInfo *>( gifFileType->UserData );
460 if( fi->position >= fi->length )
462 return 0; // if at or past end - no
464 if( (fi->position + length) >= fi->length )
466 length = fi->length - fi->position;
468 memcpy( buffer, fi->map + fi->position, length );
469 fi->position += length;
474 * @brief Decode a gif image into rows then expand to 32bit into the destination
477 bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin,
478 int transparent, int x, int y, int w, int h, bool fill )
480 int intoffset[] = {0, 4, 2, 1};
481 int intjump[] = {8, 8, 4, 2};
482 int i, xx, yy, pix, gifW, gifH;
483 GifRowType *rows = NULL;
485 ColorMapObject *colorMap;
488 // what we need is image size.
490 sp = &gif->SavedImages[ gif->ImageCount - 1 ];
496 gifW = sp->ImageDesc.Width;
497 gifH = sp->ImageDesc.Height;
499 if( ( gifW < w ) || ( gifH < h ) )
501 DALI_ASSERT_DEBUG( false && "Dimensions are bigger than the Gif image size");
505 // build a blob of memory to have pointers to rows of pixels
506 // AND store the decoded gif pixels (1 byte per pixel) as welll
507 rows = static_cast<GifRowType *>(malloc( (gifH * sizeof(GifRowType) ) + ( gifW * gifH * sizeof(GifPixelType) )));
513 // fill in the pointers at the start
514 for( yy = 0; yy < gifH; yy++ )
516 rows[yy] = reinterpret_cast<unsigned char *>(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType));
519 // if gif is interlaced, walk interlace pattern and decode into rows
520 if( gif->Image.Interlace )
522 for( i = 0; i < 4; i++ )
524 for( yy = intoffset[i]; yy < gifH; yy += intjump[i] )
526 if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK )
533 // normal top to bottom - decode into rows
536 for( yy = 0; yy < gifH; yy++ )
538 if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK )
545 // work out what colormap to use
546 if( gif->Image.ColorMap )
548 colorMap = gif->Image.ColorMap;
552 colorMap = gif->SColorMap;
555 // if we need to deal with transparent pixels at all...
556 if( transparent >= 0 )
558 // if we are told to FILL (overwrite with transparency kept)
561 for( yy = 0; yy < h; yy++ )
563 p = data + ((y + yy) * rowpix) + x;
564 for( xx = 0; xx < w; xx++ )
566 pix = rows[yin + yy][xin + xx];
567 if( pix != transparent )
569 *p = PixelLookup( colorMap, pix );
579 // paste on top with transparent pixels untouched
582 for( yy = 0; yy < h; yy++ )
584 p = data + ((y + yy) * rowpix) + x;
585 for( xx = 0; xx < w; xx++ )
587 pix = rows[yin + yy][xin + xx];
588 if( pix != transparent )
590 *p = PixelLookup( colorMap, pix );
599 // walk pixels without worring about transparency at all
600 for( yy = 0; yy < h; yy++ )
602 p = data + ((y + yy) * rowpix) + x;
603 for( xx = 0; xx < w; xx++ )
605 pix = rows[yin + yy][xin + xx];
606 *p = PixelLookup( colorMap, pix );
622 * @brief Reader header from the gif file and populates structures accordingly.
624 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
625 * @param[out] prop A ImageProperties structure for storing information about GIF data.
626 * @param[out] error Error code
627 * @return The true or false whether reading was successful or not.
629 bool ReadHeader( LoaderInfo &loaderInfo,
630 ImageProperties &prop, //output struct
633 GifAnimationData &animated = loaderInfo.animated;
634 LoaderInfo::FileData &fileData = loaderInfo.fileData;
636 LoaderInfo::FileInfo fileInfo;
638 GifFileType *gif = NULL;
639 // it is possible which gif file have error midle of frames,
640 // in that case we should play gif file until meet error frame.
643 FrameInfo *frameInfo = NULL;
646 if( fileData.isLocalResource )
648 Internal::Platform::FileReader fileReader( fileData.fileName );
649 FILE *fp = fileReader.GetFile();
655 if( fseek( fp, 0, SEEK_END ) <= -1 )
660 fileData.length = ftell( fp );
661 if( fileData.length <= -1 )
666 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
668 fileData.globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * fileData.length ) );
669 fileData.length = fread( fileData.globalMap, sizeof( GifByteType ), fileData.length, fp);
670 fileInfo.map = fileData.globalMap;
681 Dali::Vector<uint8_t> dataBuffer;
684 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( fileData.fileName, dataBuffer, dataSize,
685 MAXIMUM_DOWNLOAD_IMAGE_SIZE );
688 size_t blobSize = dataBuffer.Size();
691 // Open a file handle on the memory buffer:
692 Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize );
693 FILE * const fp = fileReader.GetFile();
696 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
698 fileData.globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * blobSize ) );
699 fileData.length = fread( fileData.globalMap, sizeof( GifByteType ), blobSize, fp);
700 fileInfo.map = fileData.globalMap;
704 DALI_LOG_ERROR( "Error seeking within file\n" );
709 DALI_LOG_ERROR( "Error reading file\n" );
717 LOADERR("LOAD_ERROR_CORRUPT_FILE");
719 fileInfo.length = fileData.length;
720 fileInfo.position = 0;
722 // actually ask libgif to open the file
723 #if GIFLIB_MAJOR >= 5
724 gif = DGifOpen( &fileInfo, FileRead, NULL );
726 gif = DGifOpen( &fileInfo, FileRead );
731 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
734 // get the gif "screen size" (the actual image size)
735 prop.w = gif->SWidth;
736 prop.h = gif->SHeight;
738 // if size is invalid - abort here
739 if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
741 if( IMG_TOO_BIG(prop.w, prop.h) )
743 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
745 LOADERR("LOAD_ERROR_GENERIC");
747 // walk through gif records in file to figure out info
750 if( DGifGetRecordType(gif, &rec) == GIF_ERROR )
752 // if we have a gif that ends part way through a sequence
753 // (or animation) consider it valid and just break - no error
754 if( imageNumber > 1 )
758 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
761 // get image description section
762 if( rec == IMAGE_DESC_RECORD_TYPE )
768 if( DGifGetImageDesc(gif) == GIF_ERROR )
770 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
772 // skip decoding and just walk image to next
773 if( DGifGetCode(gif, &img_code, &img) == GIF_ERROR )
775 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
781 DGifGetCodeNext( gif, &img );
783 // store geometry in the last frame info data
786 StoreFrameInfo( gif, frameInfo );
787 CheckTransparency( full, frameInfo, prop.w, prop.h );
789 // or if we dont have a frameInfo entry - create one even for stills
792 // allocate and save frame with field data
793 frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
796 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
798 // store geometry info from gif image
799 StoreFrameInfo( gif, frameInfo );
800 // check for transparency/alpha
801 CheckTransparency( full, frameInfo, prop.w, prop.h );
805 // we have an extension code block - for animated gifs for sure
806 else if( rec == EXTENSION_RECORD_TYPE )
812 // get the first extension entry
813 DGifGetExtension( gif, &ext_code, &ext );
816 // graphic control extension - for animated gif data
817 // and transparent index + flag
818 if( ext_code == 0xf9 )
820 // create frame and store it in image
821 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
822 int disposeMode = (ext[1] >> 2) & 0x7;
823 int delay = (int(ext[3]) << 8) | int(ext[2]);
824 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
827 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
830 // netscape extension indicating loop count.
831 else if( ext_code == 0xff ) /* application extension */
833 if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
834 !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
837 DGifGetExtensionNext( gif, &ext );
840 loopCount = (int(ext[3]) << 8) | int(ext[2]);
848 // and continue onto the next extension entry
850 DGifGetExtensionNext( gif, &ext );
853 } while( rec != TERMINATE_RECORD_TYPE );
855 // if the gif main says we have more than one image or our image counting
856 // says so, then this image is animated - indicate this
857 if( (gif->ImageCount > 1) || (imageNumber > 1) )
859 animated.animated = 1;
860 animated.loopCount = loopCount;
862 animated.frameCount = std::min( gif->ImageCount, imageNumber );
869 animated.currentFrame = 1;
871 // no errors in header scan etc. so set err and return value
875 on_error: // jump here on any errors to clean up
876 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
879 DGifCloseFile( gif, NULL );
884 DGifCloseFile( gif );
892 * @brief Reader next frame of the gif file and populates structures accordingly.
894 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
895 * @param[in/out] prop A ImageProperties structure containing information about gif data.
896 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
897 * @param[out] error Error code
898 * @return The true or false whether reading was successful or not.
900 bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
901 unsigned char *pixels, int *error )
903 GifAnimationData &animated = loaderInfo.animated;
904 LoaderInfo::FileData &fileData = loaderInfo.fileData;
907 GifFileType *gif = NULL;
908 int index = 0, imageNumber = 0;
909 FrameInfo *frameInfo;
910 ImageFrame *frame = NULL;
911 ImageFrame *lastPreservedFrame = NULL;
913 index = animated.currentFrame;
915 // if index is invalid for animated image - error out
916 if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
918 LOADERR("LOAD_ERROR_GENERIC");
921 // find the given frame index
922 frame = FindFrame( animated, index );
925 if( (frame->loaded) && (frame->data) )
927 // frame is already there and decoded - jump to end
933 LOADERR("LOAD_ERROR_CORRUPT_FILE");
937 // actually ask libgif to open the file
938 gif = loaderInfo.gif;
941 loaderInfo.fileInfo.map = fileData.globalMap ;
942 if( !loaderInfo.fileInfo.map )
944 LOADERR("LOAD_ERROR_CORRUPT_FILE");
946 loaderInfo.fileInfo.length = fileData.length;
947 loaderInfo.fileInfo.position = 0;
949 #if GIFLIB_MAJOR >= 5
950 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead, NULL );
952 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead );
954 // if gif open failed... get out of here
957 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
959 loaderInfo.gif = gif;
960 loaderInfo.imageNumber = 1;
963 // if we want to go backwards, we likely need/want to re-decode from the
964 // start as we have nothing to build on
965 if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
967 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
969 DGifCloseFile( loaderInfo.gif, NULL );
972 DGifCloseFile( loaderInfo.gif );
974 loaderInfo.gif = NULL;
975 loaderInfo.imageNumber = 0;
979 // our current position is the previous frame we decoded from the file
980 imageNumber = loaderInfo.imageNumber;
982 // walk through gif records in file to figure out info
985 if( DGifGetRecordType( gif, &rec ) == GIF_ERROR )
987 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
990 if( rec == EXTENSION_RECORD_TYPE )
993 GifByteType *ext = NULL;
994 DGifGetExtension( gif, &ext_code, &ext );
999 DGifGetExtensionNext( gif, &ext );
1002 // get image description section
1003 else if( rec == IMAGE_DESC_RECORD_TYPE )
1005 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1008 ImageFrame *previousFrame = NULL;
1009 ImageFrame *thisFrame = NULL;
1012 if( DGifGetImageDesc(gif) == GIF_ERROR )
1014 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1017 // get the previous frame entry AND the current one to fill in
1018 previousFrame = FindFrame(animated, imageNumber - 1);
1019 thisFrame = FindFrame(animated, imageNumber);
1021 // if we have a frame AND we're animated AND we have no data...
1022 if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
1027 thisFrame->data = new uint32_t[prop.w * prop.h];
1029 if( !thisFrame->data )
1031 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1034 // if we have no prior frame OR prior frame data... empty
1035 if( (!previousFrame) || (!previousFrame->data) )
1038 frameInfo = &(thisFrame->info);
1039 memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
1041 // we have a prior frame to copy data from...
1044 frameInfo = &( previousFrame->info );
1046 // fix coords of sub image in case it goes out...
1047 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1048 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1051 // if dispose mode is not restore - then copy pre frame
1052 if( frameInfo->dispose != DISPOSE_PREVIOUS )
1054 memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1057 // if dispose mode is "background" then fill with bg
1058 if( frameInfo->dispose == DISPOSE_BACKGROUND )
1060 FillFrame( thisFrame->data, prop.w, gif, frameInfo, x, y, w, h );
1062 else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
1067 // Find last preserved frame.
1068 lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
1069 if( ! lastPreservedFrame )
1071 LOADERR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
1074 } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
1076 if ( lastPreservedFrame )
1078 memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1082 // now draw this frame on top
1083 frameInfo = &( thisFrame->info );
1084 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1085 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1087 if( !DecodeImage( gif, thisFrame->data, prop.w,
1088 xin, yin, frameInfo->transparent,
1089 x, y, w, h, first) )
1091 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1094 // mark as loaded and done
1095 thisFrame->loaded = true;
1097 FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
1099 // if we have a frame BUT the image is not animated. different
1101 else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
1103 // if we don't have the data decoded yet - decode it
1104 if( (!thisFrame->loaded) || (!thisFrame->data) )
1106 // use frame info but we WONT allocate frame pixels
1107 frameInfo = &( thisFrame->info );
1108 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1109 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1112 // clear out all pixels
1113 FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, gif, frameInfo, 0, 0, prop.w, prop.h );
1115 // and decode the gif with overwriting
1116 if( !DecodeImage( gif, reinterpret_cast<uint32_t *>(pixels), prop.w,
1117 xin, yin, frameInfo->transparent, x, y, w, h, true) )
1119 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1122 // mark as loaded and done
1123 thisFrame->loaded = true;
1125 // flush mem we don't need (at expense of decode cpu)
1129 // skip decoding and just walk image to next
1130 if( DGifGetCode( gif, &img_code, &img ) == GIF_ERROR )
1132 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1138 DGifGetCodeNext( gif, &img );
1143 // if we found the image we wanted - get out of here
1144 if( imageNumber > index )
1149 } while( rec != TERMINATE_RECORD_TYPE );
1151 // if we are at the end of the animation or not animated, close file
1152 loaderInfo.imageNumber = imageNumber;
1153 if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
1155 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
1156 if( loaderInfo.gif )
1158 DGifCloseFile( loaderInfo.gif, NULL );
1161 if( loaderInfo.gif )
1163 DGifCloseFile( loaderInfo.gif );
1167 loaderInfo.gif = NULL;
1168 loaderInfo.imageNumber = 0;
1172 // no errors in header scan etc. so set err and return value
1176 // if it was an animated image we need to copy the data to the
1177 // pixels for the image from the frame holding the data
1178 if( animated.animated && frame->data )
1180 memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
1183 on_error: // jump here on any errors to clean up
1187 } // unnamed namespace
1189 struct GifLoading::Impl
1192 Impl( const std::string& url, bool isLocalResource )
1195 loaderInfo.gif = nullptr;
1197 loaderInfo.fileData.fileName = mUrl.c_str();
1198 loaderInfo.fileData.isLocalResource = isLocalResource;
1200 ReadHeader( loaderInfo, imageProperties, &error );
1203 // Moveable but not copyable
1205 Impl( const Impl& ) = delete;
1206 Impl& operator=( const Impl& ) = delete;
1207 Impl( Impl&& ) = default;
1208 Impl& operator=( Impl&& ) = default;
1212 if( loaderInfo.fileData.globalMap )
1214 free( loaderInfo.fileData.globalMap );
1215 loaderInfo.fileData.globalMap = nullptr;
1218 // Delete all image frames
1219 for( auto &&frame : loaderInfo.animated.frames )
1221 if( frame.data != nullptr )
1223 // De-allocate memory of the frame data.
1224 delete[] frame.data;
1225 frame.data = nullptr;
1231 LoaderInfo loaderInfo;
1232 ImageProperties imageProperties;
1235 std::unique_ptr<GifLoading> GifLoading::New( const std::string &url, bool isLocalResource )
1237 return std::unique_ptr<GifLoading>( new GifLoading( url, isLocalResource ) );
1240 GifLoading::GifLoading( const std::string &url, bool isLocalResource )
1241 : mImpl( new GifLoading::Impl( url, isLocalResource ) )
1246 GifLoading::~GifLoading()
1251 bool GifLoading::LoadNextNFrames( int frameStartIndex, int count, std::vector<Dali::PixelData> &pixelData )
1256 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t );
1258 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count );
1260 for( int i = 0; i < count; ++i )
1262 auto pixelBuffer = new unsigned char[ bufferSize ];
1264 mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount );
1266 if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) )
1270 pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize,
1271 mImpl->imageProperties.w, mImpl->imageProperties.h,
1272 Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) );
1281 bool GifLoading::LoadAllFrames( std::vector<Dali::PixelData> &pixelData, Dali::Vector<uint32_t> &frameDelays )
1283 if( LoadFrameDelays( frameDelays ) )
1285 return LoadNextNFrames( 0, mImpl->loaderInfo.animated.frameCount, pixelData );
1290 ImageDimensions GifLoading::GetImageSize()
1292 return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.h );
1295 int GifLoading::GetImageCount()
1297 return mImpl->loaderInfo.animated.frameCount;
1300 bool GifLoading::LoadFrameDelays( Dali::Vector<uint32_t> &frameDelays )
1302 frameDelays.Clear();
1304 for( auto &&elem : mImpl->loaderInfo.animated.frames )
1306 // Read frame delay time, multiply 10 to change time unit to milliseconds
1307 frameDelays.PushBack( elem.info.delay * 10 );