2 * Copyright (c) 2015 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.
19 #include "loader-jpeg.h"
20 #include "resource-loading-client.h"
21 #include <dali/integration-api/bitmap.h>
22 #include <resource-loader/debug/resource-loader-debug.h>
23 #include "platform-capabilities.h"
24 #include "image-operations.h"
27 #include <libexif/exif-data.h>
28 #include <libexif/exif-loader.h>
29 #include <libexif/exif-tag.h>
30 #include <turbojpeg.h>
37 using Integration::Bitmap;
39 namespace TizenPlatform
44 const unsigned DECODED_PIXEL_SIZE = 3;
45 const TJPF DECODED_PIXEL_LIBJPEG_TYPE = TJPF_RGB;
47 /** Transformations that can be applied to decoded pixels to respect exif orientation
48 * codes in image headers */
51 JPGFORM_NONE = 1, /* no transformation 0th-Row = top & 0th-Column = left */
52 JPGFORM_FLIP_H, /* horizontal flip 0th-Row = top & 0th-Column = right */
53 JPGFORM_FLIP_V, /* vertical flip 0th-Row = bottom & 0th-Column = right*/
54 JPGFORM_TRANSPOSE, /* transpose across UL-to-LR axis 0th-Row = bottom & 0th-Column = left*/
55 JPGFORM_TRANSVERSE,/* transpose across UR-to-LL axis 0th-Row = left & 0th-Column = top*/
56 JPGFORM_ROT_90, /* 90-degree clockwise rotation 0th-Row = right & 0th-Column = top*/
57 JPGFORM_ROT_180, /* 180-degree rotation 0th-Row = right & 0th-Column = bottom*/
58 JPGFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) 0th-Row = left & 0th-Column = bottom*/
69 * @brief Error handling bookeeping for the JPEG Turbo library's
70 * setjmp/longjmp simulated exceptions.
72 struct JpegErrorState {
73 struct jpeg_error_mgr errorManager;
78 * @brief Called by the JPEG library when it hits an error.
79 * We jump out of the library so our loader code can return an error.
81 void JpegErrorHandler ( j_common_ptr cinfo )
83 DALI_LOG_ERROR( "JpegErrorHandler(): libjpeg-turbo fatal error in JPEG decoding.\n" );
84 /* cinfo->err really points to a JpegErrorState struct, so coerce pointer */
85 JpegErrorState * myerr = reinterpret_cast<JpegErrorState *>( cinfo->err );
87 /* Return control to the setjmp point */
88 longjmp( myerr->jumpBuffer, 1 );
91 void JpegOutputMessageHandler( j_common_ptr cinfo )
93 /* Stop libjpeg from printing to stderr - Do Nothing */
96 /** Simple struct to ensure xif data is deleted. */
99 ExifAutoPtr( ExifData* data)
105 exif_data_free( mData);
110 /** simple class to enforce clean-up of JPEG structures. */
113 AutoJpg(const tjhandle jpgHandle)
120 // clean up JPG resources
124 tjhandle GetHandle() const
130 AutoJpg( const AutoJpg& ); //< not defined
131 AutoJpg& operator= ( const AutoJpg& ); //< not defined
134 }; // struct AutoJpg;
136 /** RAII wrapper to free memory allocated by the jpeg-turbo library. */
139 AutoJpgMem(unsigned char * const tjMem)
149 unsigned char * Get() const
155 AutoJpgMem( const AutoJpgMem& ); //< not defined
156 AutoJpgMem& operator= ( const AutoJpgMem& ); //< not defined
158 unsigned char * const mTjMem;
161 // Workaround to avoid exceeding the maximum texture size
162 const int MAX_TEXTURE_WIDTH = 4096;
163 const int MAX_TEXTURE_HEIGHT = 4096;
167 bool JpegRotate90 (unsigned char *buffer, int width, int height, int bpp);
168 bool JpegRotate180(unsigned char *buffer, int width, int height, int bpp);
169 bool JpegRotate270(unsigned char *buffer, int width, int height, int bpp);
170 JPGFORM_CODE ConvertExifOrientation(ExifData* exifData);
171 bool TransformSize( int requiredWidth, int requiredHeight,
172 FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
173 JPGFORM_CODE transform,
174 int& preXformImageWidth, int& preXformImageHeight,
175 int& postXformImageWidth, int& postXformImageHeight );
177 bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height )
179 // using libjpeg API to avoid having to read the whole file in a buffer
180 struct jpeg_decompress_struct cinfo;
181 struct JpegErrorState jerr;
182 cinfo.err = jpeg_std_error( &jerr.errorManager );
184 jerr.errorManager.output_message = JpegOutputMessageHandler;
185 jerr.errorManager.error_exit = JpegErrorHandler;
187 // On error exit from the JPEG lib, control will pass via JpegErrorHandler
188 // into this branch body for cleanup and error return:
189 if(setjmp(jerr.jumpBuffer))
191 jpeg_destroy_decompress(&cinfo);
195 jpeg_create_decompress( &cinfo );
197 jpeg_stdio_src( &cinfo, fp );
199 // Check header to see if it is JPEG file
200 if( jpeg_read_header( &cinfo, TRUE ) != JPEG_HEADER_OK )
203 jpeg_destroy_decompress( &cinfo );
207 width = cinfo.image_width;
208 height = cinfo.image_height;
210 jpeg_destroy_decompress( &cinfo );
214 bool LoadBitmapFromJpeg( const ResourceLoadingClient& client, const ImageLoader::Input& input, Integration::Bitmap& bitmap )
217 FILE* const fp = input.file;
219 if( fseek(fp,0,SEEK_END) )
221 DALI_LOG_ERROR("Error seeking to end of file\n");
225 long positionIndicator = ftell(fp);
226 unsigned int jpegBufferSize = 0u;
227 if( positionIndicator > -1L )
229 jpegBufferSize = static_cast<unsigned int>(positionIndicator);
232 if( 0u == jpegBufferSize )
237 if( fseek(fp, 0, SEEK_SET) )
239 DALI_LOG_ERROR("Error seeking to start of file\n");
243 Vector<unsigned char> jpegBuffer;
246 jpegBuffer.Reserve( jpegBufferSize );
250 DALI_LOG_ERROR( "Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U );
253 unsigned char * const jpegBufferPtr = jpegBuffer.Begin();
255 // Pull the compressed JPEG image bytes out of a file and into memory:
256 if( fread( jpegBufferPtr, 1, jpegBufferSize, fp ) != jpegBufferSize )
258 DALI_LOG_WARNING("Error on image file read.\n");
262 if( fseek(fp, 0, SEEK_SET) )
264 DALI_LOG_ERROR("Error seeking to start of file\n");
267 // Allow early cancellation between the load and the decompress:
268 client.InterruptionPoint();
270 AutoJpg autoJpg(tjInitDecompress());
272 if(autoJpg.GetHandle() == NULL)
274 DALI_LOG_ERROR("%s\n", tjGetErrorStr());
278 JPGFORM_CODE transform = JPGFORM_NONE;
280 if( input.reorientationRequested )
282 ExifAutoPtr exifData( exif_data_new_from_data(jpegBufferPtr, jpegBufferSize) );
285 transform = ConvertExifOrientation(exifData.mData);
289 // Push jpeg data in memory buffer through TurboJPEG decoder to make a raw pixel array:
290 int chrominanceSubsampling = -1;
291 int preXformImageWidth = 0, preXformImageHeight = 0;
292 if( tjDecompressHeader2( autoJpg.GetHandle(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling ) == -1 )
294 DALI_LOG_ERROR("%s\n", tjGetErrorStr());
295 // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
298 if(preXformImageWidth == 0 || preXformImageHeight == 0)
300 DALI_LOG_WARNING("Invalid Image!\n");
304 int requiredWidth = input.scalingParameters.dimensions.GetWidth();
305 int requiredHeight = input.scalingParameters.dimensions.GetHeight();
307 // If transform is a 90 or 270 degree rotation, the logical width and height
308 // request from the client needs to be adjusted to account by effectively
309 // rotating that too, and the final width and height need to be swapped:
310 int postXformImageWidth = preXformImageWidth;
311 int postXformImageHeight = preXformImageHeight;
314 int scaledPreXformWidth = preXformImageWidth;
315 int scaledPreXformHeight = preXformImageHeight;
316 int scaledPostXformWidth = postXformImageWidth;
317 int scaledPostXformHeight = postXformImageHeight;
319 TransformSize( requiredWidth, requiredHeight,
320 input.scalingParameters.scalingMode,
321 input.scalingParameters.samplingMode,
323 scaledPreXformWidth, scaledPreXformHeight,
324 scaledPostXformWidth, scaledPostXformHeight );
326 // Allocate a bitmap and decompress the jpeg buffer into its pixel buffer:
328 unsigned char * const bitmapPixelBuffer = bitmap.GetPackedPixelsProfile()->ReserveBuffer(Pixel::RGB888, scaledPostXformWidth, scaledPostXformHeight);
330 // Allow early cancellation before decoding:
331 client.InterruptionPoint();
333 if( tjDecompress2( autoJpg.GetHandle(), jpegBufferPtr, jpegBufferSize, bitmapPixelBuffer, scaledPreXformWidth, 0, scaledPreXformHeight, DECODED_PIXEL_LIBJPEG_TYPE, flags ) == -1 )
335 std::string errorString = tjGetErrorStr();
337 if( errorString.find("Corrupt JPEG data") == std::string::npos )
339 DALI_LOG_ERROR("%s\n", errorString.c_str());
344 DALI_LOG_WARNING("%s\n", errorString.c_str());
347 //TurboJPEG API functions will now return an error code if a warning is triggered in the underlying libjpeg API.
348 //So, we need to distinguish return of tjGetErrorStr() is warning or error.
349 //If the return string has 'Corrupt JPEG data' prefix, it means warning.
352 const unsigned int bufferWidth = GetTextureDimension( scaledPreXformWidth );
353 const unsigned int bufferHeight = GetTextureDimension( scaledPreXformHeight );
355 if( transform != JPGFORM_NONE )
357 // Allow early cancellation before shuffling pixels around on the CPU:
358 client.InterruptionPoint();
369 // 3 orientation changes for a camera held perpendicular to the ground or upside-down:
370 case JPGFORM_ROT_180:
372 result = JpegRotate180(bitmapPixelBuffer, bufferWidth, bufferHeight, DECODED_PIXEL_SIZE);
375 case JPGFORM_ROT_270:
377 result = JpegRotate270(bitmapPixelBuffer, bufferWidth, bufferHeight, DECODED_PIXEL_SIZE);
382 result = JpegRotate90(bitmapPixelBuffer, bufferWidth, bufferHeight, DECODED_PIXEL_SIZE);
385 /// Less-common orientation changes, since they don't correspond to a camera's
386 // physical orientation:
389 case JPGFORM_TRANSPOSE:
390 case JPGFORM_TRANSVERSE:
392 DALI_LOG_WARNING( "Unsupported JPEG Orientation transformation: %x.\n", transform );
399 ///@Todo: Move all these rotation functions to portable/image-operations and take "Jpeg" out of their names.
400 bool JpegRotate90(unsigned char *buffer, int width, int height, int bpp)
402 int w, iw, ih, hw = 0;
406 Vector<unsigned char> data;
407 data.Reserve(width * height * bpp);
408 unsigned char *dataPtr = data.Begin();
409 memcpy(dataPtr, buffer, width * height * bpp);
419 RGB888Type* to = reinterpret_cast<RGB888Type*>(buffer) + iw - 1;
420 RGB888Type* from = reinterpret_cast<RGB888Type*>( dataPtr );
422 for(ix = iw; -- ix >= 0;)
424 for(iy = ih; -- iy >= 0; ++from )
443 bool JpegRotate180(unsigned char *buffer, int width, int height, int bpp)
445 int ix, iw, ih, hw = 0;
456 RGB888Type* to = reinterpret_cast<RGB888Type*>(buffer) ;
457 RGB888Type* from = reinterpret_cast<RGB888Type*>( buffer ) + hw - 1;
458 for(; --ix >= (hw / 2); ++to, --from)
476 bool JpegRotate270(unsigned char *buffer, int width, int height, int bpp)
478 int w, iw, ih, hw = 0;
483 Vector<unsigned char> data;
484 data.Reserve(width * height * bpp);
485 unsigned char *dataPtr = data.Begin();
486 memcpy(dataPtr, buffer, width * height * bpp);
496 RGB888Type* to = reinterpret_cast<RGB888Type*>(buffer) + hw - iw;
497 RGB888Type* from = reinterpret_cast<RGB888Type*>( dataPtr );
501 for(ix = iw; -- ix >= 0;)
503 for(iy = ih; -- iy >= 0;)
522 bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char >& encodedPixels,
523 const std::size_t width, const std::size_t height, const Pixel::Format pixelFormat, unsigned quality )
527 DALI_LOG_ERROR("Null input buffer\n");
531 // Translate pixel format enum:
532 int jpegPixelFormat = -1;
534 switch( pixelFormat )
538 jpegPixelFormat = TJPF_RGB;
541 case Pixel::RGBA8888:
544 jpegPixelFormat = TJPF_RGBX;
547 case Pixel::BGRA8888:
550 jpegPixelFormat = TJPF_BGRX;
555 DALI_LOG_ERROR( "Unsupported pixel format for encoding to JPEG.\n" );
560 // Assert quality is in the documented allowable range of the jpeg-turbo lib:
561 DALI_ASSERT_DEBUG( quality >= 1 );
562 DALI_ASSERT_DEBUG( quality <= 100 );
572 // Initialise a JPEG codec:
573 AutoJpg autoJpg( tjInitCompress() );
575 if( autoJpg.GetHandle() == NULL )
577 DALI_LOG_ERROR( "JPEG Compressor init failed: %s\n", tjGetErrorStr() );
581 // Run the compressor:
582 unsigned char* dstBuffer = NULL;
583 unsigned long dstBufferSize = 0;
586 if( tjCompress2( autoJpg.GetHandle(), const_cast<unsigned char*>(pixelBuffer), width, 0, height, jpegPixelFormat, &dstBuffer, &dstBufferSize, TJSAMP_444, quality, flags ) )
588 DALI_LOG_ERROR("JPEG Compression failed: %s\n", tjGetErrorStr());
592 // Safely wrap the jpeg codec's buffer in case we are about to throw, then
593 // save the pixels to a persistent buffer that we own and let our cleaner
594 // class clean up the buffer as it goes out of scope:
595 AutoJpgMem cleaner( dstBuffer );
596 encodedPixels.Reserve( dstBufferSize );
597 memcpy( encodedPixels.Begin(), dstBuffer, dstBufferSize );
603 JPGFORM_CODE ConvertExifOrientation(ExifData* exifData)
605 JPGFORM_CODE transform = JPGFORM_NONE;
606 ExifEntry * const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
610 orientation = exif_get_short(entry->data, exif_data_get_byte_order(entry->parent->parent));
611 switch( orientation )
615 transform = JPGFORM_NONE;
620 transform = JPGFORM_FLIP_H;
625 transform = JPGFORM_FLIP_V;
630 transform = JPGFORM_TRANSPOSE;
635 transform = JPGFORM_TRANSVERSE;
640 transform = JPGFORM_ROT_90;
645 transform = JPGFORM_ROT_180;
650 transform = JPGFORM_ROT_270;
655 // Try to keep loading the file, but let app developer know there was something fishy:
656 DALI_LOG_WARNING( "Incorrect/Unknown Orientation setting found in EXIF header of JPEG image (%x). Orientation setting will be ignored.\n", entry );
664 bool TransformSize( int requiredWidth, int requiredHeight,
665 FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
666 JPGFORM_CODE transform,
667 int& preXformImageWidth, int& preXformImageHeight,
668 int& postXformImageWidth, int& postXformImageHeight )
672 if( transform == JPGFORM_ROT_90 || transform == JPGFORM_ROT_270 )
674 std::swap( requiredWidth, requiredHeight );
675 std::swap( postXformImageWidth, postXformImageHeight );
678 // Apply the special rules for when there are one or two zeros in requested dimensions:
679 const ImageDimensions correctedDesired = Internal::Platform::CalculateDesiredDimensions( ImageDimensions( postXformImageWidth, postXformImageHeight), ImageDimensions( requiredWidth, requiredHeight ) );
680 requiredWidth = correctedDesired.GetWidth();
681 requiredHeight = correctedDesired.GetHeight();
683 // Rescale image during decode using one of the decoder's built-in rescaling
684 // ratios (expected to be powers of 2), keeping the final image at least as
685 // wide and high as was requested:
688 tjscalingfactor* factors = tjGetScalingFactors( &numFactors );
689 if( factors == NULL )
691 DALI_LOG_WARNING("TurboJpeg tjGetScalingFactors error!\n");
696 // Internal jpeg downscaling is the same as our BOX_X sampling modes so only
697 // apply it if the application requested one of those:
698 // (use a switch case here so this code will fail to compile if other modes are added)
699 bool downscale = true;
700 switch( samplingMode )
702 case SamplingMode::BOX:
703 case SamplingMode::BOX_THEN_NEAREST:
704 case SamplingMode::BOX_THEN_LINEAR:
705 case SamplingMode::DONT_CARE:
710 case SamplingMode::NO_FILTER:
711 case SamplingMode::NEAREST:
712 case SamplingMode::LINEAR:
719 int scaleFactorIndex( 0 );
722 // Find nearest supported scaling factor (factors are in sequential order, getting smaller)
723 for( int i = 1; i < numFactors; ++i )
725 bool widthLessRequired = TJSCALED( postXformImageWidth, factors[i]) < requiredWidth;
726 bool heightLessRequired = TJSCALED( postXformImageHeight, factors[i]) < requiredHeight;
727 // If either scaled dimension is smaller than the desired one, we were done at the last iteration
728 if ( (fittingMode == FittingMode::SCALE_TO_FILL) && (widthLessRequired || heightLessRequired) )
732 // If both dimensions are smaller than the desired one, we were done at the last iteration:
733 if ( (fittingMode == FittingMode::SHRINK_TO_FIT) && ( widthLessRequired && heightLessRequired ) )
737 // If the width is smaller than the desired one, we were done at the last iteration:
738 if ( fittingMode == FittingMode::FIT_WIDTH && widthLessRequired )
742 // If the width is smaller than the desired one, we were done at the last iteration:
743 if ( fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired )
747 // This factor stays is within our fitting mode constraint so remember it:
748 scaleFactorIndex = i;
752 // Regardless of requested size, downscale to avoid exceeding the maximum texture size:
753 for( int i = scaleFactorIndex; i < numFactors; ++i )
755 // Continue downscaling to below maximum texture size (if possible)
756 scaleFactorIndex = i;
758 if( TJSCALED(postXformImageWidth, (factors[i])) < MAX_TEXTURE_WIDTH &&
759 TJSCALED(postXformImageHeight, (factors[i])) < MAX_TEXTURE_HEIGHT )
761 // Current scale-factor downscales to below maximum texture size
766 // We have finally chosen the scale-factor, return width/height values
767 if( scaleFactorIndex > 0 )
769 preXformImageWidth = TJSCALED(preXformImageWidth, (factors[scaleFactorIndex]));
770 preXformImageHeight = TJSCALED(preXformImageHeight, (factors[scaleFactorIndex]));
771 postXformImageWidth = TJSCALED(postXformImageWidth, (factors[scaleFactorIndex]));
772 postXformImageHeight = TJSCALED(postXformImageHeight, (factors[scaleFactorIndex]));
779 ExifData* LoadExifData( FILE* fp )
781 ExifData* exifData=NULL;
782 ExifLoader* exifLoader;
783 unsigned char dataBuffer[1024];
785 if( fseek( fp, 0, SEEK_SET ) )
787 DALI_LOG_ERROR("Error seeking to start of file\n");
791 exifLoader = exif_loader_new ();
795 int size = fread( dataBuffer, 1, sizeof( dataBuffer ), fp );
800 if( ! exif_loader_write( exifLoader, dataBuffer, size ) )
806 exifData = exif_loader_get_data( exifLoader );
807 exif_loader_unref( exifLoader );
813 bool LoadJpegHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
815 unsigned int requiredWidth = input.scalingParameters.dimensions.GetWidth();
816 unsigned int requiredHeight = input.scalingParameters.dimensions.GetHeight();
817 FILE* const fp = input.file;
819 bool success = false;
820 if( requiredWidth == 0 && requiredHeight == 0 )
822 success = LoadJpegHeader( fp, width, height );
826 // Double check we get the same width/height from the header
827 unsigned int headerWidth;
828 unsigned int headerHeight;
829 if( LoadJpegHeader( fp, headerWidth, headerHeight ) )
831 JPGFORM_CODE transform = JPGFORM_NONE;
833 if( input.reorientationRequested )
835 ExifAutoPtr exifData( LoadExifData( fp ) );
838 transform = ConvertExifOrientation(exifData.mData);
841 int preXformImageWidth = headerWidth;
842 int preXformImageHeight = headerHeight;
843 int postXformImageWidth = headerWidth;
844 int postXformImageHeight = headerHeight;
846 success = TransformSize( requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight );
849 width = postXformImageWidth;
850 height = postXformImageHeight;
857 height = headerHeight;
865 } // namespace TizenPlatform