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 "gif-loading.h"
24 #include <sys/types.h>
31 #include <dali/integration-api/debug.h>
32 #include <dali/public-api/images/pixel-data.h>
34 #define IMG_TOO_BIG( w, h ) \
35 ( ( static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h) ) >= \
36 ( (1ULL << (29 * (sizeof(void *) / 4))) - 2048) )
38 #define LOADERR( x ) \
40 DALI_LOG_ERROR( x ); \
49 #if defined(DEBUG_ENABLED)
50 Debug::Filter *gGifLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" );
53 const int IMG_MAX_SIZE = 65000;
56 const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
57 const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
69 dispose( DISPOSE_BACKGROUND ),
75 unsigned short delay; // delay time in 1/100ths of a sec
76 short transparent : 10; // -1 == not, anything else == index
77 short dispose : 6; // 0, 1, 2, 3 (others invalid)
78 short interlace : 1; // interlaced or not
96 uint32_t *data; /* frame decoding data */
97 FrameInfo info; /* special image type info */
101 struct GifAnimationData
112 std::vector<ImageFrame> frames;
130 : fileName( nullptr ),
131 globalMap ( nullptr ),
137 const char *fileName; /**< The absolute path of the file. */
138 unsigned char *globalMap ; /**< A pointer to the entire contents of the file that have been mapped with mmap(2). */
139 long long length; /**< The length of the file in bytes. */
140 int fileDescriptor; /**< The file descriptor. */
153 int position, length; // yes - gif uses ints for file sizes.
157 GifAnimationData animated;
163 struct ImageProperties
171 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
173 * @param[in] animated A structure containing GIF animation data
174 * @param[in] index Frame index to be searched in GIF
175 * @return A pointer to the ImageFrame.
177 inline int CombinePixelABGR( int a, int r, int g, int b )
179 return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) );
182 inline int PixelLookup( ColorMapObject *colorMap, int index )
184 return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue );
188 * @brief Brute force find frame index - gifs are normally small so ok for now.
190 * @param[in] animated A structure containing GIF animation data
191 * @param[in] index Frame index to be searched in GIF
192 * @return A pointer to the ImageFrame.
194 ImageFrame *FindFrame( const GifAnimationData &animated, int index )
196 for( auto &&elem : animated.frames )
198 if( elem.index == index )
200 return const_cast<ImageFrame *>( &elem );
207 * @brief Fill in an image with a specific rgba color value.
209 * @param[in] data A pointer pointing to an image data
210 * @param[in] row A int containing the number of rows in an image
211 * @param[in] val A uint32_t containing rgba color value
212 * @param[in] x X-coordinate used an offset to calculate pixel position
213 * @param[in] y Y-coordinate used an offset to calculate pixel position
214 * @param[in] width Width of the image
215 * @param[in] height Height of the image
217 void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height )
220 uint32_t *pixelPosition;
222 for( yAxis = 0; yAxis < height; yAxis++ )
224 pixelPosition = data + ((y + yAxis) * row) + x;
225 for( xAxis = 0; xAxis < width; xAxis++ )
227 *pixelPosition = val;
234 * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
236 * @param[in] data A pointer pointing to an image data
237 * @param[in] row A int containing the number of rows in an image
238 * @param[in] gif A pointer pointing to GIF File Type
239 * @param[in] frameInfo A pointer pointing to Frame Information data
240 * @param[in] x X-coordinate used an offset to calculate pixel position
241 * @param[in] y Y-coordinate used an offset to calculate pixel position
242 * @param[in] width Width of the image
243 * @param[in] height Height of the image
245 void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h )
247 // solid color fill for pre frame region
248 if( frameInfo->transparent < 0 )
250 ColorMapObject *colorMap;
253 // work out color to use from colorMap
254 if( gif->Image.ColorMap )
256 colorMap = gif->Image.ColorMap;
260 colorMap = gif->SColorMap;
262 backGroundColor = gif->SBackGroundColor;
264 FillImage( data, row,
265 CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red,
266 colorMap->Colors[backGroundColor].Green,
267 colorMap->Colors[backGroundColor].Blue ),
270 // fill in region with 0 (transparent)
273 FillImage( data, row, 0, x, y, w, h );
278 * @brief Store common fields from gif file info into frame info
280 * @param[in] gif A pointer pointing to GIF File Type
281 * @param[in] frameInfo A pointer pointing to Frame Information data
283 void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo )
285 frameInfo->x = gif->Image.Left;
286 frameInfo->y = gif->Image.Top;
287 frameInfo->w = gif->Image.Width;
288 frameInfo->h = gif->Image.Height;
289 frameInfo->interlace = gif->Image.Interlace;
293 * @brief Check if image fills "screen space" and if so, if it is transparent
294 * at all then the image could be transparent - OR if image doesnt fill,
295 * then it could be trasnparent (full coverage of screen). Some gifs will
296 * be recognized as solid here for faster rendering, but not all.
298 * @param[out] full A boolean to show whether image is transparent or not
299 * @param[in] frameInfo A pointer pointing to Frame Information data
300 * @param[in] width Width of the image
301 * @param[in] height Height of the image
303 void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height )
305 if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) &&
306 ( frameInfo->w == width ) && ( frameInfo->h == height ) )
308 if( frameInfo->transparent >= 0 )
320 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
322 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 )
330 if( (x0 + w0) > imageWidth )
332 w0 = imageWidth - x0;
340 if( (y0 + h0) > imageHeight )
342 h0 = imageHeight - y0;
351 * @brief Flush out rgba frame images to save memory but skip current,
352 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
354 * @param[in] animated A structure containing GIF animation data
355 * @param[in] width Width of the image
356 * @param[in] height Height of the image
357 * @param[in] thisframe The current frame
358 * @param[in] prevframe The previous frame
359 * @param[in] lastPreservedFrame The last preserved frame
361 void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame )
363 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" );
365 // target is the amount of memory we want to be under for stored frames
366 int total = 0, target = 512 * 1024;
368 // total up the amount of memory used by stored frames for this image
369 for( auto &&frame : animated.frames )
376 total *= ( width * height * sizeof( uint32_t ) );
378 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total );
380 // If we use more than target (512k) for frames - flush
383 // Clean frames (except current and previous) until below target
384 for( auto &&frame : animated.frames )
386 if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
387 (!lastPreservedFrame || frame.index != lastPreservedFrame->index) )
389 if( frame.data != nullptr )
392 frame.data = nullptr;
394 // subtract memory used and if below target - stop flush
395 total -= ( width * height * sizeof( uint32_t ) );
405 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" );
409 * @brief allocate frame and frame info and append to list and store fields.
411 * @param[in] animated A structure containing GIF animation data
412 * @param[in] transparent Transparent index of the new frame
413 * @param[in] dispose Dispose mode of new frame
414 * @param[in] delay The frame delay of new frame
415 * @param[in] index The index of new frame
417 FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index )
421 // record transparent index to be used or -1 if none
422 // for this SPECIFIC frame
423 frame.info.transparent = transparent;
424 // record dispose mode (3 bits)
425 frame.info.dispose = dispose;
426 // record delay (2 bytes so max 65546 /100 sec)
427 frame.info.delay = delay;
428 // record the index number we are at
430 // that frame is stored AT image/screen size
432 animated.frames.push_back( frame );
434 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() );
436 return &( animated.frames.back().info );
440 * @brief Copy data from gif file into buffer.
442 * @param[in] gifFileType A pointer pointing to GIF File Type
443 * @param[out] buffer A pointer to buffer containing GIF raw data
444 * @param[in] len The length in bytes to be copied
445 * @return The data length of the image in bytes
447 int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length )
449 LoaderInfo::FileInfo *fi = reinterpret_cast<LoaderInfo::FileInfo *>( gifFileType->UserData );
451 if( fi->position >= fi->length )
453 return 0; // if at or past end - no
455 if( (fi->position + length) >= fi->length )
457 length = fi->length - fi->position;
459 memcpy( buffer, fi->map + fi->position, length );
460 fi->position += length;
465 * @brief Decode a gif image into rows then expand to 32bit into the destination
468 bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin,
469 int transparent, int x, int y, int w, int h, bool fill )
471 int intoffset[] = {0, 4, 2, 1};
472 int intjump[] = {8, 8, 4, 2};
474 GifRowType *rows = NULL;
476 ColorMapObject *colorMap;
479 // what we need is image size.
481 sp = &gif->SavedImages[ gif->ImageCount - 1 ];
486 w = sp->ImageDesc.Width;
487 h = sp->ImageDesc.Height;
489 // build a blob of memory to have pointers to rows of pixels
490 // AND store the decoded gif pixels (1 byte per pixel) as welll
491 rows = static_cast<GifRowType *>(malloc( (h * sizeof(GifRowType) ) + ( w * h * sizeof(GifPixelType) )));
497 // fill in the pointers at the start
498 for( yy = 0; yy < h; yy++ )
500 rows[yy] = reinterpret_cast<unsigned char *>(rows) + (h * sizeof(GifRowType)) + (yy * w * sizeof(GifPixelType));
503 // if gif is interlaced, walk interlace pattern and decode into rows
504 if( gif->Image.Interlace )
506 for( i = 0; i < 4; i++ )
508 for( yy = intoffset[i]; yy < h; yy += intjump[i] )
510 if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
517 // normal top to bottom - decode into rows
520 for( yy = 0; yy < h; yy++ )
522 if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
529 // work out what colormap to use
530 if( gif->Image.ColorMap )
532 colorMap = gif->Image.ColorMap;
536 colorMap = gif->SColorMap;
539 // if we need to deal with transparent pixels at all...
540 if( transparent >= 0 )
542 // if we are told to FILL (overwrite with transparency kept)
545 for( yy = 0; yy < h; yy++ )
547 p = data + ((y + yy) * rowpix) + x;
548 for( xx = 0; xx < w; xx++ )
550 pix = rows[yin + yy][xin + xx];
551 if( pix != transparent )
553 *p = PixelLookup( colorMap, pix );
563 // paste on top with transparent pixels untouched
566 for( yy = 0; yy < h; yy++ )
568 p = data + ((y + yy) * rowpix) + x;
569 for( xx = 0; xx < w; xx++ )
571 pix = rows[yin + yy][xin + xx];
572 if( pix != transparent )
574 *p = PixelLookup( colorMap, pix );
583 // walk pixels without worring about transparency at all
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 *p = PixelLookup( colorMap, pix );
606 * @brief Reader header from the gif file and populates structures accordingly.
608 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
609 * @param[out] prop A ImageProperties structure for storing information about GIF data.
610 * @param[out] error Error code
611 * @return The true or false whether reading was successful or not.
613 bool ReadHeader( LoaderInfo &loaderInfo,
614 ImageProperties &prop, //output struct
617 GifAnimationData &animated = loaderInfo.animated;
618 LoaderInfo::FileData &fileData = loaderInfo.fileData;
620 LoaderInfo::FileInfo fileInfo;
622 GifFileType *gif = NULL;
623 // it is possible which gif file have error midle of frames,
624 // in that case we should play gif file until meet error frame.
627 FrameInfo *frameInfo = NULL;
630 // init prop struct with some default null values
634 fileData.fileDescriptor = open( fileData.fileName, O_RDONLY );
636 if( fileData.fileDescriptor == -1 )
641 fileData.length = lseek( fileData.fileDescriptor, 0, SEEK_END );
642 if( fileData.length <= -1 )
644 close( fileData.fileDescriptor );
648 if( lseek( fileData.fileDescriptor, 0, SEEK_SET ) == -1 )
650 close( fileData.fileDescriptor );
654 // map the file and store/track info
655 fileData.globalMap = reinterpret_cast<unsigned char *>( mmap(NULL, fileData.length, PROT_READ, MAP_SHARED, fileData.fileDescriptor, 0 ));
656 fileInfo.map = fileData.globalMap ;
658 close(fileData.fileDescriptor);
659 fileData.fileDescriptor = -1;
663 LOADERR("LOAD_ERROR_CORRUPT_FILE");
665 fileInfo.length = fileData.length;
666 fileInfo.position = 0;
668 // actually ask libgif to open the file
669 #if GIFLIB_MAJOR >= 5
670 gif = DGifOpen( &fileInfo, FileRead, NULL );
672 gif = DGifOpen( &fileInfo, FileRead );
677 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
680 // get the gif "screen size" (the actual image size)
681 prop.w = gif->SWidth;
682 prop.h = gif->SHeight;
684 // if size is invalid - abort here
685 if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
687 if( IMG_TOO_BIG(prop.w, prop.h) )
689 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
691 LOADERR("LOAD_ERROR_GENERIC");
693 // walk through gif records in file to figure out info
696 if( DGifGetRecordType(gif, &rec) == GIF_ERROR )
698 // if we have a gif that ends part way through a sequence
699 // (or animation) consider it valid and just break - no error
700 if( imageNumber > 1 )
704 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
707 // get image description section
708 if( rec == IMAGE_DESC_RECORD_TYPE )
714 if( DGifGetImageDesc(gif) == GIF_ERROR )
716 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
718 // skip decoding and just walk image to next
719 if( DGifGetCode(gif, &img_code, &img) == GIF_ERROR )
721 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
727 DGifGetCodeNext( gif, &img );
729 // store geometry in the last frame info data
732 StoreFrameInfo( gif, frameInfo );
733 CheckTransparency( full, frameInfo, prop.w, prop.h );
735 // or if we dont have a frameInfo entry - create one even for stills
738 // allocate and save frame with field data
739 frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
742 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
744 // store geometry info from gif image
745 StoreFrameInfo( gif, frameInfo );
746 // check for transparency/alpha
747 CheckTransparency( full, frameInfo, prop.w, prop.h );
751 // we have an extension code block - for animated gifs for sure
752 else if( rec == EXTENSION_RECORD_TYPE )
758 // get the first extension entry
759 DGifGetExtension( gif, &ext_code, &ext );
762 // graphic control extension - for animated gif data
763 // and transparent index + flag
764 if( ext_code == 0xf9 )
766 // create frame and store it in image
767 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
768 int disposeMode = (ext[1] >> 2) & 0x7;
769 int delay = (int(ext[3]) << 8) | int(ext[2]);
770 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
773 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
776 // netscape extension indicating loop count.
777 else if( ext_code == 0xff ) /* application extension */
779 if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
780 !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
783 DGifGetExtensionNext( gif, &ext );
786 loopCount = (int(ext[3]) << 8) | int(ext[2]);
794 // and continue onto the next extension entry
796 DGifGetExtensionNext( gif, &ext );
799 } while( rec != TERMINATE_RECORD_TYPE );
801 // if the gif main says we have more than one image or our image counting
802 // says so, then this image is animated - indicate this
803 if( (gif->ImageCount > 1) || (imageNumber > 1) )
805 animated.animated = 1;
806 animated.loopCount = loopCount;
808 animated.frameCount = std::min( gif->ImageCount, imageNumber );
815 animated.currentFrame = 1;
817 // no errors in header scan etc. so set err and return value
821 on_error: // jump here on any errors to clean up
822 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
825 DGifCloseFile( gif, NULL );
830 DGifCloseFile( gif );
838 * @brief Reader next frame of the gif file and populates structures accordingly.
840 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
841 * @param[in/out] prop A ImageProperties structure containing information about gif data.
842 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
843 * @param[out] error Error code
844 * @return The true or false whether reading was successful or not.
846 bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
847 unsigned char *pixels, int *error )
849 GifAnimationData &animated = loaderInfo.animated;
850 LoaderInfo::FileData &fileData = loaderInfo.fileData;
853 GifFileType *gif = NULL;
854 int index = 0, imageNumber = 0;
855 FrameInfo *frameInfo;
856 ImageFrame *frame = NULL;
857 ImageFrame *lastPreservedFrame = NULL;
859 index = animated.currentFrame;
861 // if index is invalid for animated image - error out
862 if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
864 LOADERR("LOAD_ERROR_GENERIC");
867 // find the given frame index
868 frame = FindFrame( animated, index );
871 if( (frame->loaded) && (frame->data) )
873 // frame is already there and decoded - jump to end
879 LOADERR("LOAD_ERROR_CORRUPT_FILE");
883 // actually ask libgif to open the file
884 gif = loaderInfo.gif;
887 loaderInfo.fileInfo.map = fileData.globalMap ;
888 if( !loaderInfo.fileInfo.map )
890 LOADERR("LOAD_ERROR_CORRUPT_FILE");
892 loaderInfo.fileInfo.length = fileData.length;
893 loaderInfo.fileInfo.position = 0;
895 #if GIFLIB_MAJOR >= 5
896 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead, NULL );
898 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead );
900 // if gif open failed... get out of here
903 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
905 loaderInfo.gif = gif;
906 loaderInfo.imageNumber = 1;
909 // if we want to go backwards, we likely need/want to re-decode from the
910 // start as we have nothing to build on
911 if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
913 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
915 DGifCloseFile( loaderInfo.gif, NULL );
918 DGifCloseFile( loaderInfo.gif );
920 loaderInfo.gif = NULL;
921 loaderInfo.imageNumber = 0;
925 // our current position is the previous frame we decoded from the file
926 imageNumber = loaderInfo.imageNumber;
928 // walk through gif records in file to figure out info
931 if( DGifGetRecordType( gif, &rec ) == GIF_ERROR )
933 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
936 if( rec == EXTENSION_RECORD_TYPE )
939 GifByteType *ext = NULL;
940 DGifGetExtension( gif, &ext_code, &ext );
945 DGifGetExtensionNext( gif, &ext );
948 // get image description section
949 else if( rec == IMAGE_DESC_RECORD_TYPE )
951 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
954 ImageFrame *previousFrame = NULL;
955 ImageFrame *thisFrame = NULL;
958 if( DGifGetImageDesc(gif) == GIF_ERROR )
960 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
963 // get the previous frame entry AND the current one to fill in
964 previousFrame = FindFrame(animated, imageNumber - 1);
965 thisFrame = FindFrame(animated, imageNumber);
967 // if we have a frame AND we're animated AND we have no data...
968 if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
973 thisFrame->data = new uint32_t[prop.w * prop.h];
975 if( !thisFrame->data )
977 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
980 // if we have no prior frame OR prior frame data... empty
981 if( (!previousFrame) || (!previousFrame->data) )
984 frameInfo = &(thisFrame->info);
985 memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
987 // we have a prior frame to copy data from...
990 frameInfo = &( previousFrame->info );
992 // fix coords of sub image in case it goes out...
993 ClipCoordinates( prop.w, prop.h, &xin, &yin,
994 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
997 // if dispose mode is not restore - then copy pre frame
998 if( frameInfo->dispose != DISPOSE_PREVIOUS )
1000 memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1003 // if dispose mode is "background" then fill with bg
1004 if( frameInfo->dispose == DISPOSE_BACKGROUND )
1006 FillFrame( thisFrame->data, prop.w, gif, frameInfo, x, y, w, h );
1008 else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
1013 // Find last preserved frame.
1014 lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
1015 if( ! lastPreservedFrame )
1017 LOADERR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
1020 } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
1022 if ( lastPreservedFrame )
1024 memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1028 // now draw this frame on top
1029 frameInfo = &( thisFrame->info );
1030 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1031 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1033 if( !DecodeImage( gif, thisFrame->data, prop.w,
1034 xin, yin, frameInfo->transparent,
1035 x, y, w, h, first) )
1037 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1040 // mark as loaded and done
1041 thisFrame->loaded = true;
1043 FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
1045 // if we hve a frame BUT the image is not animated... different
1047 else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
1049 // if we don't have the data decoded yet - decode it
1050 if( (!thisFrame->loaded) || (!thisFrame->data) )
1052 // use frame info but we WONT allocate frame pixels
1053 frameInfo = &( thisFrame->info );
1054 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1055 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1058 // clear out all pixels
1059 FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, gif, frameInfo, 0, 0, prop.w, prop.h );
1061 // and decode the gif with overwriting
1062 if( !DecodeImage( gif, reinterpret_cast<uint32_t *>(pixels), prop.w,
1063 xin, yin, frameInfo->transparent, x, y, w, h, true) )
1065 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1068 // mark as loaded and done
1069 thisFrame->loaded = true;
1071 // flush mem we don't need (at expense of decode cpu)
1075 // skip decoding and just walk image to next
1076 if( DGifGetCode( gif, &img_code, &img ) == GIF_ERROR )
1078 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1084 DGifGetCodeNext( gif, &img );
1089 // if we found the image we wanted - get out of here
1090 if( imageNumber > index )
1095 } while( rec != TERMINATE_RECORD_TYPE );
1097 // if we are at the end of the animation or not animated, close file
1098 loaderInfo.imageNumber = imageNumber;
1099 if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
1101 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
1102 if( loaderInfo.gif )
1104 DGifCloseFile( loaderInfo.gif, NULL );
1107 if( loaderInfo.gif )
1109 DGifCloseFile( loaderInfo.gif );
1113 loaderInfo.gif = NULL;
1114 loaderInfo.imageNumber = 0;
1118 // no errors in header scan etc. so set err and return value
1122 // if it was an animated image we need to copy the data to the
1123 // pixels for the image from the frame holding the data
1124 if( animated.animated && frame->data )
1126 memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
1129 on_error: // jump here on any errors to clean up
1133 } // unnamed namespace
1135 struct GifLoading::Impl
1138 Impl( const std::string& url)
1141 loaderInfo.gif = nullptr;
1143 loaderInfo.fileData.fileName = mUrl.c_str();
1145 ReadHeader( loaderInfo, imageProperties, &error );
1150 if( loaderInfo.fileData.globalMap )
1152 munmap( loaderInfo.fileData.globalMap , loaderInfo.fileData.length );
1153 loaderInfo.fileData.globalMap = nullptr;
1158 LoaderInfo loaderInfo;
1159 ImageProperties imageProperties;
1162 std::unique_ptr<GifLoading> GifLoading::New( const std::string &url )
1164 return std::unique_ptr<GifLoading>( new GifLoading( url ) );
1167 GifLoading::GifLoading( const std::string &url )
1168 : mImpl( new GifLoading::Impl( url ) )
1172 GifLoading::~GifLoading()
1177 bool GifLoading::LoadNextNFrames( int frameStartIndex, int count, std::vector<Dali::PixelData> &pixelData )
1182 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t );
1184 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count );
1186 for( int i = 0; i < count; ++i )
1188 auto pixelBuffer = new unsigned char[ bufferSize ];
1190 mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount );
1192 if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) )
1196 pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize,
1197 mImpl->imageProperties.w, mImpl->imageProperties.h,
1198 Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) );
1207 bool GifLoading::LoadAllFrames( std::vector<Dali::PixelData> &pixelData, Dali::Vector<uint32_t> &frameDelays )
1209 if( LoadFrameDelays( frameDelays ) )
1211 return LoadNextNFrames( 0, mImpl->loaderInfo.animated.frameCount, pixelData );
1216 ImageDimensions GifLoading::GetImageSize()
1218 return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.w );
1221 int GifLoading::GetImageCount()
1223 return mImpl->loaderInfo.animated.frameCount;
1226 bool GifLoading::LoadFrameDelays( Dali::Vector<uint32_t> &frameDelays )
1228 frameDelays.Clear();
1230 for( auto &&elem : mImpl->loaderInfo.animated.frames )
1232 // Read frame delay time, multiply 10 to change time unit to milliseconds
1233 frameDelays.PushBack( elem.info.delay * 10 );