2 * Copyright (c) 2017 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 <dali/internal/imaging/common/loader-jpeg.h>
26 #include <libexif/exif-data.h>
27 #include <libexif/exif-loader.h>
28 #include <libexif/exif-tag.h>
29 #include <turbojpeg.h>
34 #include <dali/public-api/object/property-map.h>
35 #include <dali/public-api/object/property-array.h>
36 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
40 #include <dali/internal/legacy/tizen/platform-capabilities.h>
41 #include <dali/internal/imaging/common/image-operations.h>
42 #include <dali/devel-api/adaptor-framework/image-loading.h>
43 #include <dali/internal/imaging/common/pixel-buffer-impl.h>
45 #include <dali/internal/system/common/file-closer.h>
47 using namespace Dali::Internal::Platform;
52 namespace Pixel = Dali::Pixel;
53 using PixelArray = unsigned char*;
54 const unsigned int DECODED_L8 = 1;
55 const unsigned int DECODED_RGB888 = 3;
56 const unsigned int DECODED_RGBA8888 = 4;
58 /** Transformations that can be applied to decoded pixels to respect exif orientation
59 * codes in image headers */
60 enum class JpegTransform
62 NONE, //< no transformation 0th-Row = top & 0th-Column = left
63 FLIP_HORIZONTAL, //< horizontal flip 0th-Row = top & 0th-Column = right
64 FLIP_VERTICAL, //< vertical flip 0th-Row = bottom & 0th-Column = right
65 TRANSPOSE, //< transpose across UL-to-LR axis 0th-Row = bottom & 0th-Column = left
66 TRANSVERSE, //< transpose across UR-to-LL axis 0th-Row = left & 0th-Column = top
67 ROTATE_90, //< 90-degree clockwise rotation 0th-Row = right & 0th-Column = top
68 ROTATE_180, //< 180-degree rotation 0th-Row = right & 0th-Column = bottom
69 ROTATE_270, //< 270-degree clockwise (or 90 ccw) 0th-Row = left & 0th-Column = bottom
73 * @brief Error handling bookeeping for the JPEG Turbo library's
74 * setjmp/longjmp simulated exceptions.
78 struct jpeg_error_mgr errorManager;
83 * @brief Called by the JPEG library when it hits an error.
84 * We jump out of the library so our loader code can return an error.
86 void JpegErrorHandler ( j_common_ptr cinfo )
88 DALI_LOG_ERROR( "JpegErrorHandler(): libjpeg-turbo fatal error in JPEG decoding.\n" );
89 /* cinfo->err really points to a JpegErrorState struct, so coerce pointer */
90 JpegErrorState * myerr = reinterpret_cast<JpegErrorState *>( cinfo->err );
92 /* Return control to the setjmp point */
93 longjmp( myerr->jumpBuffer, 1 );
96 void JpegOutputMessageHandler( j_common_ptr cinfo )
98 /* Stop libjpeg from printing to stderr - Do Nothing */
102 * LibJPEG Turbo tjDecompress2 API doesn't distinguish between errors that still allow
103 * the JPEG to be displayed and fatal errors.
105 bool IsJpegErrorFatal( const std::string& errorMessage )
107 if( ( errorMessage.find("Corrupt JPEG data") != std::string::npos ) ||
108 ( errorMessage.find("Invalid SOS parameters") != std::string::npos ) ||
109 ( errorMessage.find("Invalid JPEG file structure") != std::string::npos ) ||
110 ( errorMessage.find("Unsupported JPEG process") != std::string::npos ) ||
111 ( errorMessage.find("Unsupported marker type") != std::string::npos ) ||
112 ( errorMessage.find("Bogus marker length") != std::string::npos ) ||
113 ( errorMessage.find("Bogus DQT index") != std::string::npos ) ||
114 ( errorMessage.find("Bogus Huffman table definition") != std::string::npos ))
121 // helpers for safe exif memory handling
122 using ExifHandle = std::unique_ptr<ExifData, decltype(exif_data_free)*>;
124 ExifHandle MakeNullExifData()
126 return ExifHandle{nullptr, exif_data_free};
129 ExifHandle MakeExifDataFromData(unsigned char* data, unsigned int size)
131 return ExifHandle{exif_data_new_from_data(data, size), exif_data_free};
134 // Helpers for safe Jpeg memory handling
135 using JpegHandle = std::unique_ptr<void /*tjhandle*/, decltype(tjDestroy)*>;
137 JpegHandle MakeJpegCompressor()
139 return JpegHandle{tjInitCompress(), tjDestroy};
142 JpegHandle MakeJpegDecompressor()
144 return JpegHandle{tjInitDecompress(), tjDestroy};
147 using JpegMemoryHandle = std::unique_ptr<unsigned char, decltype(tjFree)*>;
149 JpegMemoryHandle MakeJpegMemory()
151 return JpegMemoryHandle{nullptr, tjFree};
154 template<class T, class Deleter>
155 class UniquePointerSetter final
158 UniquePointerSetter(std::unique_ptr<T, Deleter>& uniquePointer)
159 : mUniquePointer(uniquePointer),
163 /// @brief Pointer to Pointer cast operator
164 operator T** () { return &mRawPointer; }
166 /// @brief Destructor, reset the unique_ptr
167 ~UniquePointerSetter() { mUniquePointer.reset(mRawPointer); }
170 std::unique_ptr<T, Deleter>& mUniquePointer;
174 template<typename T, typename Deleter>
175 UniquePointerSetter<T, Deleter> SetPointer(std::unique_ptr<T, Deleter>& uniquePointer)
177 return UniquePointerSetter<T, Deleter>{uniquePointer};
180 using TransformFunction = std::function<void(PixelArray,unsigned, unsigned)>;
181 using TransformFunctionArray = std::array<TransformFunction, 3>; // 1, 3 and 4 bytes per pixel
183 /// @brief Select the transform function depending on the pixel format
184 TransformFunction GetTransformFunction(const TransformFunctionArray& functions,
185 Pixel::Format pixelFormat)
187 auto function = TransformFunction{};
189 int decodedPixelSize = Pixel::GetBytesPerPixel(pixelFormat);
190 switch( decodedPixelSize )
194 function = functions[0];
199 function = functions[1];
202 case DECODED_RGBA8888:
204 function = functions[2];
209 DALI_LOG_ERROR("Transform operation not supported on this Pixel::Format!");
210 function = functions[1];
217 // Storing Exif fields as properties
218 template<class R, class V>
219 R ConvertExifNumeric( const ExifEntry& entry )
221 return static_cast<R>((*reinterpret_cast<V*>(entry.data)));
224 void AddExifFieldPropertyMap( Dali::Property::Map& out, const ExifEntry& entry, ExifIfd ifd )
226 auto shortName = std::string(exif_tag_get_name_in_ifd(entry.tag, ifd ));
227 switch( entry.format )
229 case EXIF_FORMAT_ASCII:
231 out.Insert( shortName, std::string(reinterpret_cast<char *>(entry.data)) );
234 case EXIF_FORMAT_SHORT:
236 out.Insert( shortName, ConvertExifNumeric<int, unsigned int>(entry) );
239 case EXIF_FORMAT_LONG:
241 out.Insert( shortName, ConvertExifNumeric<int, unsigned long>(entry) );
244 case EXIF_FORMAT_SSHORT:
246 out.Insert( shortName, ConvertExifNumeric<int, int>(entry) );
249 case EXIF_FORMAT_SLONG:
251 out.Insert( shortName, ConvertExifNumeric<int, long>(entry) );
254 case EXIF_FORMAT_FLOAT:
256 out.Insert (shortName, ConvertExifNumeric<float, float>(entry) );
259 case EXIF_FORMAT_DOUBLE:
261 out.Insert( shortName, ConvertExifNumeric<float, double>(entry) );
264 case EXIF_FORMAT_RATIONAL:
266 auto values = reinterpret_cast<unsigned int*>( entry.data );
267 Dali::Property::Array array;
268 array.Add( static_cast<int>(values[0]) );
269 array.Add( static_cast<int>(values[1]) );
270 out.Insert(shortName, array);
273 case EXIF_FORMAT_SBYTE:
275 out.Insert(shortName, "EXIF_FORMAT_SBYTE Unsupported");
278 case EXIF_FORMAT_BYTE:
280 out.Insert(shortName, "EXIF_FORMAT_BYTE Unsupported");
283 case EXIF_FORMAT_SRATIONAL:
285 auto values = reinterpret_cast<int*>( entry.data );
286 Dali::Property::Array array;
287 array.Add(values[0]);
288 array.Add(values[1]);
289 out.Insert(shortName, array);
292 case EXIF_FORMAT_UNDEFINED:
295 std::stringstream ss;
296 ss << "EXIF_FORMAT_UNDEFINED, size: " << entry.size << ", components: " << entry.components;
297 out.Insert( shortName, ss.str());
302 /// @brief Apply a transform to a buffer
303 bool Transform(const TransformFunctionArray& transformFunctions,
307 Pixel::Format pixelFormat )
309 auto transformFunction = GetTransformFunction(transformFunctions, pixelFormat);
310 if(transformFunction)
312 transformFunction(buffer, width, height);
314 return bool(transformFunction);
317 /// @brief Auxiliar type to represent pixel data with different number of bytes
325 void FlipVertical(PixelArray buffer, int width, int height)
327 // Destination pixel, set as the first pixel of screen
328 auto to = reinterpret_cast<PixelType<N>*>( buffer );
330 // Source pixel, as the image is flipped horizontally and vertically,
331 // the source pixel is the end of the buffer of size width * height
332 auto from = reinterpret_cast<PixelType<N>*>(buffer) + width * height - 1;
334 for (auto ix = 0, endLoop = (width * height) / 2; ix < endLoop; ++ix, ++to, --from)
336 std::swap(*from, *to);
341 void FlipHorizontal(PixelArray buffer, int width, int height)
343 for(auto iy = 0; iy < height; ++iy)
345 //Set the destination pixel as the beginning of the row
346 auto to = reinterpret_cast<PixelType<N>*>(buffer) + width * iy;
347 //Set the source pixel as the end of the row to flip in X axis
348 auto from = reinterpret_cast<PixelType<N>*>(buffer) + width * (iy + 1) - 1;
349 for(auto ix = 0; ix < width / 2; ++ix, ++to, --from)
351 std::swap(*from, *to);
357 void Transpose(PixelArray buffer, int width, int height)
359 //Transform vertically only
360 for(auto iy = 0; iy < height / 2; ++iy)
362 for(auto ix = 0; ix < width; ++ix)
364 auto to = reinterpret_cast<PixelType<N>*>(buffer) + iy * width + ix;
365 auto from = reinterpret_cast<PixelType<N>*>(buffer) + (height - 1 - iy) * width + ix;
366 std::swap(*from, *to);
372 void Transverse(PixelArray buffer, int width, int height)
374 using PixelT = PixelType<N>;
376 data.Resize( width * height );
377 auto dataPtr = data.Begin();
379 auto original = reinterpret_cast<PixelT*>(buffer);
380 std::copy(original, original + width * height, dataPtr);
383 for( auto iy = 0; iy < width; ++iy )
385 for( auto ix = 0; ix < height; ++ix, ++to )
387 auto from = dataPtr + ix * width + iy;
395 void Rotate90(PixelArray buffer, int width, int height)
397 using PixelT = PixelType<N>;
399 data.Resize(width * height);
400 auto dataPtr = data.Begin();
402 auto original = reinterpret_cast<PixelT*>(buffer);
403 std::copy(original, original + width * height, dataPtr);
405 std::swap(width, height);
406 auto hw = width * height;
409 auto to = original + width - 1;
412 for(auto ix = width; --ix >= 0;)
414 for(auto iy = height; --iy >= 0; ++from)
424 void Rotate180(PixelArray buffer, int width, int height)
426 using PixelT = PixelType<N>;
428 data.Resize(width * height);
429 auto dataPtr = data.Begin();
431 auto original = reinterpret_cast<PixelT*>(buffer);
432 std::copy(original, original + width * height, dataPtr);
435 for( auto iy = 0; iy < width; iy++ )
437 for( auto ix = 0; ix < height; ix++ )
439 auto from = dataPtr + (height - ix) * width - 1 - iy;
448 void Rotate270(PixelArray buffer, int width, int height)
450 using PixelT = PixelType<N>;
452 data.Resize(width * height);
453 auto dataPtr = data.Begin();
455 auto original = reinterpret_cast<PixelT*>(buffer);
456 std::copy(original, original + width * height, dataPtr);
459 std::swap(width, height);
460 auto hw = width * height;
462 auto* to = original + hw - width;
463 auto* from = dataPtr;
467 for(auto ix = width; --ix >= 0;)
469 for(auto iy = height; --iy >= 0;)
484 namespace TizenPlatform
487 JpegTransform ConvertExifOrientation(ExifData* exifData);
488 bool TransformSize( int requiredWidth, int requiredHeight,
489 FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
490 JpegTransform transform,
491 int& preXformImageWidth, int& preXformImageHeight,
492 int& postXformImageWidth, int& postXformImageHeight );
494 bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height )
496 // using libjpeg API to avoid having to read the whole file in a buffer
497 struct jpeg_decompress_struct cinfo;
498 struct JpegErrorState jerr;
499 cinfo.err = jpeg_std_error( &jerr.errorManager );
501 jerr.errorManager.output_message = JpegOutputMessageHandler;
502 jerr.errorManager.error_exit = JpegErrorHandler;
504 // On error exit from the JPEG lib, control will pass via JpegErrorHandler
505 // into this branch body for cleanup and error return:
506 if(setjmp(jerr.jumpBuffer))
508 jpeg_destroy_decompress(&cinfo);
512 // jpeg_create_decompress internally uses C casts
513 #pragma GCC diagnostic push
514 #pragma GCC diagnostic ignored "-Wold-style-cast"
515 jpeg_create_decompress( &cinfo );
516 #pragma GCC diagnostic pop
518 jpeg_stdio_src( &cinfo, fp );
520 // Check header to see if it is JPEG file
521 if( jpeg_read_header( &cinfo, TRUE ) != JPEG_HEADER_OK )
524 jpeg_destroy_decompress( &cinfo );
528 width = cinfo.image_width;
529 height = cinfo.image_height;
531 jpeg_destroy_decompress( &cinfo );
535 bool LoadBitmapFromJpeg( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
538 FILE* const fp = input.file;
540 if( InternalFile::fseek(fp,0,SEEK_END) )
542 DALI_LOG_ERROR("Error seeking to end of file\n");
546 long positionIndicator = InternalFile::ftell(fp);
547 unsigned int jpegBufferSize = 0u;
548 if( positionIndicator > -1L )
550 jpegBufferSize = static_cast<unsigned int>(positionIndicator);
553 if( 0u == jpegBufferSize )
558 if( InternalFile::fseek(fp, 0, SEEK_SET) )
560 DALI_LOG_ERROR("Error seeking to start of file\n");
564 Vector<unsigned char> jpegBuffer;
567 jpegBuffer.Resize( jpegBufferSize );
571 DALI_LOG_ERROR( "Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U );
574 unsigned char * const jpegBufferPtr = jpegBuffer.Begin();
576 // Pull the compressed JPEG image bytes out of a file and into memory:
577 if( InternalFile::fread( jpegBufferPtr, 1, jpegBufferSize, fp ) != jpegBufferSize )
579 DALI_LOG_WARNING("Error on image file read.\n");
583 if( InternalFile::fseek(fp, 0, SEEK_SET) )
585 DALI_LOG_ERROR("Error seeking to start of file\n");
588 auto jpeg = MakeJpegDecompressor();
592 DALI_LOG_ERROR("%s\n", tjGetErrorStr());
596 auto transform = JpegTransform::NONE;
599 auto exifData = MakeExifDataFromData(jpegBufferPtr, jpegBufferSize);
601 if( exifData && input.reorientationRequested )
603 transform = ConvertExifOrientation(exifData.get());
606 std::unique_ptr<Property::Map> exifMap;
607 exifMap.reset( new Property::Map() );
609 for( auto k = 0u; k < EXIF_IFD_COUNT; ++k )
611 auto content = exifData->ifd[k];
612 for (auto i = 0u; i < content->count; ++i)
614 auto &&tag = content->entries[i];
615 const char *shortName = exif_tag_get_name_in_ifd(tag->tag, static_cast<ExifIfd>(k));
618 AddExifFieldPropertyMap(*exifMap, *tag, static_cast<ExifIfd>(k));
623 // Push jpeg data in memory buffer through TurboJPEG decoder to make a raw pixel array:
624 int chrominanceSubsampling = -1;
625 int preXformImageWidth = 0, preXformImageHeight = 0;
627 // In Ubuntu, the turbojpeg version is not correct. so build error occurs.
628 // Temporarily separate Ubuntu and other profiles.
629 #ifndef DALI_PROFILE_UBUNTU
630 int jpegColorspace = -1;
631 if( tjDecompressHeader3( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling, &jpegColorspace ) == -1 )
633 DALI_LOG_ERROR("%s\n", tjGetErrorStr());
634 // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
637 if( tjDecompressHeader2( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling ) == -1 )
639 DALI_LOG_ERROR("%s\n", tjGetErrorStr());
640 // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
644 if(preXformImageWidth == 0 || preXformImageHeight == 0)
646 DALI_LOG_WARNING("Invalid Image!\n");
650 int requiredWidth = input.scalingParameters.dimensions.GetWidth();
651 int requiredHeight = input.scalingParameters.dimensions.GetHeight();
653 // If transform is a 90 or 270 degree rotation, the logical width and height
654 // request from the client needs to be adjusted to account by effectively
655 // rotating that too, and the final width and height need to be swapped:
656 int postXformImageWidth = preXformImageWidth;
657 int postXformImageHeight = preXformImageHeight;
660 int scaledPreXformWidth = preXformImageWidth;
661 int scaledPreXformHeight = preXformImageHeight;
662 int scaledPostXformWidth = postXformImageWidth;
663 int scaledPostXformHeight = postXformImageHeight;
665 TransformSize( requiredWidth, requiredHeight,
666 input.scalingParameters.scalingMode,
667 input.scalingParameters.samplingMode,
669 scaledPreXformWidth, scaledPreXformHeight,
670 scaledPostXformWidth, scaledPostXformHeight );
673 // Colorspace conversion options
674 TJPF pixelLibJpegType = TJPF_RGB;
675 Pixel::Format pixelFormat = Pixel::RGB888;
676 #ifndef DALI_PROFILE_UBUNTU
677 switch (jpegColorspace)
680 // YCbCr is not an absolute colorspace but rather a mathematical transformation of RGB designed solely for storage and transmission.
681 // YCbCr images must be converted to RGB before they can actually be displayed.
684 pixelLibJpegType = TJPF_RGB;
685 pixelFormat = Pixel::RGB888;
690 pixelLibJpegType = TJPF_GRAY;
691 pixelFormat = Pixel::L8;
697 pixelLibJpegType = TJPF_CMYK;
698 pixelFormat = Pixel::RGBA8888;
703 pixelLibJpegType = TJPF_RGB;
704 pixelFormat = Pixel::RGB888;
709 // Allocate a bitmap and decompress the jpeg buffer into its pixel buffer:
710 bitmap = Dali::Devel::PixelBuffer::New(scaledPostXformWidth, scaledPostXformHeight, pixelFormat);
713 GetImplementation(bitmap).SetMetadata( std::move(exifMap) );
715 auto bitmapPixelBuffer = bitmap.GetBuffer();
717 if( tjDecompress2( jpeg.get(), jpegBufferPtr, jpegBufferSize, reinterpret_cast<unsigned char*>( bitmapPixelBuffer ), scaledPreXformWidth, 0, scaledPreXformHeight, pixelLibJpegType, flags ) == -1 )
719 std::string errorString = tjGetErrorStr();
721 if( IsJpegErrorFatal( errorString ) )
723 DALI_LOG_ERROR("%s\n", errorString.c_str() );
728 DALI_LOG_WARNING("%s\n", errorString.c_str() );
732 const unsigned int bufferWidth = GetTextureDimension( scaledPreXformWidth );
733 const unsigned int bufferHeight = GetTextureDimension( scaledPreXformHeight );
738 case JpegTransform::NONE:
743 // 3 orientation changes for a camera held perpendicular to the ground or upside-down:
744 case JpegTransform::ROTATE_180:
746 static auto rotate180Functions = TransformFunctionArray {
751 result = Transform(rotate180Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
754 case JpegTransform::ROTATE_270:
756 static auto rotate270Functions = TransformFunctionArray {
761 result = Transform(rotate270Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
764 case JpegTransform::ROTATE_90:
766 static auto rotate90Functions = TransformFunctionArray {
771 result = Transform(rotate90Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
774 case JpegTransform::FLIP_VERTICAL:
776 static auto flipVerticalFunctions = TransformFunctionArray {
781 result = Transform(flipVerticalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
784 // Less-common orientation changes, since they don't correspond to a camera's physical orientation:
785 case JpegTransform::FLIP_HORIZONTAL:
787 static auto flipHorizontalFunctions = TransformFunctionArray {
792 result = Transform(flipHorizontalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
795 case JpegTransform::TRANSPOSE:
797 static auto transposeFunctions = TransformFunctionArray {
802 result = Transform(transposeFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
805 case JpegTransform::TRANSVERSE:
807 static auto transverseFunctions = TransformFunctionArray {
812 result = Transform(transverseFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
817 DALI_LOG_ERROR( "Unsupported JPEG Orientation transformation: %x.\n", transform );
825 bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char >& encodedPixels,
826 const std::size_t width, const std::size_t height, const Pixel::Format pixelFormat, unsigned quality )
831 DALI_LOG_ERROR("Null input buffer\n");
835 // Translate pixel format enum:
836 int jpegPixelFormat = -1;
838 switch( pixelFormat )
842 jpegPixelFormat = TJPF_RGB;
845 case Pixel::RGBA8888:
848 jpegPixelFormat = TJPF_RGBX;
851 case Pixel::BGRA8888:
854 jpegPixelFormat = TJPF_BGRX;
859 DALI_LOG_ERROR( "Unsupported pixel format for encoding to JPEG.\n" );
864 // Assert quality is in the documented allowable range of the jpeg-turbo lib:
865 DALI_ASSERT_DEBUG( quality >= 1 );
866 DALI_ASSERT_DEBUG( quality <= 100 );
876 // Initialise a JPEG codec:
878 auto jpeg = MakeJpegCompressor();
881 DALI_LOG_ERROR( "JPEG Compressor init failed: %s\n", tjGetErrorStr() );
886 // Safely wrap the jpeg codec's buffer in case we are about to throw, then
887 // save the pixels to a persistent buffer that we own and let our cleaner
888 // class clean up the buffer as it goes out of scope:
889 auto dstBuffer = MakeJpegMemory();
891 // Run the compressor:
892 unsigned long dstBufferSize = 0;
895 if( tjCompress2( jpeg.get(),
896 const_cast<unsigned char*>(pixelBuffer),
898 jpegPixelFormat, SetPointer(dstBuffer), &dstBufferSize,
899 TJSAMP_444, quality, flags ) )
901 DALI_LOG_ERROR("JPEG Compression failed: %s\n", tjGetErrorStr());
905 encodedPixels.Resize( dstBufferSize );
906 memcpy( encodedPixels.Begin(), dstBuffer.get(), dstBufferSize );
912 JpegTransform ConvertExifOrientation(ExifData* exifData)
914 auto transform = JpegTransform::NONE;
915 ExifEntry * const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
919 orientation = exif_get_short(entry->data, exif_data_get_byte_order(entry->parent->parent));
920 switch( orientation )
924 transform = JpegTransform::NONE;
929 transform = JpegTransform::FLIP_HORIZONTAL;
934 transform = JpegTransform::FLIP_VERTICAL;
939 transform = JpegTransform::TRANSPOSE;
944 transform = JpegTransform::TRANSVERSE;
949 transform = JpegTransform::ROTATE_90;
954 transform = JpegTransform::ROTATE_180;
959 transform = JpegTransform::ROTATE_270;
964 // Try to keep loading the file, but let app developer know there was something fishy:
965 DALI_LOG_WARNING( "Incorrect/Unknown Orientation setting found in EXIF header of JPEG image (%x). Orientation setting will be ignored.\n", entry );
973 bool TransformSize( int requiredWidth, int requiredHeight,
974 FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
975 JpegTransform transform,
976 int& preXformImageWidth, int& preXformImageHeight,
977 int& postXformImageWidth, int& postXformImageHeight )
981 if( transform == JpegTransform::ROTATE_90 || transform == JpegTransform::ROTATE_270 || transform == JpegTransform::ROTATE_180 || transform == JpegTransform::TRANSVERSE)
983 std::swap( requiredWidth, requiredHeight );
984 std::swap( postXformImageWidth, postXformImageHeight );
987 // Apply the special rules for when there are one or two zeros in requested dimensions:
988 const ImageDimensions correctedDesired = Internal::Platform::CalculateDesiredDimensions( ImageDimensions( postXformImageWidth, postXformImageHeight), ImageDimensions( requiredWidth, requiredHeight ) );
989 requiredWidth = correctedDesired.GetWidth();
990 requiredHeight = correctedDesired.GetHeight();
992 // Rescale image during decode using one of the decoder's built-in rescaling
993 // ratios (expected to be powers of 2), keeping the final image at least as
994 // wide and high as was requested:
997 tjscalingfactor* factors = tjGetScalingFactors( &numFactors );
998 if( factors == NULL )
1000 DALI_LOG_WARNING("TurboJpeg tjGetScalingFactors error!\n");
1005 // Internal jpeg downscaling is the same as our BOX_X sampling modes so only
1006 // apply it if the application requested one of those:
1007 // (use a switch case here so this code will fail to compile if other modes are added)
1008 bool downscale = true;
1009 switch( samplingMode )
1011 case SamplingMode::BOX:
1012 case SamplingMode::BOX_THEN_NEAREST:
1013 case SamplingMode::BOX_THEN_LINEAR:
1014 case SamplingMode::DONT_CARE:
1019 case SamplingMode::NO_FILTER:
1020 case SamplingMode::NEAREST:
1021 case SamplingMode::LINEAR:
1028 int scaleFactorIndex( 0 );
1031 // Find nearest supported scaling factor (factors are in sequential order, getting smaller)
1032 for( int i = 1; i < numFactors; ++i )
1034 bool widthLessRequired = TJSCALED( postXformImageWidth, factors[i]) < requiredWidth;
1035 bool heightLessRequired = TJSCALED( postXformImageHeight, factors[i]) < requiredHeight;
1036 // If either scaled dimension is smaller than the desired one, we were done at the last iteration
1037 if ( (fittingMode == FittingMode::SCALE_TO_FILL) && (widthLessRequired || heightLessRequired) )
1041 // If both dimensions are smaller than the desired one, we were done at the last iteration:
1042 if ( (fittingMode == FittingMode::SHRINK_TO_FIT) && ( widthLessRequired && heightLessRequired ) )
1046 // If the width is smaller than the desired one, we were done at the last iteration:
1047 if ( fittingMode == FittingMode::FIT_WIDTH && widthLessRequired )
1051 // If the width is smaller than the desired one, we were done at the last iteration:
1052 if ( fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired )
1056 // This factor stays is within our fitting mode constraint so remember it:
1057 scaleFactorIndex = i;
1061 // Regardless of requested size, downscale to avoid exceeding the maximum texture size:
1062 for( int i = scaleFactorIndex; i < numFactors; ++i )
1064 // Continue downscaling to below maximum texture size (if possible)
1065 scaleFactorIndex = i;
1067 if( TJSCALED(postXformImageWidth, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) &&
1068 TJSCALED(postXformImageHeight, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) )
1070 // Current scale-factor downscales to below maximum texture size
1075 // We have finally chosen the scale-factor, return width/height values
1076 if( scaleFactorIndex > 0 )
1078 preXformImageWidth = TJSCALED(preXformImageWidth, (factors[scaleFactorIndex]));
1079 preXformImageHeight = TJSCALED(preXformImageHeight, (factors[scaleFactorIndex]));
1080 postXformImageWidth = TJSCALED(postXformImageWidth, (factors[scaleFactorIndex]));
1081 postXformImageHeight = TJSCALED(postXformImageHeight, (factors[scaleFactorIndex]));
1088 ExifHandle LoadExifData( FILE* fp )
1090 auto exifData = MakeNullExifData();
1091 unsigned char dataBuffer[1024];
1093 if( InternalFile::fseek( fp, 0, SEEK_SET ) )
1095 DALI_LOG_ERROR("Error seeking to start of file\n");
1099 auto exifLoader = std::unique_ptr<ExifLoader, decltype(exif_loader_unref)*>{
1100 exif_loader_new(), exif_loader_unref };
1102 while( !InternalFile::feof(fp) )
1104 int size = InternalFile::fread( dataBuffer, 1, sizeof( dataBuffer ), fp );
1109 if( ! exif_loader_write( exifLoader.get(), dataBuffer, size ) )
1115 exifData.reset( exif_loader_get_data( exifLoader.get() ) );
1121 bool LoadJpegHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
1123 unsigned int requiredWidth = input.scalingParameters.dimensions.GetWidth();
1124 unsigned int requiredHeight = input.scalingParameters.dimensions.GetHeight();
1125 FILE* const fp = input.file;
1127 bool success = false;
1128 if( requiredWidth == 0 && requiredHeight == 0 )
1130 success = LoadJpegHeader( fp, width, height );
1134 // Double check we get the same width/height from the header
1135 unsigned int headerWidth;
1136 unsigned int headerHeight;
1137 if( LoadJpegHeader( fp, headerWidth, headerHeight ) )
1139 auto transform = JpegTransform::NONE;
1141 if( input.reorientationRequested )
1143 auto exifData = LoadExifData( fp );
1146 transform = ConvertExifOrientation(exifData.get());
1149 int preXformImageWidth = headerWidth;
1150 int preXformImageHeight = headerHeight;
1151 int postXformImageWidth = headerWidth;
1152 int postXformImageHeight = headerHeight;
1154 success = TransformSize( requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight );
1157 width = postXformImageWidth;
1158 height = postXformImageHeight;
1164 width = headerWidth;
1165 height = headerHeight;
1173 } // namespace TizenPlatform