2 * Copyright (c) 2020 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 * Copyright notice for the EFL:
17 * Copyright (C) EFL developers (see AUTHORS)
21 #include <dali/internal/imaging/common/gif-loading.h>
24 #include <sys/types.h>
32 #include <dali/integration-api/debug.h>
33 #include <dali/public-api/images/pixel-data.h>
34 #include <dali/internal/imaging/common/file-download.h>
35 #include <dali/internal/system/common/file-reader.h>
37 #define IMG_TOO_BIG( w, h ) \
38 ( ( static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h) ) >= \
39 ( (1ULL << (29 * (sizeof(void *) / 4))) - 2048) )
41 #define LOADERR( x ) \
43 DALI_LOG_ERROR( x ); \
58 #if defined(DEBUG_ENABLED)
59 Debug::Filter *gGifLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" );
62 const int IMG_MAX_SIZE = 65000;
63 constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024;
66 const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
67 const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
79 dispose( DISPOSE_BACKGROUND ),
85 unsigned short delay; // delay time in 1/100ths of a sec
86 short transparent : 10; // -1 == not, anything else == index
87 short dispose : 6; // 0, 1, 2, 3 (others invalid)
88 short interlace : 1; // interlaced or not
103 if( data != nullptr )
105 // De-allocate memory of the frame data.
112 uint32_t *data; /* frame decoding data */
113 FrameInfo info; /* special image type info */
117 struct GifAnimationData
128 std::vector<ImageFrame> frames;
135 // Forward declaration
147 : fileName( nullptr ),
148 globalMap ( nullptr ),
150 isLocalResource( true )
166 bool LoadLocalFile();
167 bool LoadRemoteFile();
170 const char *fileName; /**< The absolute path of the file. */
171 unsigned char *globalMap ; /**< A pointer to the entire contents of the file */
172 long long length; /**< The length of the file in bytes. */
173 bool isLocalResource; /**< The flag whether the file is a local resource */
186 int position, length; // yes - gif uses ints for file sizes.
190 GifAnimationData animated;
191 std::unique_ptr<GifAccessor> gifAccessor{nullptr};
196 struct ImageProperties
204 * Class to access gif open/close using riaa
210 * @param[in,out] fileInfo Contains ptr to memory, and is updated by DGifOpen
212 GifAccessor(LoaderInfo::FileInfo& fileInfo)
215 // actually ask libgif to open the file
216 #if GIFLIB_MAJOR >= 5
217 gif = DGifOpen( &fileInfo, FileRead, NULL );
219 gif = DGifOpen( &fileInfo, FileRead );
224 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT");
232 #if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
233 DGifCloseFile( gif, NULL );
235 DGifCloseFile( gif );
241 * @brief Copy data from gif file into buffer.
243 * @param[in] gifFileType A pointer pointing to GIF File Type
244 * @param[out] buffer A pointer to buffer containing GIF raw data
245 * @param[in] len The length in bytes to be copied
246 * @return The data length of the image in bytes
248 static int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length )
250 LoaderInfo::FileInfo *fi = reinterpret_cast<LoaderInfo::FileInfo *>( gifFileType->UserData );
252 if( fi->position >= fi->length )
254 return 0; // if at or past end - no
256 if( (fi->position + length) >= fi->length )
258 length = fi->length - fi->position;
260 memcpy( buffer, fi->map + fi->position, length );
261 fi->position += length;
266 GifFileType *gif = nullptr;
269 bool LoaderInfo::FileData::LoadFile()
272 if( isLocalResource )
274 success = LoadLocalFile();
278 success = LoadRemoteFile();
283 bool LoaderInfo::FileData::LoadLocalFile()
285 Internal::Platform::FileReader fileReader( fileName );
286 FILE *fp = fileReader.GetFile();
292 if( fseek( fp, 0, SEEK_END ) <= -1 )
297 length = ftell( fp );
303 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
305 globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * length ) );
306 length = fread( globalMap, sizeof( GifByteType ), length, fp);
315 bool LoaderInfo::FileData::LoadRemoteFile()
318 bool succeeded=false;
319 Dali::Vector<uint8_t> dataBuffer;
322 succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( fileName, dataBuffer, dataSize,
323 MAXIMUM_DOWNLOAD_IMAGE_SIZE );
326 size_t blobSize = dataBuffer.Size();
329 // Open a file handle on the memory buffer:
330 Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize );
331 FILE * const fp = fileReader.GetFile();
334 if( ( ! fseek( fp, 0, SEEK_SET ) ) )
336 globalMap = reinterpret_cast<GifByteType*>( malloc(sizeof( GifByteType ) * blobSize ) );
337 length = fread( globalMap, sizeof( GifByteType ), blobSize, fp);
342 DALI_LOG_ERROR( "Error seeking within file\n" );
347 DALI_LOG_ERROR( "Error reading file\n" );
357 * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
359 * @param[in] animated A structure containing GIF animation data
360 * @param[in] index Frame index to be searched in GIF
361 * @return A pointer to the ImageFrame.
363 inline int CombinePixelABGR( int a, int r, int g, int b )
365 return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) );
368 inline int PixelLookup( ColorMapObject *colorMap, int index )
370 return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue );
374 * @brief Brute force find frame index - gifs are normally small so ok for now.
376 * @param[in] animated A structure containing GIF animation data
377 * @param[in] index Frame index to be searched in GIF
378 * @return A pointer to the ImageFrame.
380 ImageFrame *FindFrame( const GifAnimationData &animated, int index )
382 for( auto &&elem : animated.frames )
384 if( elem.index == index )
386 return const_cast<ImageFrame *>( &elem );
393 * @brief Fill in an image with a specific rgba color value.
395 * @param[in] data A pointer pointing to an image data
396 * @param[in] row A int containing the number of rows in an image
397 * @param[in] val A uint32_t containing rgba color value
398 * @param[in] x X-coordinate used an offset to calculate pixel position
399 * @param[in] y Y-coordinate used an offset to calculate pixel position
400 * @param[in] width Width of the image
401 * @param[in] height Height of the image
403 void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height )
406 uint32_t *pixelPosition;
408 for( yAxis = 0; yAxis < height; yAxis++ )
410 pixelPosition = data + ((y + yAxis) * row) + x;
411 for( xAxis = 0; xAxis < width; xAxis++ )
413 *pixelPosition = val;
420 * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
422 * @param[in] data A pointer pointing to an image data
423 * @param[in] row A int containing the number of rows in an image
424 * @param[in] gif A pointer pointing to GIF File Type
425 * @param[in] frameInfo A pointer pointing to Frame Information data
426 * @param[in] x X-coordinate used an offset to calculate pixel position
427 * @param[in] y Y-coordinate used an offset to calculate pixel position
428 * @param[in] width Width of the image
429 * @param[in] height Height of the image
431 void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h )
433 // solid color fill for pre frame region
434 if( frameInfo->transparent < 0 )
436 ColorMapObject *colorMap;
439 // work out color to use from colorMap
440 if( gif->Image.ColorMap )
442 colorMap = gif->Image.ColorMap;
446 colorMap = gif->SColorMap;
448 backGroundColor = gif->SBackGroundColor;
450 FillImage( data, row,
451 CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red,
452 colorMap->Colors[backGroundColor].Green,
453 colorMap->Colors[backGroundColor].Blue ),
456 // fill in region with 0 (transparent)
459 FillImage( data, row, 0, x, y, w, h );
464 * @brief Store common fields from gif file info into frame info
466 * @param[in] gif A pointer pointing to GIF File Type
467 * @param[in] frameInfo A pointer pointing to Frame Information data
469 void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo )
471 frameInfo->x = gif->Image.Left;
472 frameInfo->y = gif->Image.Top;
473 frameInfo->w = gif->Image.Width;
474 frameInfo->h = gif->Image.Height;
475 frameInfo->interlace = gif->Image.Interlace;
479 * @brief Check if image fills "screen space" and if so, if it is transparent
480 * at all then the image could be transparent - OR if image doesnt fill,
481 * then it could be trasnparent (full coverage of screen). Some gifs will
482 * be recognized as solid here for faster rendering, but not all.
484 * @param[out] full A boolean to show whether image is transparent or not
485 * @param[in] frameInfo A pointer pointing to Frame Information data
486 * @param[in] width Width of the image
487 * @param[in] height Height of the image
489 void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height )
491 if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) &&
492 ( frameInfo->w == width ) && ( frameInfo->h == height ) )
494 if( frameInfo->transparent >= 0 )
506 * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
508 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 )
516 if( (x0 + w0) > imageWidth )
518 w0 = imageWidth - x0;
526 if( (y0 + h0) > imageHeight )
528 h0 = imageHeight - y0;
537 * @brief Flush out rgba frame images to save memory but skip current,
538 * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
540 * @param[in] animated A structure containing GIF animation data
541 * @param[in] width Width of the image
542 * @param[in] height Height of the image
543 * @param[in] thisframe The current frame
544 * @param[in] prevframe The previous frame
545 * @param[in] lastPreservedFrame The last preserved frame
547 void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame )
549 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" );
551 // target is the amount of memory we want to be under for stored frames
552 int total = 0, target = 512 * 1024;
554 // total up the amount of memory used by stored frames for this image
555 for( auto &&frame : animated.frames )
562 total *= ( width * height * sizeof( uint32_t ) );
564 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total );
566 // If we use more than target (512k) for frames - flush
569 // Clean frames (except current and previous) until below target
570 for( auto &&frame : animated.frames )
572 if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
573 (!lastPreservedFrame || frame.index != lastPreservedFrame->index) )
575 if( frame.data != nullptr )
578 frame.data = nullptr;
580 // subtract memory used and if below target - stop flush
581 total -= ( width * height * sizeof( uint32_t ) );
591 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" );
595 * @brief allocate frame and frame info and append to list and store fields.
597 * @param[in] animated A structure containing GIF animation data
598 * @param[in] transparent Transparent index of the new frame
599 * @param[in] dispose Dispose mode of new frame
600 * @param[in] delay The frame delay of new frame
601 * @param[in] index The index of new frame
603 FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index )
607 // record transparent index to be used or -1 if none
608 // for this SPECIFIC frame
609 frame.info.transparent = transparent;
610 // record dispose mode (3 bits)
611 frame.info.dispose = dispose;
612 // record delay (2 bytes so max 65546 /100 sec)
613 frame.info.delay = delay;
614 // record the index number we are at
616 // that frame is stored AT image/screen size
618 animated.frames.push_back( frame );
620 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() );
622 return &( animated.frames.back().info );
627 * @brief Decode a gif image into rows then expand to 32bit into the destination
630 bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin,
631 int transparent, int x, int y, int w, int h, bool fill )
633 int intoffset[] = {0, 4, 2, 1};
634 int intjump[] = {8, 8, 4, 2};
635 int i, xx, yy, pix, gifW, gifH;
636 GifRowType *rows = NULL;
638 ColorMapObject *colorMap;
641 // what we need is image size.
643 sp = &gif->SavedImages[ gif->ImageCount - 1 ];
645 gifW = sp->ImageDesc.Width;
646 gifH = sp->ImageDesc.Height;
648 if( ( gifW < w ) || ( gifH < h ) )
650 DALI_ASSERT_DEBUG( false && "Dimensions are bigger than the Gif image size");
654 // build a blob of memory to have pointers to rows of pixels
655 // AND store the decoded gif pixels (1 byte per pixel) as welll
656 rows = static_cast<GifRowType *>( malloc( (gifH * sizeof(GifRowType) ) + ( gifW * gifH * sizeof(GifPixelType) )));
662 // fill in the pointers at the start
663 for( yy = 0; yy < gifH; yy++ )
665 rows[yy] = reinterpret_cast<unsigned char *>(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType));
668 // if gif is interlaced, walk interlace pattern and decode into rows
669 if( gif->Image.Interlace )
671 for( i = 0; i < 4; i++ )
673 for( yy = intoffset[i]; yy < gifH; yy += intjump[i] )
675 if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK )
682 // normal top to bottom - decode into rows
685 for( yy = 0; yy < gifH; yy++ )
687 if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK )
694 // work out what colormap to use
695 if( gif->Image.ColorMap )
697 colorMap = gif->Image.ColorMap;
701 colorMap = gif->SColorMap;
704 // if we need to deal with transparent pixels at all...
705 if( transparent >= 0 )
707 // if we are told to FILL (overwrite with transparency kept)
710 for( yy = 0; yy < h; yy++ )
712 p = data + ((y + yy) * rowpix) + x;
713 for( xx = 0; xx < w; xx++ )
715 pix = rows[yin + yy][xin + xx];
716 if( pix != transparent )
718 *p = PixelLookup( colorMap, pix );
728 // paste on top with transparent pixels untouched
731 for( yy = 0; yy < h; yy++ )
733 p = data + ((y + yy) * rowpix) + x;
734 for( xx = 0; xx < w; xx++ )
736 pix = rows[yin + yy][xin + xx];
737 if( pix != transparent )
739 *p = PixelLookup( colorMap, pix );
748 // walk pixels without worring about transparency at all
749 for( yy = 0; yy < h; yy++ )
751 p = data + ((y + yy) * rowpix) + x;
752 for( xx = 0; xx < w; xx++ )
754 pix = rows[yin + yy][xin + xx];
755 *p = PixelLookup( colorMap, pix );
773 * @brief Reader header from the gif file and populates structures accordingly.
775 * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
776 * @param[out] prop A ImageProperties structure for storing information about GIF data.
777 * @param[out] error Error code
778 * @return The true or false whether reading was successful or not.
780 bool ReadHeader( LoaderInfo &loaderInfo,
781 ImageProperties &prop, //output struct
784 GifAnimationData &animated = loaderInfo.animated;
785 LoaderInfo::FileData &fileData = loaderInfo.fileData;
786 bool success = false;
787 LoaderInfo::FileInfo fileInfo;
790 // it is possible which gif file have error midle of frames,
791 // in that case we should play gif file until meet error frame.
794 FrameInfo *frameInfo = NULL;
797 success = fileData.LoadFile();
798 if(!success || !fileData.globalMap)
801 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE");
805 fileInfo.map = fileData.globalMap;
806 fileInfo.length = fileData.length;
807 fileInfo.position = 0;
808 GifAccessor gifAccessor(fileInfo);
810 if( gifAccessor.gif )
812 // get the gif "screen size" (the actual image size)
813 prop.w = gifAccessor.gif->SWidth;
814 prop.h = gifAccessor.gif->SHeight;
816 // if size is invalid - abort here
817 if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
819 if( IMG_TOO_BIG(prop.w, prop.h) )
822 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
827 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
832 // walk through gif records in file to figure out info
836 if( DGifGetRecordType(gifAccessor.gif, &rec) == GIF_ERROR )
838 // if we have a gif that ends part way through a sequence
839 // (or animation) consider it valid and just break - no error
840 if( imageNumber <= 1 )
847 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT");
852 // get image description section
853 if( rec == IMAGE_DESC_RECORD_TYPE )
859 if( DGifGetImageDesc(gifAccessor.gif) == GIF_ERROR )
862 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT");
865 // skip decoding and just walk image to next
866 if( DGifGetCode(gifAccessor.gif, &img_code, &img) == GIF_ERROR )
869 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT");
876 DGifGetCodeNext( gifAccessor.gif, &img );
878 // store geometry in the last frame info data
881 StoreFrameInfo( gifAccessor.gif, frameInfo );
882 CheckTransparency( full, frameInfo, prop.w, prop.h );
884 // or if we dont have a frameInfo entry - create one even for stills
887 // allocate and save frame with field data
888 frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
892 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
895 // store geometry info from gif image
896 StoreFrameInfo( gifAccessor.gif, frameInfo );
897 // check for transparency/alpha
898 CheckTransparency( full, frameInfo, prop.w, prop.h );
902 // we have an extension code block - for animated gifs for sure
903 else if( rec == EXTENSION_RECORD_TYPE )
906 GifByteType *ext = NULL;
908 // get the first extension entry
909 DGifGetExtension( gifAccessor.gif, &ext_code, &ext );
912 // graphic control extension - for animated gif data
913 // and transparent index + flag
914 if( ext_code == 0xf9 )
916 // create frame and store it in image
917 int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
918 int disposeMode = (ext[1] >> 2) & 0x7;
919 int delay = (int(ext[3]) << 8) | int(ext[2]);
920 frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
924 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
928 // netscape extension indicating loop count.
929 else if( ext_code == 0xff ) /* application extension */
931 if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
932 !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
935 DGifGetExtensionNext( gifAccessor.gif, &ext );
938 loopCount = (int(ext[3]) << 8) | int(ext[2]);
947 // and continue onto the next extension entry
949 DGifGetExtensionNext( gifAccessor.gif, &ext );
952 } while( rec != TERMINATE_RECORD_TYPE && success );
956 // if the gif main says we have more than one image or our image counting
957 // says so, then this image is animated - indicate this
958 if( (gifAccessor.gif->ImageCount > 1) || (imageNumber > 1) )
960 animated.animated = 1;
961 animated.loopCount = loopCount;
963 animated.frameCount = std::min( gifAccessor.gif->ImageCount, imageNumber );
970 animated.currentFrame = 1;
972 // no errors in header scan etc. so set err and return value
982 * @brief Reader next frame of the gif file and populates structures accordingly.
984 * @param[in,out] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
985 * @param[in,out] prop A ImageProperties structure containing information about gif data.
986 * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
987 * @param[out] error Error code
988 * @return The true or false whether reading was successful or not.
990 bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
991 unsigned char *pixels, int *error )
993 GifAnimationData &animated = loaderInfo.animated;
994 LoaderInfo::FileData &fileData = loaderInfo.fileData;
997 int index = 0, imageNumber = 0;
998 FrameInfo *frameInfo;
999 ImageFrame *frame = NULL;
1000 ImageFrame *lastPreservedFrame = NULL;
1002 index = animated.currentFrame;
1004 // if index is invalid for animated image - error out
1005 if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
1007 DALI_LOG_ERROR("LOAD_ERROR_GENERIC");
1011 // find the given frame index
1012 frame = FindFrame( animated, index );
1015 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE");
1018 else if( !(frame->loaded) || !(frame->data) )
1020 // if we want to go backwards, we likely need/want to re-decode from the
1021 // start as we have nothing to build on. If there is a gif, imageNumber
1022 // has been set already.
1023 if( loaderInfo.gifAccessor && loaderInfo.imageNumber > 0)
1025 if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
1027 loaderInfo.gifAccessor.reset();
1028 loaderInfo.imageNumber = 0;
1032 // actually ask libgif to open the file
1033 if( !loaderInfo.gifAccessor )
1035 loaderInfo.fileInfo.map = fileData.globalMap ;
1036 loaderInfo.fileInfo.length = fileData.length;
1037 loaderInfo.fileInfo.position = 0;
1038 if( !loaderInfo.fileInfo.map )
1040 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE");
1043 std::unique_ptr<GifAccessor> gifAccessor = std::make_unique<GifAccessor>(loaderInfo.fileInfo);
1044 if( !gifAccessor->gif )
1046 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT");
1049 loaderInfo.gifAccessor = std::move(gifAccessor);
1050 loaderInfo.imageNumber = 1;
1053 // our current position is the previous frame we decoded from the file
1054 imageNumber = loaderInfo.imageNumber;
1056 // walk through gif records in file to figure out info
1059 if( DGifGetRecordType( loaderInfo.gifAccessor->gif, &rec ) == GIF_ERROR )
1061 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT");
1065 if( rec == EXTENSION_RECORD_TYPE )
1068 GifByteType *ext = NULL;
1069 DGifGetExtension( loaderInfo.gifAccessor->gif, &ext_code, &ext );
1074 DGifGetExtensionNext( loaderInfo.gifAccessor->gif, &ext );
1077 // get image description section
1078 else if( rec == IMAGE_DESC_RECORD_TYPE )
1080 int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
1083 ImageFrame *previousFrame = NULL;
1084 ImageFrame *thisFrame = NULL;
1087 if( DGifGetImageDesc(loaderInfo.gifAccessor->gif) == GIF_ERROR )
1089 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT");
1093 // get the previous frame entry AND the current one to fill in
1094 previousFrame = FindFrame(animated, imageNumber - 1);
1095 thisFrame = FindFrame(animated, imageNumber);
1097 // if we have a frame AND we're animated AND we have no data...
1098 if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
1103 thisFrame->data = new uint32_t[prop.w * prop.h];
1105 if( !thisFrame->data )
1107 DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
1111 // if we have no prior frame OR prior frame data... empty
1112 if( (!previousFrame) || (!previousFrame->data) )
1115 frameInfo = &(thisFrame->info);
1116 memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
1118 // we have a prior frame to copy data from...
1121 frameInfo = &( previousFrame->info );
1123 // fix coords of sub image in case it goes out...
1124 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1125 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1128 // if dispose mode is not restore - then copy pre frame
1129 if( frameInfo->dispose != DISPOSE_PREVIOUS )
1131 memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1134 // if dispose mode is "background" then fill with bg
1135 if( frameInfo->dispose == DISPOSE_BACKGROUND )
1137 FillFrame( thisFrame->data, prop.w, loaderInfo.gifAccessor->gif, frameInfo, x, y, w, h );
1139 else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
1144 // Find last preserved frame.
1145 lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
1146 if( ! lastPreservedFrame )
1148 DALI_LOG_ERROR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
1152 } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
1154 if ( lastPreservedFrame )
1156 memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
1160 // now draw this frame on top
1161 frameInfo = &( thisFrame->info );
1162 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1163 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1165 if( !DecodeImage( loaderInfo.gifAccessor->gif, thisFrame->data, prop.w,
1166 xin, yin, frameInfo->transparent,
1167 x, y, w, h, first) )
1169 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE");
1173 // mark as loaded and done
1174 thisFrame->loaded = true;
1176 FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
1178 // if we have a frame BUT the image is not animated. different
1180 else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
1182 // if we don't have the data decoded yet - decode it
1183 if( (!thisFrame->loaded) || (!thisFrame->data) )
1185 // use frame info but we WONT allocate frame pixels
1186 frameInfo = &( thisFrame->info );
1187 ClipCoordinates( prop.w, prop.h, &xin, &yin,
1188 frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
1191 // clear out all pixels
1192 FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, loaderInfo.gifAccessor->gif,
1193 frameInfo, 0, 0, prop.w, prop.h );
1195 // and decode the gif with overwriting
1196 if( !DecodeImage( loaderInfo.gifAccessor->gif, reinterpret_cast<uint32_t *>(pixels),
1197 prop.w, xin, yin, frameInfo->transparent, x, y, w, h, true) )
1199 DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE");
1203 // mark as loaded and done
1204 thisFrame->loaded = true;
1206 // flush mem we don't need (at expense of decode cpu)
1210 // skip decoding and just walk image to next
1211 if( DGifGetCode( loaderInfo.gifAccessor->gif, &img_code, &img ) == GIF_ERROR )
1213 DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT");
1220 DGifGetCodeNext( loaderInfo.gifAccessor->gif, &img );
1225 // if we found the image we wanted - get out of here
1226 if( imageNumber > index )
1231 } while( rec != TERMINATE_RECORD_TYPE );
1233 // if we are at the end of the animation or not animated, close file
1234 loaderInfo.imageNumber = imageNumber;
1235 if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
1237 loaderInfo.gifAccessor.reset();
1238 loaderInfo.imageNumber = 0;
1242 // no errors in header scan etc. so set err and return value
1246 // if it was an animated image we need to copy the data to the
1247 // pixels for the image from the frame holding the data
1248 if( animated.animated && frame->data )
1250 memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
1256 } // unnamed namespace
1258 struct GifLoading::Impl
1261 Impl( const std::string& url, bool isLocalResource )
1264 loaderInfo.gifAccessor = nullptr;
1266 loaderInfo.fileData.fileName = mUrl.c_str();
1267 loaderInfo.fileData.isLocalResource = isLocalResource;
1269 ReadHeader( loaderInfo, imageProperties, &error );
1272 // Moveable but not copyable
1273 Impl( const Impl& ) = delete;
1274 Impl& operator=( const Impl& ) = delete;
1275 Impl( Impl&& ) = default;
1276 Impl& operator=( Impl&& ) = default;
1279 LoaderInfo loaderInfo;
1280 ImageProperties imageProperties;
1283 AnimatedImageLoadingPtr GifLoading::New( const std::string &url, bool isLocalResource )
1285 return AnimatedImageLoadingPtr( new GifLoading( url, isLocalResource ) );
1288 GifLoading::GifLoading( const std::string &url, bool isLocalResource )
1289 : mImpl( new GifLoading::Impl( url, isLocalResource ) )
1294 GifLoading::~GifLoading()
1299 bool GifLoading::LoadNextNFrames( uint32_t frameStartIndex, int count, std::vector<Dali::PixelData> &pixelData )
1304 const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t );
1306 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count );
1308 for( int i = 0; i < count; ++i )
1310 auto pixelBuffer = new unsigned char[ bufferSize ];
1312 mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount );
1314 if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) )
1318 pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize,
1319 mImpl->imageProperties.w, mImpl->imageProperties.h,
1320 Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) );
1329 Dali::Devel::PixelBuffer GifLoading::LoadFrame( uint32_t frameIndex )
1332 Dali::Devel::PixelBuffer pixelBuffer;
1334 DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex );
1336 pixelBuffer = Dali::Devel::PixelBuffer::New( mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888 );
1338 mImpl->loaderInfo.animated.currentFrame = 1 + ( frameIndex % mImpl->loaderInfo.animated.frameCount );
1339 ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer.GetBuffer(), &error );
1343 pixelBuffer = Dali::Devel::PixelBuffer();
1348 ImageDimensions GifLoading::GetImageSize() const
1350 return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.h );
1353 uint32_t GifLoading::GetImageCount() const
1355 return mImpl->loaderInfo.animated.frameCount;
1358 uint32_t GifLoading::GetFrameInterval( uint32_t frameIndex ) const
1360 return mImpl->loaderInfo.animated.frames[frameIndex].info.delay * 10;
1363 std::string GifLoading::GetUrl() const
1368 } // namespace Adaptor
1370 } // namespace Internal