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>
33 #include <resource-loader/network/file-download.h>
34 #include <platform-abstractions/portable/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
176 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
178 * @param[in] animated A structure containing GIF animation data
179 * @param[in] index Frame index to be searched in GIF
180 * @return A pointer to the ImageFrame.
182 inline int CombinePixelABGR( int a, int r, int g, int b )
184 return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) );
187 inline int PixelLookup( ColorMapObject *colorMap, int index )
189 return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue );
193 * @brief Brute force find frame index - gifs are normally small so ok for now.
195 * @param[in] animated A structure containing GIF animation data
196 * @param[in] index Frame index to be searched in GIF
197 * @return A pointer to the ImageFrame.
199 ImageFrame *FindFrame( const GifAnimationData &animated, int index )
201 for( auto &&elem : animated.frames )
203 if( elem.index == index )
205 return const_cast<ImageFrame *>( &elem );
212 * @brief Fill in an image with a specific rgba color value.
214 * @param[in] data A pointer pointing to an image data
215 * @param[in] row A int containing the number of rows in an image
216 * @param[in] val A uint32_t containing rgba color value
217 * @param[in] x X-coordinate used an offset to calculate pixel position
218 * @param[in] y Y-coordinate used an offset to calculate pixel position
219 * @param[in] width Width of the image
220 * @param[in] height Height of the image
222 void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height )
225 uint32_t *pixelPosition;
227 for( yAxis = 0; yAxis < height; yAxis++ )
229 pixelPosition = data + ((y + yAxis) * row) + x;
230 for( xAxis = 0; xAxis < width; xAxis++ )
232 *pixelPosition = val;
239 * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
241 * @param[in] data A pointer pointing to an image data
242 * @param[in] row A int containing the number of rows in an image
243 * @param[in] gif A pointer pointing to GIF File Type
244 * @param[in] frameInfo A pointer pointing to Frame Information data
245 * @param[in] x X-coordinate used an offset to calculate pixel position
246 * @param[in] y Y-coordinate used an offset to calculate pixel position
247 * @param[in] width Width of the image
248 * @param[in] height Height of the image
250 void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h )
252 // solid color fill for pre frame region
253 if( frameInfo->transparent < 0 )
255 ColorMapObject *colorMap;
258 // work out color to use from colorMap
259 if( gif->Image.ColorMap )
261 colorMap = gif->Image.ColorMap;
265 colorMap = gif->SColorMap;
267 backGroundColor = gif->SBackGroundColor;
269 FillImage( data, row,
270 CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red,
271 colorMap->Colors[backGroundColor].Green,
272 colorMap->Colors[backGroundColor].Blue ),
275 // fill in region with 0 (transparent)
278 FillImage( data, row, 0, x, y, w, h );
283 * @brief Store common fields from gif file info into frame info
285 * @param[in] gif A pointer pointing to GIF File Type
286 * @param[in] frameInfo A pointer pointing to Frame Information data
288 void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo )
290 frameInfo->x = gif->Image.Left;
291 frameInfo->y = gif->Image.Top;
292 frameInfo->w = gif->Image.Width;
293 frameInfo->h = gif->Image.Height;
294 frameInfo->interlace = gif->Image.Interlace;
298 * @brief Check if image fills "screen space" and if so, if it is transparent
299 * at all then the image could be transparent - OR if image doesnt fill,
300 * then it could be trasnparent (full coverage of screen). Some gifs will
301 * be recognized as solid here for faster rendering, but not all.
303 * @param[out] full A boolean to show whether image is transparent or not
304 * @param[in] frameInfo A pointer pointing to Frame Information data
305 * @param[in] width Width of the image
306 * @param[in] height Height of the image
308 void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height )
310 if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) &&
311 ( frameInfo->w == width ) && ( frameInfo->h == height ) )
313 if( frameInfo->transparent >= 0 )
325 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
327 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 )
335 if( (x0 + w0) > imageWidth )
337 w0 = imageWidth - x0;
345 if( (y0 + h0) > imageHeight )
347 h0 = imageHeight - y0;
356 * @brief Flush out rgba frame images to save memory but skip current,
357 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
359 * @param[in] animated A structure containing GIF animation data
360 * @param[in] width Width of the image
361 * @param[in] height Height of the image
362 * @param[in] thisframe The current frame
363 * @param[in] prevframe The previous frame
364 * @param[in] lastPreservedFrame The last preserved frame
366 void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame )
368 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" );
370 // target is the amount of memory we want to be under for stored frames
371 int total = 0, target = 512 * 1024;
373 // total up the amount of memory used by stored frames for this image
374 for( auto &&frame : animated.frames )
381 total *= ( width * height * sizeof( uint32_t ) );
383 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total );
385 // If we use more than target (512k) for frames - flush
388 // Clean frames (except current and previous) until below target
389 for( auto &&frame : animated.frames )
391 if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
392 (!lastPreservedFrame || frame.index != lastPreservedFrame->index) )
394 if( frame.data != nullptr )
397 frame.data = nullptr;
399 // subtract memory used and if below target - stop flush
400 total -= ( width * height * sizeof( uint32_t ) );
410 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" );
414 * @brief allocate frame and frame info and append to list and store fields.
416 * @param[in] animated A structure containing GIF animation data
417 * @param[in] transparent Transparent index of the new frame
418 * @param[in] dispose Dispose mode of new frame
419 * @param[in] delay The frame delay of new frame
420 * @param[in] index The index of new frame
422 FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index )
426 // record transparent index to be used or -1 if none
427 // for this SPECIFIC frame
428 frame.info.transparent = transparent;
429 // record dispose mode (3 bits)
430 frame.info.dispose = dispose;
431 // record delay (2 bytes so max 65546 /100 sec)
432 frame.info.delay = delay;
433 // record the index number we are at
435 // that frame is stored AT image/screen size
437 animated.frames.push_back( frame );
439 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() );
441 return &( animated.frames.back().info );
445 * @brief Copy data from gif file into buffer.
447 * @param[in] gifFileType A pointer pointing to GIF File Type
448 * @param[out] buffer A pointer to buffer containing GIF raw data
449 * @param[in] len The length in bytes to be copied
450 * @return The data length of the image in bytes
452 int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length )
454 LoaderInfo::FileInfo *fi = reinterpret_cast<LoaderInfo::FileInfo *>( gifFileType->UserData );
456 if( fi->position >= fi->length )
458 return 0; // if at or past end - no
460 if( (fi->position + length) >= fi->length )
462 length = fi->length - fi->position;
464 memcpy( buffer, fi->map + fi->position, length );
465 fi->position += length;
470 * @brief Decode a gif image into rows then expand to 32bit into the destination
473 bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin,
474 int transparent, int x, int y, int w, int h, bool fill )
476 int intoffset[] = {0, 4, 2, 1};
477 int intjump[] = {8, 8, 4, 2};
479 GifRowType *rows = NULL;
481 ColorMapObject *colorMap;
484 // what we need is image size.
486 sp = &gif->SavedImages[ gif->ImageCount - 1 ];
491 w = sp->ImageDesc.Width;
492 h = sp->ImageDesc.Height;
494 // build a blob of memory to have pointers to rows of pixels
495 // AND store the decoded gif pixels (1 byte per pixel) as welll
496 rows = static_cast<GifRowType *>(malloc( (h * sizeof(GifRowType) ) + ( w * h * sizeof(GifPixelType) )));
502 // fill in the pointers at the start
503 for( yy = 0; yy < h; yy++ )
505 rows[yy] = reinterpret_cast<unsigned char *>(rows) + (h * sizeof(GifRowType)) + (yy * w * sizeof(GifPixelType));
508 // if gif is interlaced, walk interlace pattern and decode into rows
509 if( gif->Image.Interlace )
511 for( i = 0; i < 4; i++ )
513 for( yy = intoffset[i]; yy < h; yy += intjump[i] )
515 if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
522 // normal top to bottom - decode into rows
525 for( yy = 0; yy < h; yy++ )
527 if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
534 // work out what colormap to use
535 if( gif->Image.ColorMap )
537 colorMap = gif->Image.ColorMap;
541 colorMap = gif->SColorMap;
544 // if we need to deal with transparent pixels at all...
545 if( transparent >= 0 )
547 // if we are told to FILL (overwrite with transparency kept)
550 for( yy = 0; yy < h; yy++ )
552 p = data + ((y + yy) * rowpix) + x;
553 for( xx = 0; xx < w; xx++ )
555 pix = rows[yin + yy][xin + xx];
556 if( pix != transparent )
558 *p = PixelLookup( colorMap, pix );
568 // paste on top with transparent pixels untouched
571 for( yy = 0; yy < h; yy++ )
573 p = data + ((y + yy) * rowpix) + x;
574 for( xx = 0; xx < w; xx++ )
576 pix = rows[yin + yy][xin + xx];
577 if( pix != transparent )
579 *p = PixelLookup( colorMap, pix );
588 // walk pixels without worring about transparency at all
589 for( yy = 0; yy < h; yy++ )
591 p = data + ((y + yy) * rowpix) + x;
592 for( xx = 0; xx < w; xx++ )
594 pix = rows[yin + yy][xin + xx];
595 *p = PixelLookup( colorMap, pix );
611 * @brief Reader header from the gif file and populates structures accordingly.
613 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
614 * @param[out] prop A ImageProperties structure for storing information about GIF data.
615 * @param[out] error Error code
616 * @return The true or false whether reading was successful or not.
618 bool ReadHeader( LoaderInfo &loaderInfo,
619 ImageProperties &prop, //output struct
622 GifAnimationData &animated = loaderInfo.animated;
623 LoaderInfo::FileData &fileData = loaderInfo.fileData;
625 LoaderInfo::FileInfo fileInfo;
627 GifFileType *gif = NULL;
628 // it is possible which gif file have error midle of frames,
629 // in that case we should play gif file until meet error frame.
632 FrameInfo *frameInfo = NULL;
635 // init prop struct with some default null values
639 if( fileData.isLocalResource )
642 fileData.fileDescriptor = open( fileData.fileName, O_RDONLY );
644 if( fileData.fileDescriptor == -1 )
649 fileData.length = lseek( fileData.fileDescriptor, 0, SEEK_END );
650 if( fileData.length <= -1 )
652 close( fileData.fileDescriptor );
656 if( lseek( fileData.fileDescriptor, 0, SEEK_SET ) == -1 )
658 close( fileData.fileDescriptor );
662 // map the file and store/track info
663 fileData.globalMap = reinterpret_cast<unsigned char *>( mmap(NULL, fileData.length, PROT_READ, MAP_SHARED, fileData.fileDescriptor, 0 ));
664 fileInfo.map = fileData.globalMap ;
666 close(fileData.fileDescriptor);
667 fileData.fileDescriptor = -1;
673 Dali::Vector<uint8_t> dataBuffer;
676 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( fileData.fileName, dataBuffer, dataSize,
677 MAXIMUM_DOWNLOAD_IMAGE_SIZE );
680 size_t blobSize = dataBuffer.Size();
683 // Open a file handle on the memory buffer:
684 Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize );
685 FILE * const fp = fileReader.GetFile();
688 fseek( fp, 0, SEEK_SET );
689 fileData.globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * blobSize ) );
690 fileData.length = fread( fileData.globalMap, sizeof( GifByteType ), blobSize, fp);
691 fileInfo.map = fileData.globalMap;
699 LOADERR("LOAD_ERROR_CORRUPT_FILE");
701 fileInfo.length = fileData.length;
702 fileInfo.position = 0;
704 // actually ask libgif to open the file
705 #if GIFLIB_MAJOR >= 5
706 gif = DGifOpen( &fileInfo, FileRead, NULL );
708 gif = DGifOpen( &fileInfo, FileRead );
713 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
716 // get the gif "screen size" (the actual image size)
717 prop.w = gif->SWidth;
718 prop.h = gif->SHeight;
720 // if size is invalid - abort here
721 if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
723 if( IMG_TOO_BIG(prop.w, prop.h) )
725 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
727 LOADERR("LOAD_ERROR_GENERIC");
729 // walk through gif records in file to figure out info
732 if( DGifGetRecordType(gif, &rec) == GIF_ERROR )
734 // if we have a gif that ends part way through a sequence
735 // (or animation) consider it valid and just break - no error
736 if( imageNumber > 1 )
740 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
743 // get image description section
744 if( rec == IMAGE_DESC_RECORD_TYPE )
750 if( DGifGetImageDesc(gif) == GIF_ERROR )
752 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
754 // skip decoding and just walk image to next
755 if( DGifGetCode(gif, &img_code, &img) == GIF_ERROR )
757 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
763 DGifGetCodeNext( gif, &img );
765 // store geometry in the last frame info data
768 StoreFrameInfo( gif, frameInfo );
769 CheckTransparency( full, frameInfo, prop.w, prop.h );
771 // or if we dont have a frameInfo entry - create one even for stills
774 // allocate and save frame with field data
775 frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
778 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
780 // store geometry info from gif image
781 StoreFrameInfo( gif, frameInfo );
782 // check for transparency/alpha
783 CheckTransparency( full, frameInfo, prop.w, prop.h );
787 // we have an extension code block - for animated gifs for sure
788 else if( rec == EXTENSION_RECORD_TYPE )
794 // get the first extension entry
795 DGifGetExtension( gif, &ext_code, &ext );
798 // graphic control extension - for animated gif data
799 // and transparent index + flag
800 if( ext_code == 0xf9 )
802 // create frame and store it in image
803 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
804 int disposeMode = (ext[1] >> 2) & 0x7;
805 int delay = (int(ext[3]) << 8) | int(ext[2]);
806 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
809 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
812 // netscape extension indicating loop count.
813 else if( ext_code == 0xff ) /* application extension */
815 if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
816 !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
819 DGifGetExtensionNext( gif, &ext );
822 loopCount = (int(ext[3]) << 8) | int(ext[2]);
830 // and continue onto the next extension entry
832 DGifGetExtensionNext( gif, &ext );
835 } while( rec != TERMINATE_RECORD_TYPE );
837 // if the gif main says we have more than one image or our image counting
838 // says so, then this image is animated - indicate this
839 if( (gif->ImageCount > 1) || (imageNumber > 1) )
841 animated.animated = 1;
842 animated.loopCount = loopCount;
844 animated.frameCount = std::min( gif->ImageCount, imageNumber );
851 animated.currentFrame = 1;
853 // no errors in header scan etc. so set err and return value
857 on_error: // jump here on any errors to clean up
858 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
861 DGifCloseFile( gif, NULL );
866 DGifCloseFile( gif );
874 * @brief Reader next frame of the gif file and populates structures accordingly.
876 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
877 * @param[in/out] prop A ImageProperties structure containing information about gif data.
878 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
879 * @param[out] error Error code
880 * @return The true or false whether reading was successful or not.
882 bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
883 unsigned char *pixels, int *error )
885 GifAnimationData &animated = loaderInfo.animated;
886 LoaderInfo::FileData &fileData = loaderInfo.fileData;
889 GifFileType *gif = NULL;
890 int index = 0, imageNumber = 0;
891 FrameInfo *frameInfo;
892 ImageFrame *frame = NULL;
893 ImageFrame *lastPreservedFrame = NULL;
895 index = animated.currentFrame;
897 // if index is invalid for animated image - error out
898 if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
900 LOADERR("LOAD_ERROR_GENERIC");
903 // find the given frame index
904 frame = FindFrame( animated, index );
907 if( (frame->loaded) && (frame->data) )
909 // frame is already there and decoded - jump to end
915 LOADERR("LOAD_ERROR_CORRUPT_FILE");
919 // actually ask libgif to open the file
920 gif = loaderInfo.gif;
923 loaderInfo.fileInfo.map = fileData.globalMap ;
924 if( !loaderInfo.fileInfo.map )
926 LOADERR("LOAD_ERROR_CORRUPT_FILE");
928 loaderInfo.fileInfo.length = fileData.length;
929 loaderInfo.fileInfo.position = 0;
931 #if GIFLIB_MAJOR >= 5
932 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead, NULL );
934 gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead );
936 // if gif open failed... get out of here
939 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
941 loaderInfo.gif = gif;
942 loaderInfo.imageNumber = 1;
945 // if we want to go backwards, we likely need/want to re-decode from the
946 // start as we have nothing to build on
947 if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
949 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
951 DGifCloseFile( loaderInfo.gif, NULL );
954 DGifCloseFile( loaderInfo.gif );
956 loaderInfo.gif = NULL;
957 loaderInfo.imageNumber = 0;
961 // our current position is the previous frame we decoded from the file
962 imageNumber = loaderInfo.imageNumber;
964 // walk through gif records in file to figure out info
967 if( DGifGetRecordType( gif, &rec ) == GIF_ERROR )
969 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
972 if( rec == EXTENSION_RECORD_TYPE )
975 GifByteType *ext = NULL;
976 DGifGetExtension( gif, &ext_code, &ext );
981 DGifGetExtensionNext( gif, &ext );
984 // get image description section
985 else if( rec == IMAGE_DESC_RECORD_TYPE )
987 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
990 ImageFrame *previousFrame = NULL;
991 ImageFrame *thisFrame = NULL;
994 if( DGifGetImageDesc(gif) == GIF_ERROR )
996 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
999 // get the previous frame entry AND the current one to fill in
1000 previousFrame = FindFrame(animated, imageNumber - 1);
1001 thisFrame = FindFrame(animated, imageNumber);
1003 // if we have a frame AND we're animated AND we have no data...
1004 if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
1009 thisFrame->data = new uint32_t[prop.w * prop.h];
1011 if( !thisFrame->data )
1013 LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1016 // if we have no prior frame OR prior frame data... empty
1017 if( (!previousFrame) || (!previousFrame->data) )
1020 frameInfo = &(thisFrame->info);
1021 memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
1023 // we have a prior frame to copy data from...
1026 frameInfo = &( previousFrame->info );
1028 // fix coords of sub image in case it goes out...
1029 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1030 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1033 // if dispose mode is not restore - then copy pre frame
1034 if( frameInfo->dispose != DISPOSE_PREVIOUS )
1036 memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1039 // if dispose mode is "background" then fill with bg
1040 if( frameInfo->dispose == DISPOSE_BACKGROUND )
1042 FillFrame( thisFrame->data, prop.w, gif, frameInfo, x, y, w, h );
1044 else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
1049 // Find last preserved frame.
1050 lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
1051 if( ! lastPreservedFrame )
1053 LOADERR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
1056 } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
1058 if ( lastPreservedFrame )
1060 memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1064 // now draw this frame on top
1065 frameInfo = &( thisFrame->info );
1066 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1067 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1069 if( !DecodeImage( gif, thisFrame->data, prop.w,
1070 xin, yin, frameInfo->transparent,
1071 x, y, w, h, first) )
1073 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1076 // mark as loaded and done
1077 thisFrame->loaded = true;
1079 FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
1081 // if we hve a frame BUT the image is not animated... different
1083 else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
1085 // if we don't have the data decoded yet - decode it
1086 if( (!thisFrame->loaded) || (!thisFrame->data) )
1088 // use frame info but we WONT allocate frame pixels
1089 frameInfo = &( thisFrame->info );
1090 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1091 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1094 // clear out all pixels
1095 FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, gif, frameInfo, 0, 0, prop.w, prop.h );
1097 // and decode the gif with overwriting
1098 if( !DecodeImage( gif, reinterpret_cast<uint32_t *>(pixels), prop.w,
1099 xin, yin, frameInfo->transparent, x, y, w, h, true) )
1101 LOADERR("LOAD_ERROR_CORRUPT_FILE");
1104 // mark as loaded and done
1105 thisFrame->loaded = true;
1107 // flush mem we don't need (at expense of decode cpu)
1111 // skip decoding and just walk image to next
1112 if( DGifGetCode( gif, &img_code, &img ) == GIF_ERROR )
1114 LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
1120 DGifGetCodeNext( gif, &img );
1125 // if we found the image we wanted - get out of here
1126 if( imageNumber > index )
1131 } while( rec != TERMINATE_RECORD_TYPE );
1133 // if we are at the end of the animation or not animated, close file
1134 loaderInfo.imageNumber = imageNumber;
1135 if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
1137 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
1138 if( loaderInfo.gif )
1140 DGifCloseFile( loaderInfo.gif, NULL );
1143 if( loaderInfo.gif )
1145 DGifCloseFile( loaderInfo.gif );
1149 loaderInfo.gif = NULL;
1150 loaderInfo.imageNumber = 0;
1154 // no errors in header scan etc. so set err and return value
1158 // if it was an animated image we need to copy the data to the
1159 // pixels for the image from the frame holding the data
1160 if( animated.animated && frame->data )
1162 memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
1165 on_error: // jump here on any errors to clean up
1169 } // unnamed namespace
1171 struct GifLoading::Impl
1174 Impl( const std::string& url, bool isLocalResource )
1177 loaderInfo.gif = nullptr;
1179 loaderInfo.fileData.fileName = mUrl.c_str();
1180 loaderInfo.fileData.isLocalResource = isLocalResource;
1182 ReadHeader( loaderInfo, imageProperties, &error );
1187 if( loaderInfo.fileData.globalMap )
1189 if( loaderInfo.fileData.isLocalResource )
1191 munmap( loaderInfo.fileData.globalMap , loaderInfo.fileData.length );
1195 free( loaderInfo.fileData.globalMap );
1197 loaderInfo.fileData.globalMap = nullptr;
1202 LoaderInfo loaderInfo;
1203 ImageProperties imageProperties;
1206 std::unique_ptr<GifLoading> GifLoading::New( const std::string &url, bool isLocalResource )
1208 return std::unique_ptr<GifLoading>( new GifLoading( url, isLocalResource ) );
1211 GifLoading::GifLoading( const std::string &url, bool isLocalResource )
1212 : mImpl( new GifLoading::Impl( url, isLocalResource ) )
1217 GifLoading::~GifLoading()
1222 bool GifLoading::LoadNextNFrames( int frameStartIndex, int count, std::vector<Dali::PixelData> &pixelData )
1227 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t );
1229 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count );
1231 for( int i = 0; i < count; ++i )
1233 auto pixelBuffer = new unsigned char[ bufferSize ];
1235 mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount );
1237 if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) )
1241 pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize,
1242 mImpl->imageProperties.w, mImpl->imageProperties.h,
1243 Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) );
1252 bool GifLoading::LoadAllFrames( std::vector<Dali::PixelData> &pixelData, Dali::Vector<uint32_t> &frameDelays )
1254 if( LoadFrameDelays( frameDelays ) )
1256 return LoadNextNFrames( 0, mImpl->loaderInfo.animated.frameCount, pixelData );
1261 ImageDimensions GifLoading::GetImageSize()
1263 return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.h );
1266 int GifLoading::GetImageCount()
1268 return mImpl->loaderInfo.animated.frameCount;
1271 bool GifLoading::LoadFrameDelays( Dali::Vector<uint32_t> &frameDelays )
1273 frameDelays.Clear();
1275 for( auto &&elem : mImpl->loaderInfo.animated.frames )
1277 // Read frame delay time, multiply 10 to change time unit to milliseconds
1278 frameDelays.PushBack( elem.info.delay * 10 );