2 * Copyright (c) 2018 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>
31 #include <dali/integration-api/debug.h>
32 #include <dali/public-api/images/pixel-data.h>
33 #include <dali/internal/imaging/common/file-download.h>
34 #include <dali/internal/system/common/file-reader.h>
36 #define IMG_TOO_BIG( w, h ) \
37 ( ( static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h) ) >= \
38 ( (1ULL << (29 * (sizeof(void *) / 4))) - 2048) )
40 #define LOADERR( x ) \
42 DALI_LOG_ERROR( x ); \
51 #if defined(DEBUG_ENABLED)
52 Debug::Filter *gGifLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" );
55 const int IMG_MAX_SIZE = 65000;
56 constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024;
59 const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
60 const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
72 dispose( DISPOSE_BACKGROUND ),
78 unsigned short delay; // delay time in 1/100ths of a sec
79 short transparent : 10; // -1 == not, anything else == index
80 short dispose : 6; // 0, 1, 2, 3 (others invalid)
81 short interlace : 1; // interlaced or not
99 uint32_t *data; /* frame decoding data */
100 FrameInfo info; /* special image type info */
104 struct GifAnimationData
115 std::vector<ImageFrame> frames;
133 : fileName( nullptr ),
134 globalMap ( nullptr ),
136 fileDescriptor( -1 ),
137 isLocalResource( true )
141 const char *fileName; /**< The absolute path of the file. */
142 unsigned char *globalMap ; /**< A pointer to the entire contents of the file that have been mapped with mmap(2). */
143 long long length; /**< The length of the file in bytes. */
144 int fileDescriptor; /**< The file descriptor. */
145 bool isLocalResource; /**< The flag whether the file is a local resource */
158 int position, length; // yes - gif uses ints for file sizes.
162 GifAnimationData animated;
168 struct ImageProperties
183 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
185 * @param[in] animated A structure containing GIF animation data
186 * @param[in] index Frame index to be searched in GIF
187 * @return A pointer to the ImageFrame.
189 inline int CombinePixelABGR( int a, int r, int g, int b )
191 return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) );
194 inline int PixelLookup( ColorMapObject *colorMap, int index )
196 return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue );
200 * @brief Brute force find frame index - gifs are normally small so ok for now.
202 * @param[in] animated A structure containing GIF animation data
203 * @param[in] index Frame index to be searched in GIF
204 * @return A pointer to the ImageFrame.
206 ImageFrame *FindFrame( const GifAnimationData &animated, int index )
208 for( auto &&elem : animated.frames )
210 if( elem.index == index )
212 return const_cast<ImageFrame *>( &elem );
219 * @brief Fill in an image with a specific rgba color value.
221 * @param[in] data A pointer pointing to an image data
222 * @param[in] row A int containing the number of rows in an image
223 * @param[in] val A uint32_t containing rgba color value
224 * @param[in] x X-coordinate used an offset to calculate pixel position
225 * @param[in] y Y-coordinate used an offset to calculate pixel position
226 * @param[in] width Width of the image
227 * @param[in] height Height of the image
229 void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height )
232 uint32_t *pixelPosition;
234 for( yAxis = 0; yAxis < height; yAxis++ )
236 pixelPosition = data + ((y + yAxis) * row) + x;
237 for( xAxis = 0; xAxis < width; xAxis++ )
239 *pixelPosition = val;
246 * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
248 * @param[in] data A pointer pointing to an image data
249 * @param[in] row A int containing the number of rows in an image
250 * @param[in] gif A pointer pointing to GIF File Type
251 * @param[in] frameInfo A pointer pointing to Frame Information data
252 * @param[in] x X-coordinate used an offset to calculate pixel position
253 * @param[in] y Y-coordinate used an offset to calculate pixel position
254 * @param[in] width Width of the image
255 * @param[in] height Height of the image
257 void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h )
259 // solid color fill for pre frame region
260 if( frameInfo->transparent < 0 )
262 ColorMapObject *colorMap;
265 // work out color to use from colorMap
266 if( gif->Image.ColorMap )
268 colorMap = gif->Image.ColorMap;
272 colorMap = gif->SColorMap;
274 backGroundColor = gif->SBackGroundColor;
276 FillImage( data, row,
277 CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red,
278 colorMap->Colors[backGroundColor].Green,
279 colorMap->Colors[backGroundColor].Blue ),
282 // fill in region with 0 (transparent)
285 FillImage( data, row, 0, x, y, w, h );
290 * @brief Store common fields from gif file info into frame info
292 * @param[in] gif A pointer pointing to GIF File Type
293 * @param[in] frameInfo A pointer pointing to Frame Information data
295 void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo )
297 frameInfo->x = gif->Image.Left;
298 frameInfo->y = gif->Image.Top;
299 frameInfo->w = gif->Image.Width;
300 frameInfo->h = gif->Image.Height;
301 frameInfo->interlace = gif->Image.Interlace;
305 * @brief Check if image fills "screen space" and if so, if it is transparent
306 * at all then the image could be transparent - OR if image doesnt fill,
307 * then it could be trasnparent (full coverage of screen). Some gifs will
308 * be recognized as solid here for faster rendering, but not all.
310 * @param[out] full A boolean to show whether image is transparent or not
311 * @param[in] frameInfo A pointer pointing to Frame Information data
312 * @param[in] width Width of the image
313 * @param[in] height Height of the image
315 void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height )
317 if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) &&
318 ( frameInfo->w == width ) && ( frameInfo->h == height ) )
320 if( frameInfo->transparent >= 0 )
332 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
334 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 )
342 if( (x0 + w0) > imageWidth )
344 w0 = imageWidth - x0;
352 if( (y0 + h0) > imageHeight )
354 h0 = imageHeight - y0;
363 * @brief Flush out rgba frame images to save memory but skip current,
364 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
366 * @param[in] animated A structure containing GIF animation data
367 * @param[in] width Width of the image
368 * @param[in] height Height of the image
369 * @param[in] thisframe The current frame
370 * @param[in] prevframe The previous frame
371 * @param[in] lastPreservedFrame The last preserved frame
373 void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame )
375 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" );
377 // target is the amount of memory we want to be under for stored frames
378 int total = 0, target = 512 * 1024;
380 // total up the amount of memory used by stored frames for this image
381 for( auto &&frame : animated.frames )
388 total *= ( width * height * sizeof( uint32_t ) );
390 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total );
392 // If we use more than target (512k) for frames - flush
395 // Clean frames (except current and previous) until below target
396 for( auto &&frame : animated.frames )
398 if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
399 (!lastPreservedFrame || frame.index != lastPreservedFrame->index) )
401 if( frame.data != nullptr )
404 frame.data = nullptr;
406 // subtract memory used and if below target - stop flush
407 total -= ( width * height * sizeof( uint32_t ) );
417 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" );
421 * @brief allocate frame and frame info and append to list and store fields.
423 * @param[in] animated A structure containing GIF animation data
424 * @param[in] transparent Transparent index of the new frame
425 * @param[in] dispose Dispose mode of new frame
426 * @param[in] delay The frame delay of new frame
427 * @param[in] index The index of new frame
429 FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index )
433 // record transparent index to be used or -1 if none
434 // for this SPECIFIC frame
435 frame.info.transparent = transparent;
436 // record dispose mode (3 bits)
437 frame.info.dispose = dispose;
438 // record delay (2 bytes so max 65546 /100 sec)
439 frame.info.delay = delay;
440 // record the index number we are at
442 // that frame is stored AT image/screen size
444 animated.frames.push_back( frame );
446 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() );
448 return &( animated.frames.back().info );
452 * @brief Copy data from gif file into buffer.
454 * @param[in] gifFileType A pointer pointing to GIF File Type
455 * @param[out] buffer A pointer to buffer containing GIF raw data
456 * @param[in] len The length in bytes to be copied
457 * @return The data length of the image in bytes
459 int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length )
461 LoaderInfo::FileInfo *fi = reinterpret_cast<LoaderInfo::FileInfo *>( gifFileType->UserData );
463 if( fi->position >= fi->length )
465 return 0; // if at or past end - no
467 if( (fi->position + length) >= fi->length )
469 length = fi->length - fi->position;
471 memcpy( buffer, fi->map + fi->position, length );
472 fi->position += length;
477 * @brief Decode a gif image into rows then expand to 32bit into the destination
480 bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin,
481 int transparent, int x, int y, int w, int h, bool fill )
483 int intoffset[] = {0, 4, 2, 1};
484 int intjump[] = {8, 8, 4, 2};
486 GifRowType *rows = NULL;
488 ColorMapObject *colorMap;
491 // what we need is image size.
493 sp = &gif->SavedImages[ gif->ImageCount - 1 ];
498 w = sp->ImageDesc.Width;
499 h = sp->ImageDesc.Height;
501 // build a blob of memory to have pointers to rows of pixels
502 // AND store the decoded gif pixels (1 byte per pixel) as welll
503 rows = static_cast<GifRowType *>(malloc( (h * sizeof(GifRowType) ) + ( w * h * sizeof(GifPixelType) )));
509 // fill in the pointers at the start
510 for( yy = 0; yy < h; yy++ )
512 rows[yy] = reinterpret_cast<unsigned char *>(rows) + (h * sizeof(GifRowType)) + (yy * w * sizeof(GifPixelType));
515 // if gif is interlaced, walk interlace pattern and decode into rows
516 if( gif->Image.Interlace )
518 for( i = 0; i < 4; i++ )
520 for( yy = intoffset[i]; yy < h; yy += intjump[i] )
522 if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
529 // normal top to bottom - decode into rows
532 for( yy = 0; yy < h; yy++ )
534 if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
541 // work out what colormap to use
542 if( gif->Image.ColorMap )
544 colorMap = gif->Image.ColorMap;
548 colorMap = gif->SColorMap;
551 // if we need to deal with transparent pixels at all...
552 if( transparent >= 0 )
554 // if we are told to FILL (overwrite with transparency kept)
557 for( yy = 0; yy < h; yy++ )
559 p = data + ((y + yy) * rowpix) + x;
560 for( xx = 0; xx < w; xx++ )
562 pix = rows[yin + yy][xin + xx];
563 if( pix != transparent )
565 *p = PixelLookup( colorMap, pix );
575 // paste on top with transparent pixels untouched
578 for( yy = 0; yy < h; yy++ )
580 p = data + ((y + yy) * rowpix) + x;
581 for( xx = 0; xx < w; xx++ )
583 pix = rows[yin + yy][xin + xx];
584 if( pix != transparent )
586 *p = PixelLookup( colorMap, pix );
595 // walk pixels without worring about transparency at all
596 for( yy = 0; yy < h; yy++ )
598 p = data + ((y + yy) * rowpix) + x;
599 for( xx = 0; xx < w; xx++ )
601 pix = rows[yin + yy][xin + xx];
602 *p = PixelLookup( colorMap, pix );
618 * @brief Reader header from the gif file and populates structures accordingly.
620 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
621 * @param[out] prop A ImageProperties structure for storing information about GIF data.
622 * @param[out] error Error code
623 * @return The true or false whether reading was successful or not.
625 bool ReadHeader( LoaderInfo &loaderInfo,
626 ImageProperties &prop, //output struct
629 GifAnimationData &animated = loaderInfo.animated;
630 LoaderInfo::FileData &fileData = loaderInfo.fileData;
632 LoaderInfo::FileInfo fileInfo;
634 GifFileType *gif = NULL;
635 // it is possible which gif file have error midle of frames,
636 // in that case we should play gif file until meet error frame.
639 FrameInfo *frameInfo = NULL;
642 if( fileData.isLocalResource )
645 fileData.fileDescriptor = open( fileData.fileName, O_RDONLY );
647 if( fileData.fileDescriptor == -1 )
652 fileData.length = lseek( fileData.fileDescriptor, 0, SEEK_END );
653 if( fileData.length <= -1 )
655 close( fileData.fileDescriptor );
659 if( lseek( fileData.fileDescriptor, 0, SEEK_SET ) == -1 )
661 close( fileData.fileDescriptor );
665 // map the file and store/track info
666 fileData.globalMap = reinterpret_cast<unsigned char *>( mmap(NULL, fileData.length, PROT_READ, MAP_SHARED, fileData.fileDescriptor, 0 ));
667 fileInfo.map = fileData.globalMap ;
669 close(fileData.fileDescriptor);
670 fileData.fileDescriptor = -1;
676 Dali::Vector<uint8_t> dataBuffer;
679 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( fileData.fileName, dataBuffer, dataSize,
680 MAXIMUM_DOWNLOAD_IMAGE_SIZE );
683 size_t blobSize = dataBuffer.Size();
686 // Open a file handle on the memory buffer:
687 Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize );
688 FILE * const fp = fileReader.GetFile();
691 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
693 fileData.globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * blobSize ) );
694 fileData.length = fread( fileData.globalMap, sizeof( GifByteType ), blobSize, fp);
695 fileInfo.map = fileData.globalMap;
699 DALI_LOG_ERROR( "Error seeking within file\n" );
704 DALI_LOG_ERROR( "Error reading file\n" );
712 LOADERR("LOAD_ERROR_CORRUPT_FILE");
714 fileInfo.length = fileData.length;
715 fileInfo.position = 0;
717 // actually ask libgif to open the file
718 #if GIFLIB_MAJOR >= 5
719 gif = DGifOpen( &fileInfo, FileRead, NULL );
721 gif = DGifOpen( &fileInfo, FileRead );
726 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
729 // get the gif "screen size" (the actual image size)
730 prop.w = gif->SWidth;
731 prop.h = gif->SHeight;
733 // if size is invalid - abort here
734 if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
736 if( IMG_TOO_BIG(prop.w, prop.h) )
738 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
740 LOADERR("LOAD_ERROR_GENERIC");
742 // walk through gif records in file to figure out info
745 if( DGifGetRecordType(gif, &rec) == GIF_ERROR )
747 // if we have a gif that ends part way through a sequence
748 // (or animation) consider it valid and just break - no error
749 if( imageNumber > 1 )
753 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
756 // get image description section
757 if( rec == IMAGE_DESC_RECORD_TYPE )
763 if( DGifGetImageDesc(gif) == GIF_ERROR )
765 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
767 // skip decoding and just walk image to next
768 if( DGifGetCode(gif, &img_code, &img) == GIF_ERROR )
770 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
776 DGifGetCodeNext( gif, &img );
778 // store geometry in the last frame info data
781 StoreFrameInfo( gif, frameInfo );
782 CheckTransparency( full, frameInfo, prop.w, prop.h );
784 // or if we dont have a frameInfo entry - create one even for stills
787 // allocate and save frame with field data
788 frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
791 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
793 // store geometry info from gif image
794 StoreFrameInfo( gif, frameInfo );
795 // check for transparency/alpha
796 CheckTransparency( full, frameInfo, prop.w, prop.h );
800 // we have an extension code block - for animated gifs for sure
801 else if( rec == EXTENSION_RECORD_TYPE )
807 // get the first extension entry
808 DGifGetExtension( gif, &ext_code, &ext );
811 // graphic control extension - for animated gif data
812 // and transparent index + flag
813 if( ext_code == 0xf9 )
815 // create frame and store it in image
816 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
817 int disposeMode = (ext[1] >> 2) & 0x7;
818 int delay = (int(ext[3]) << 8) | int(ext[2]);
819 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
822 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
825 // netscape extension indicating loop count.
826 else if( ext_code == 0xff ) /* application extension */
828 if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
829 !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
832 DGifGetExtensionNext( gif, &ext );
835 loopCount = (int(ext[3]) << 8) | int(ext[2]);
843 // and continue onto the next extension entry
845 DGifGetExtensionNext( gif, &ext );
848 } while( rec != TERMINATE_RECORD_TYPE );
850 // if the gif main says we have more than one image or our image counting
851 // says so, then this image is animated - indicate this
852 if( (gif->ImageCount > 1) || (imageNumber > 1) )
854 animated.animated = 1;
855 animated.loopCount = loopCount;
857 animated.frameCount = std::min( gif->ImageCount, imageNumber );
864 animated.currentFrame = 1;
866 // no errors in header scan etc. so set err and return value
870 on_error: // jump here on any errors to clean up
871 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
874 DGifCloseFile( gif, NULL );
879 DGifCloseFile( gif );
887 * @brief Reader next frame of the gif file and populates structures accordingly.
889 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
890 * @param[in/out] prop A ImageProperties structure containing information about gif data.
891 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
892 * @param[out] error Error code
893 * @return The true or false whether reading was successful or not.
895 bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
896 unsigned char *pixels, int *error )
898 GifAnimationData &animated = loaderInfo.animated;
899 LoaderInfo::FileData &fileData = loaderInfo.fileData;
902 GifFileType *gif = NULL;
903 int index = 0, imageNumber = 0;
904 FrameInfo *frameInfo;
905 ImageFrame *frame = NULL;
906 ImageFrame *lastPreservedFrame = NULL;
908 index = animated.currentFrame;
910 // if index is invalid for animated image - error out
911 if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
913 LOADERR("LOAD_ERROR_GENERIC");
916 // find the given frame index
917 frame = FindFrame( animated, index );
920 if( (frame->loaded) && (frame->data) )
922 // frame is already there and decoded - jump to end
928 LOADERR("LOAD_ERROR_CORRUPT_FILE");
932 // actually ask libgif to open the file
933 gif = loaderInfo.gif;
936 loaderInfo.fileInfo.map = fileData.globalMap ;
937 if( !loaderInfo.fileInfo.map )
939 LOADERR("LOAD_ERROR_CORRUPT_FILE");
941 loaderInfo.fileInfo.length = fileData.length;
942 loaderInfo.fileInfo.position = 0;
944 #if GIFLIB_MAJOR >= 5
945 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead, NULL );
947 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead );
949 // if gif open failed... get out of here
952 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
954 loaderInfo.gif = gif;
955 loaderInfo.imageNumber = 1;
958 // if we want to go backwards, we likely need/want to re-decode from the
959 // start as we have nothing to build on
960 if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
962 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
964 DGifCloseFile( loaderInfo.gif, NULL );
967 DGifCloseFile( loaderInfo.gif );
969 loaderInfo.gif = NULL;
970 loaderInfo.imageNumber = 0;
974 // our current position is the previous frame we decoded from the file
975 imageNumber = loaderInfo.imageNumber;
977 // walk through gif records in file to figure out info
980 if( DGifGetRecordType( gif, &rec ) == GIF_ERROR )
982 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
985 if( rec == EXTENSION_RECORD_TYPE )
988 GifByteType *ext = NULL;
989 DGifGetExtension( gif, &ext_code, &ext );
994 DGifGetExtensionNext( gif, &ext );
997 // get image description section
998 else if( rec == IMAGE_DESC_RECORD_TYPE )
1000 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1003 ImageFrame *previousFrame = NULL;
1004 ImageFrame *thisFrame = NULL;
1007 if( DGifGetImageDesc(gif) == GIF_ERROR )
1009 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1012 // get the previous frame entry AND the current one to fill in
1013 previousFrame = FindFrame(animated, imageNumber - 1);
1014 thisFrame = FindFrame(animated, imageNumber);
1016 // if we have a frame AND we're animated AND we have no data...
1017 if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
1022 thisFrame->data = new uint32_t[prop.w * prop.h];
1024 if( !thisFrame->data )
1026 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1029 // if we have no prior frame OR prior frame data... empty
1030 if( (!previousFrame) || (!previousFrame->data) )
1033 frameInfo = &(thisFrame->info);
1034 memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
1036 // we have a prior frame to copy data from...
1039 frameInfo = &( previousFrame->info );
1041 // fix coords of sub image in case it goes out...
1042 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1043 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1046 // if dispose mode is not restore - then copy pre frame
1047 if( frameInfo->dispose != DISPOSE_PREVIOUS )
1049 memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1052 // if dispose mode is "background" then fill with bg
1053 if( frameInfo->dispose == DISPOSE_BACKGROUND )
1055 FillFrame( thisFrame->data, prop.w, gif, frameInfo, x, y, w, h );
1057 else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
1062 // Find last preserved frame.
1063 lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
1064 if( ! lastPreservedFrame )
1066 LOADERR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
1069 } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
1071 if ( lastPreservedFrame )
1073 memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1077 // now draw this frame on top
1078 frameInfo = &( thisFrame->info );
1079 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1080 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1082 if( !DecodeImage( gif, thisFrame->data, prop.w,
1083 xin, yin, frameInfo->transparent,
1084 x, y, w, h, first) )
1086 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1089 // mark as loaded and done
1090 thisFrame->loaded = true;
1092 FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
1094 // if we have a frame BUT the image is not animated. different
1096 else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
1098 // if we don't have the data decoded yet - decode it
1099 if( (!thisFrame->loaded) || (!thisFrame->data) )
1101 // use frame info but we WONT allocate frame pixels
1102 frameInfo = &( thisFrame->info );
1103 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1104 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1107 // clear out all pixels
1108 FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, gif, frameInfo, 0, 0, prop.w, prop.h );
1110 // and decode the gif with overwriting
1111 if( !DecodeImage( gif, reinterpret_cast<uint32_t *>(pixels), prop.w,
1112 xin, yin, frameInfo->transparent, x, y, w, h, true) )
1114 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1117 // mark as loaded and done
1118 thisFrame->loaded = true;
1120 // flush mem we don't need (at expense of decode cpu)
1124 // skip decoding and just walk image to next
1125 if( DGifGetCode( gif, &img_code, &img ) == GIF_ERROR )
1127 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1133 DGifGetCodeNext( gif, &img );
1138 // if we found the image we wanted - get out of here
1139 if( imageNumber > index )
1144 } while( rec != TERMINATE_RECORD_TYPE );
1146 // if we are at the end of the animation or not animated, close file
1147 loaderInfo.imageNumber = imageNumber;
1148 if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
1150 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
1151 if( loaderInfo.gif )
1153 DGifCloseFile( loaderInfo.gif, NULL );
1156 if( loaderInfo.gif )
1158 DGifCloseFile( loaderInfo.gif );
1162 loaderInfo.gif = NULL;
1163 loaderInfo.imageNumber = 0;
1167 // no errors in header scan etc. so set err and return value
1171 // if it was an animated image we need to copy the data to the
1172 // pixels for the image from the frame holding the data
1173 if( animated.animated && frame->data )
1175 memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
1178 on_error: // jump here on any errors to clean up
1182 } // unnamed namespace
1184 struct GifLoading::Impl
1187 Impl( const std::string& url, bool isLocalResource )
1190 loaderInfo.gif = nullptr;
1192 loaderInfo.fileData.fileName = mUrl.c_str();
1193 loaderInfo.fileData.isLocalResource = isLocalResource;
1195 ReadHeader( loaderInfo, imageProperties, &error );
1198 // Moveable but not copyable
1200 Impl( const Impl& ) = delete;
1201 Impl& operator=( const Impl& ) = delete;
1202 Impl( Impl&& ) = default;
1203 Impl& operator=( Impl&& ) = default;
1207 if( loaderInfo.fileData.globalMap )
1209 if( loaderInfo.fileData.isLocalResource )
1211 munmap( loaderInfo.fileData.globalMap , loaderInfo.fileData.length );
1215 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 std::unique_ptr<GifLoading> GifLoading::New( const std::string &url, bool isLocalResource )
1239 return std::unique_ptr<GifLoading>( 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( int 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 bool GifLoading::LoadAllFrames( std::vector<Dali::PixelData> &pixelData, Dali::Vector<uint32_t> &frameDelays )
1285 if( LoadFrameDelays( frameDelays ) )
1287 return LoadNextNFrames( 0, mImpl->loaderInfo.animated.frameCount, pixelData );
1292 ImageDimensions GifLoading::GetImageSize()
1294 return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.h );
1297 int GifLoading::GetImageCount()
1299 return mImpl->loaderInfo.animated.frameCount;
1302 bool GifLoading::LoadFrameDelays( Dali::Vector<uint32_t> &frameDelays )
1304 frameDelays.Clear();
1306 for( auto &&elem : mImpl->loaderInfo.animated.frames )
1308 // Read frame delay time, multiply 10 to change time unit to milliseconds
1309 frameDelays.PushBack( elem.info.delay * 10 );