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>
48 namespace Pixel = Dali::Pixel;
49 using PixelArray = unsigned char*;
50 const unsigned int DECODED_L8 = 1;
51 const unsigned int DECODED_RGB888 = 3;
52 const unsigned int DECODED_RGBA8888 = 4;
54 /** Transformations that can be applied to decoded pixels to respect exif orientation
55 * codes in image headers */
56 enum class JpegTransform
58 NONE, //< no transformation 0th-Row = top & 0th-Column = left
59 FLIP_HORIZONTAL, //< horizontal flip 0th-Row = top & 0th-Column = right
60 FLIP_VERTICAL, //< vertical flip 0th-Row = bottom & 0th-Column = right
61 TRANSPOSE, //< transpose across UL-to-LR axis 0th-Row = bottom & 0th-Column = left
62 TRANSVERSE, //< transpose across UR-to-LL axis 0th-Row = left & 0th-Column = top
63 ROTATE_90, //< 90-degree clockwise rotation 0th-Row = right & 0th-Column = top
64 ROTATE_180, //< 180-degree rotation 0th-Row = right & 0th-Column = bottom
65 ROTATE_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.
74 struct jpeg_error_mgr errorManager;
79 * @brief Called by the JPEG library when it hits an error.
80 * We jump out of the library so our loader code can return an error.
82 void JpegErrorHandler ( j_common_ptr cinfo )
84 DALI_LOG_ERROR( "JpegErrorHandler(): libjpeg-turbo fatal error in JPEG decoding.\n" );
85 /* cinfo->err really points to a JpegErrorState struct, so coerce pointer */
86 JpegErrorState * myerr = reinterpret_cast<JpegErrorState *>( cinfo->err );
88 /* Return control to the setjmp point */
89 longjmp( myerr->jumpBuffer, 1 );
92 void JpegOutputMessageHandler( j_common_ptr cinfo )
94 /* Stop libjpeg from printing to stderr - Do Nothing */
98 * LibJPEG Turbo tjDecompress2 API doesn't distinguish between errors that still allow
99 * the JPEG to be displayed and fatal errors.
101 bool IsJpegErrorFatal( const std::string& errorMessage )
103 if( ( errorMessage.find("Corrupt JPEG data") != std::string::npos ) ||
104 ( errorMessage.find("Invalid SOS parameters") != std::string::npos ) ||
105 ( errorMessage.find("Invalid JPEG file structure") != std::string::npos ) ||
106 ( errorMessage.find("Unsupported JPEG process") != std::string::npos ) ||
107 ( errorMessage.find("Unsupported marker type") != std::string::npos ) ||
108 ( errorMessage.find("Bogus marker length") != std::string::npos ) ||
109 ( errorMessage.find("Bogus DQT index") != std::string::npos ) ||
110 ( errorMessage.find("Bogus Huffman table definition") != std::string::npos ))
117 // helpers for safe exif memory handling
118 using ExifHandle = std::unique_ptr<ExifData, decltype(exif_data_free)*>;
120 ExifHandle MakeNullExifData()
122 return ExifHandle{nullptr, exif_data_free};
125 ExifHandle MakeExifDataFromData(unsigned char* data, unsigned int size)
127 return ExifHandle{exif_data_new_from_data(data, size), exif_data_free};
130 // Helpers for safe Jpeg memory handling
131 using JpegHandle = std::unique_ptr<void /*tjhandle*/, decltype(tjDestroy)*>;
133 JpegHandle MakeJpegCompressor()
135 return JpegHandle{tjInitCompress(), tjDestroy};
138 JpegHandle MakeJpegDecompressor()
140 return JpegHandle{tjInitDecompress(), tjDestroy};
143 using JpegMemoryHandle = std::unique_ptr<unsigned char, decltype(tjFree)*>;
145 JpegMemoryHandle MakeJpegMemory()
147 return JpegMemoryHandle{nullptr, tjFree};
150 template<class T, class Deleter>
151 class UniquePointerSetter final
154 UniquePointerSetter(std::unique_ptr<T, Deleter>& uniquePointer)
155 : mUniquePointer(uniquePointer),
159 /// @brief Pointer to Pointer cast operator
160 operator T** () { return &mRawPointer; }
162 /// @brief Destructor, reset the unique_ptr
163 ~UniquePointerSetter() { mUniquePointer.reset(mRawPointer); }
166 std::unique_ptr<T, Deleter>& mUniquePointer;
170 template<typename T, typename Deleter>
171 UniquePointerSetter<T, Deleter> SetPointer(std::unique_ptr<T, Deleter>& uniquePointer)
173 return UniquePointerSetter<T, Deleter>{uniquePointer};
176 using TransformFunction = std::function<void(PixelArray,unsigned, unsigned)>;
177 using TransformFunctionArray = std::array<TransformFunction, 3>; // 1, 3 and 4 bytes per pixel
179 /// @brief Select the transform function depending on the pixel format
180 TransformFunction GetTransformFunction(const TransformFunctionArray& functions,
181 Pixel::Format pixelFormat)
183 auto function = TransformFunction{};
185 int decodedPixelSize = Pixel::GetBytesPerPixel(pixelFormat);
186 switch( decodedPixelSize )
190 function = functions[0];
195 function = functions[1];
198 case DECODED_RGBA8888:
200 function = functions[2];
205 DALI_LOG_ERROR("Transform operation not supported on this Pixel::Format!");
206 function = functions[1];
213 // Storing Exif fields as properties
214 template<class R, class V>
215 R ConvertExifNumeric( const ExifEntry& entry )
217 return static_cast<R>((*reinterpret_cast<V*>(entry.data)));
220 void AddExifFieldPropertyMap( Dali::Property::Map& out, const ExifEntry& entry, ExifIfd ifd )
222 auto shortName = std::string(exif_tag_get_name_in_ifd(entry.tag, ifd ));
223 switch( entry.format )
225 case EXIF_FORMAT_ASCII:
227 out.Insert( shortName, std::string( reinterpret_cast<char *>(entry.data), entry.size ) );
230 case EXIF_FORMAT_SHORT:
232 out.Insert( shortName, ConvertExifNumeric<int, unsigned short>(entry) );
235 case EXIF_FORMAT_LONG:
237 out.Insert( shortName, ConvertExifNumeric<int, unsigned long>(entry) );
240 case EXIF_FORMAT_SSHORT:
242 out.Insert( shortName, ConvertExifNumeric<int, short>(entry) );
245 case EXIF_FORMAT_SLONG:
247 out.Insert( shortName, ConvertExifNumeric<int, long>(entry) );
250 case EXIF_FORMAT_FLOAT:
252 out.Insert (shortName, ConvertExifNumeric<float, float>(entry) );
255 case EXIF_FORMAT_DOUBLE:
257 out.Insert( shortName, ConvertExifNumeric<float, double>(entry) );
260 case EXIF_FORMAT_RATIONAL:
262 auto values = reinterpret_cast<unsigned int*>( entry.data );
263 Dali::Property::Array array;
264 array.Add( static_cast<int>(values[0]) );
265 array.Add( static_cast<int>(values[1]) );
266 out.Insert(shortName, array);
269 case EXIF_FORMAT_SBYTE:
271 out.Insert(shortName, "EXIF_FORMAT_SBYTE Unsupported");
274 case EXIF_FORMAT_BYTE:
276 out.Insert(shortName, "EXIF_FORMAT_BYTE Unsupported");
279 case EXIF_FORMAT_SRATIONAL:
281 auto values = reinterpret_cast<int*>( entry.data );
282 Dali::Property::Array array;
283 array.Add(values[0]);
284 array.Add(values[1]);
285 out.Insert(shortName, array);
288 case EXIF_FORMAT_UNDEFINED:
291 std::stringstream ss;
292 ss << "EXIF_FORMAT_UNDEFINED, size: " << entry.size << ", components: " << entry.components;
293 out.Insert( shortName, ss.str());
298 /// @brief Apply a transform to a buffer
299 bool Transform(const TransformFunctionArray& transformFunctions,
303 Pixel::Format pixelFormat )
305 auto transformFunction = GetTransformFunction(transformFunctions, pixelFormat);
306 if(transformFunction)
308 transformFunction(buffer, width, height);
310 return bool(transformFunction);
313 /// @brief Auxiliar type to represent pixel data with different number of bytes
321 void FlipVertical(PixelArray buffer, int width, int height)
323 // Destination pixel, set as the first pixel of screen
324 auto to = reinterpret_cast<PixelType<N>*>( buffer );
326 // Source pixel, as the image is flipped horizontally and vertically,
327 // the source pixel is the end of the buffer of size width * height
328 auto from = reinterpret_cast<PixelType<N>*>(buffer) + width * height - 1;
330 for (auto ix = 0, endLoop = (width * height) / 2; ix < endLoop; ++ix, ++to, --from)
332 std::swap(*from, *to);
337 void FlipHorizontal(PixelArray buffer, int width, int height)
339 for(auto iy = 0; iy < height; ++iy)
341 //Set the destination pixel as the beginning of the row
342 auto to = reinterpret_cast<PixelType<N>*>(buffer) + width * iy;
343 //Set the source pixel as the end of the row to flip in X axis
344 auto from = reinterpret_cast<PixelType<N>*>(buffer) + width * (iy + 1) - 1;
345 for(auto ix = 0; ix < width / 2; ++ix, ++to, --from)
347 std::swap(*from, *to);
353 void Transpose(PixelArray buffer, int width, int height)
355 //Transform vertically only
356 for(auto iy = 0; iy < height / 2; ++iy)
358 for(auto ix = 0; ix < width; ++ix)
360 auto to = reinterpret_cast<PixelType<N>*>(buffer) + iy * width + ix;
361 auto from = reinterpret_cast<PixelType<N>*>(buffer) + (height - 1 - iy) * width + ix;
362 std::swap(*from, *to);
368 void Transverse(PixelArray buffer, int width, int height)
370 using PixelT = PixelType<N>;
372 data.Resize( width * height );
373 auto dataPtr = data.Begin();
375 auto original = reinterpret_cast<PixelT*>(buffer);
376 std::copy(original, original + width * height, dataPtr);
379 for( auto iy = 0; iy < width; ++iy )
381 for( auto ix = 0; ix < height; ++ix, ++to )
383 auto from = dataPtr + ix * width + iy;
391 void Rotate90(PixelArray buffer, int width, int height)
393 using PixelT = PixelType<N>;
395 data.Resize(width * height);
396 auto dataPtr = data.Begin();
398 auto original = reinterpret_cast<PixelT*>(buffer);
399 std::copy(original, original + width * height, dataPtr);
401 std::swap(width, height);
402 auto hw = width * height;
405 auto to = original + width - 1;
408 for(auto ix = width; --ix >= 0;)
410 for(auto iy = height; --iy >= 0; ++from)
420 void Rotate180(PixelArray buffer, int width, int height)
422 using PixelT = PixelType<N>;
424 data.Resize(width * height);
425 auto dataPtr = data.Begin();
427 auto original = reinterpret_cast<PixelT*>(buffer);
428 std::copy(original, original + width * height, dataPtr);
431 for( auto iy = 0; iy < width; iy++ )
433 for( auto ix = 0; ix < height; ix++ )
435 auto from = dataPtr + (height - ix) * width - 1 - iy;
444 void Rotate270(PixelArray buffer, int width, int height)
446 using PixelT = PixelType<N>;
448 data.Resize(width * height);
449 auto dataPtr = data.Begin();
451 auto original = reinterpret_cast<PixelT*>(buffer);
452 std::copy(original, original + width * height, dataPtr);
455 std::swap(width, height);
456 auto hw = width * height;
458 auto* to = original + hw - width;
459 auto* from = dataPtr;
463 for(auto ix = width; --ix >= 0;)
465 for(auto iy = height; --iy >= 0;)
480 namespace TizenPlatform
483 JpegTransform ConvertExifOrientation(ExifData* exifData);
484 bool TransformSize( int requiredWidth, int requiredHeight,
485 FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
486 JpegTransform transform,
487 int& preXformImageWidth, int& preXformImageHeight,
488 int& postXformImageWidth, int& postXformImageHeight );
490 bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height )
492 // using libjpeg API to avoid having to read the whole file in a buffer
493 struct jpeg_decompress_struct cinfo;
494 struct JpegErrorState jerr;
495 cinfo.err = jpeg_std_error( &jerr.errorManager );
497 jerr.errorManager.output_message = JpegOutputMessageHandler;
498 jerr.errorManager.error_exit = JpegErrorHandler;
500 // On error exit from the JPEG lib, control will pass via JpegErrorHandler
501 // into this branch body for cleanup and error return:
502 if(setjmp(jerr.jumpBuffer))
504 jpeg_destroy_decompress(&cinfo);
508 // jpeg_create_decompress internally uses C casts
509 #pragma GCC diagnostic push
510 #pragma GCC diagnostic ignored "-Wold-style-cast"
511 jpeg_create_decompress( &cinfo );
512 #pragma GCC diagnostic pop
514 jpeg_stdio_src( &cinfo, fp );
516 // Check header to see if it is JPEG file
517 if( jpeg_read_header( &cinfo, TRUE ) != JPEG_HEADER_OK )
520 jpeg_destroy_decompress( &cinfo );
524 width = cinfo.image_width;
525 height = cinfo.image_height;
527 jpeg_destroy_decompress( &cinfo );
531 bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
534 FILE* const fp = input.file;
536 if( fseek(fp,0,SEEK_END) )
538 DALI_LOG_ERROR("Error seeking to end of file\n");
542 long positionIndicator = ftell(fp);
543 unsigned int jpegBufferSize = 0u;
544 if( positionIndicator > -1L )
546 jpegBufferSize = static_cast<unsigned int>(positionIndicator);
549 if( 0u == jpegBufferSize )
554 if( fseek(fp, 0, SEEK_SET) )
556 DALI_LOG_ERROR("Error seeking to start of file\n");
560 Vector<unsigned char> jpegBuffer;
563 jpegBuffer.Resize( jpegBufferSize );
567 DALI_LOG_ERROR( "Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U );
570 unsigned char * const jpegBufferPtr = jpegBuffer.Begin();
572 // Pull the compressed JPEG image bytes out of a file and into memory:
573 if( fread( jpegBufferPtr, 1, jpegBufferSize, fp ) != jpegBufferSize )
575 DALI_LOG_WARNING("Error on image file read.\n");
579 if( fseek(fp, 0, SEEK_SET) )
581 DALI_LOG_ERROR("Error seeking to start of file\n");
584 auto jpeg = MakeJpegDecompressor();
588 DALI_LOG_ERROR("%s\n", tjGetErrorStr());
592 auto transform = JpegTransform::NONE;
595 auto exifData = MakeExifDataFromData(jpegBufferPtr, jpegBufferSize);
597 if( exifData && input.reorientationRequested )
599 transform = ConvertExifOrientation(exifData.get());
602 std::unique_ptr<Property::Map> exifMap;
603 exifMap.reset( new Property::Map() );
605 for( auto k = 0u; k < EXIF_IFD_COUNT; ++k )
607 auto content = exifData->ifd[k];
608 for (auto i = 0u; i < content->count; ++i)
610 auto &&tag = content->entries[i];
611 const char *shortName = exif_tag_get_name_in_ifd(tag->tag, static_cast<ExifIfd>(k));
614 AddExifFieldPropertyMap(*exifMap, *tag, static_cast<ExifIfd>(k));
619 // Push jpeg data in memory buffer through TurboJPEG decoder to make a raw pixel array:
620 int chrominanceSubsampling = -1;
621 int preXformImageWidth = 0, preXformImageHeight = 0;
623 // In Ubuntu, the turbojpeg version is not correct. so build error occurs.
624 // Temporarily separate Ubuntu and other profiles.
625 #ifndef DALI_PROFILE_UBUNTU
626 int jpegColorspace = -1;
627 if( tjDecompressHeader3( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling, &jpegColorspace ) == -1 )
629 DALI_LOG_ERROR("%s\n", tjGetErrorStr());
630 // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
633 if( tjDecompressHeader2( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling ) == -1 )
635 DALI_LOG_ERROR("%s\n", tjGetErrorStr());
636 // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
640 if(preXformImageWidth == 0 || preXformImageHeight == 0)
642 DALI_LOG_WARNING("Invalid Image!\n");
646 int requiredWidth = input.scalingParameters.dimensions.GetWidth();
647 int requiredHeight = input.scalingParameters.dimensions.GetHeight();
649 // If transform is a 90 or 270 degree rotation, the logical width and height
650 // request from the client needs to be adjusted to account by effectively
651 // rotating that too, and the final width and height need to be swapped:
652 int postXformImageWidth = preXformImageWidth;
653 int postXformImageHeight = preXformImageHeight;
656 int scaledPreXformWidth = preXformImageWidth;
657 int scaledPreXformHeight = preXformImageHeight;
658 int scaledPostXformWidth = postXformImageWidth;
659 int scaledPostXformHeight = postXformImageHeight;
661 TransformSize( requiredWidth, requiredHeight,
662 input.scalingParameters.scalingMode,
663 input.scalingParameters.samplingMode,
665 scaledPreXformWidth, scaledPreXformHeight,
666 scaledPostXformWidth, scaledPostXformHeight );
669 // Colorspace conversion options
670 TJPF pixelLibJpegType = TJPF_RGB;
671 Pixel::Format pixelFormat = Pixel::RGB888;
672 #ifndef DALI_PROFILE_UBUNTU
673 switch (jpegColorspace)
676 // YCbCr is not an absolute colorspace but rather a mathematical transformation of RGB designed solely for storage and transmission.
677 // YCbCr images must be converted to RGB before they can actually be displayed.
680 pixelLibJpegType = TJPF_RGB;
681 pixelFormat = Pixel::RGB888;
686 pixelLibJpegType = TJPF_GRAY;
687 pixelFormat = Pixel::L8;
693 pixelLibJpegType = TJPF_CMYK;
694 pixelFormat = Pixel::RGBA8888;
699 pixelLibJpegType = TJPF_RGB;
700 pixelFormat = Pixel::RGB888;
705 // Allocate a bitmap and decompress the jpeg buffer into its pixel buffer:
706 bitmap = Dali::Devel::PixelBuffer::New(scaledPostXformWidth, scaledPostXformHeight, pixelFormat);
709 GetImplementation(bitmap).SetMetadata( std::move(exifMap) );
711 auto bitmapPixelBuffer = bitmap.GetBuffer();
713 if( tjDecompress2( jpeg.get(), jpegBufferPtr, jpegBufferSize, reinterpret_cast<unsigned char*>( bitmapPixelBuffer ), scaledPreXformWidth, 0, scaledPreXformHeight, pixelLibJpegType, flags ) == -1 )
715 std::string errorString = tjGetErrorStr();
717 if( IsJpegErrorFatal( errorString ) )
719 DALI_LOG_ERROR("%s\n", errorString.c_str() );
724 DALI_LOG_WARNING("%s\n", errorString.c_str() );
728 const unsigned int bufferWidth = GetTextureDimension( scaledPreXformWidth );
729 const unsigned int bufferHeight = GetTextureDimension( scaledPreXformHeight );
734 case JpegTransform::NONE:
739 // 3 orientation changes for a camera held perpendicular to the ground or upside-down:
740 case JpegTransform::ROTATE_180:
742 static auto rotate180Functions = TransformFunctionArray {
747 result = Transform(rotate180Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
750 case JpegTransform::ROTATE_270:
752 static auto rotate270Functions = TransformFunctionArray {
757 result = Transform(rotate270Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
760 case JpegTransform::ROTATE_90:
762 static auto rotate90Functions = TransformFunctionArray {
767 result = Transform(rotate90Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
770 case JpegTransform::FLIP_VERTICAL:
772 static auto flipVerticalFunctions = TransformFunctionArray {
777 result = Transform(flipVerticalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
780 // Less-common orientation changes, since they don't correspond to a camera's physical orientation:
781 case JpegTransform::FLIP_HORIZONTAL:
783 static auto flipHorizontalFunctions = TransformFunctionArray {
788 result = Transform(flipHorizontalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
791 case JpegTransform::TRANSPOSE:
793 static auto transposeFunctions = TransformFunctionArray {
798 result = Transform(transposeFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
801 case JpegTransform::TRANSVERSE:
803 static auto transverseFunctions = TransformFunctionArray {
808 result = Transform(transverseFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
813 DALI_LOG_ERROR( "Unsupported JPEG Orientation transformation: %x.\n", transform );
821 bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char >& encodedPixels,
822 const std::size_t width, const std::size_t height, const Pixel::Format pixelFormat, unsigned quality )
827 DALI_LOG_ERROR("Null input buffer\n");
831 // Translate pixel format enum:
832 int jpegPixelFormat = -1;
834 switch( pixelFormat )
838 jpegPixelFormat = TJPF_RGB;
841 case Pixel::RGBA8888:
844 jpegPixelFormat = TJPF_RGBX;
847 case Pixel::BGRA8888:
850 jpegPixelFormat = TJPF_BGRX;
855 DALI_LOG_ERROR( "Unsupported pixel format for encoding to JPEG.\n" );
860 // Assert quality is in the documented allowable range of the jpeg-turbo lib:
861 DALI_ASSERT_DEBUG( quality >= 1 );
862 DALI_ASSERT_DEBUG( quality <= 100 );
872 // Initialise a JPEG codec:
874 auto jpeg = MakeJpegCompressor();
877 DALI_LOG_ERROR( "JPEG Compressor init failed: %s\n", tjGetErrorStr() );
882 // Safely wrap the jpeg codec's buffer in case we are about to throw, then
883 // save the pixels to a persistent buffer that we own and let our cleaner
884 // class clean up the buffer as it goes out of scope:
885 auto dstBuffer = MakeJpegMemory();
887 // Run the compressor:
888 unsigned long dstBufferSize = 0;
891 if( tjCompress2( jpeg.get(),
892 const_cast<unsigned char*>(pixelBuffer),
894 jpegPixelFormat, SetPointer(dstBuffer), &dstBufferSize,
895 TJSAMP_444, quality, flags ) )
897 DALI_LOG_ERROR("JPEG Compression failed: %s\n", tjGetErrorStr());
901 encodedPixels.Resize( dstBufferSize );
902 memcpy( encodedPixels.Begin(), dstBuffer.get(), dstBufferSize );
908 JpegTransform ConvertExifOrientation(ExifData* exifData)
910 auto transform = JpegTransform::NONE;
911 ExifEntry * const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
915 orientation = exif_get_short(entry->data, exif_data_get_byte_order(entry->parent->parent));
916 switch( orientation )
920 transform = JpegTransform::NONE;
925 transform = JpegTransform::FLIP_HORIZONTAL;
930 transform = JpegTransform::FLIP_VERTICAL;
935 transform = JpegTransform::TRANSPOSE;
940 transform = JpegTransform::TRANSVERSE;
945 transform = JpegTransform::ROTATE_90;
950 transform = JpegTransform::ROTATE_180;
955 transform = JpegTransform::ROTATE_270;
960 // Try to keep loading the file, but let app developer know there was something fishy:
961 DALI_LOG_WARNING( "Incorrect/Unknown Orientation setting found in EXIF header of JPEG image (%x). Orientation setting will be ignored.\n", entry );
969 bool TransformSize( int requiredWidth, int requiredHeight,
970 FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
971 JpegTransform transform,
972 int& preXformImageWidth, int& preXformImageHeight,
973 int& postXformImageWidth, int& postXformImageHeight )
977 if( transform == JpegTransform::ROTATE_90 || transform == JpegTransform::ROTATE_270 || transform == JpegTransform::ROTATE_180 || transform == JpegTransform::TRANSVERSE)
979 std::swap( requiredWidth, requiredHeight );
980 std::swap( postXformImageWidth, postXformImageHeight );
983 // Apply the special rules for when there are one or two zeros in requested dimensions:
984 const ImageDimensions correctedDesired = Internal::Platform::CalculateDesiredDimensions( ImageDimensions( postXformImageWidth, postXformImageHeight), ImageDimensions( requiredWidth, requiredHeight ) );
985 requiredWidth = correctedDesired.GetWidth();
986 requiredHeight = correctedDesired.GetHeight();
988 // Rescale image during decode using one of the decoder's built-in rescaling
989 // ratios (expected to be powers of 2), keeping the final image at least as
990 // wide and high as was requested:
993 tjscalingfactor* factors = tjGetScalingFactors( &numFactors );
994 if( factors == NULL )
996 DALI_LOG_WARNING("TurboJpeg tjGetScalingFactors error!\n");
1001 // Internal jpeg downscaling is the same as our BOX_X sampling modes so only
1002 // apply it if the application requested one of those:
1003 // (use a switch case here so this code will fail to compile if other modes are added)
1004 bool downscale = true;
1005 switch( samplingMode )
1007 case SamplingMode::BOX:
1008 case SamplingMode::BOX_THEN_NEAREST:
1009 case SamplingMode::BOX_THEN_LINEAR:
1010 case SamplingMode::DONT_CARE:
1015 case SamplingMode::NO_FILTER:
1016 case SamplingMode::NEAREST:
1017 case SamplingMode::LINEAR:
1024 int scaleFactorIndex( 0 );
1027 // Find nearest supported scaling factor (factors are in sequential order, getting smaller)
1028 for( int i = 1; i < numFactors; ++i )
1030 bool widthLessRequired = TJSCALED( postXformImageWidth, factors[i]) < requiredWidth;
1031 bool heightLessRequired = TJSCALED( postXformImageHeight, factors[i]) < requiredHeight;
1032 // If either scaled dimension is smaller than the desired one, we were done at the last iteration
1033 if ( (fittingMode == FittingMode::SCALE_TO_FILL) && (widthLessRequired || heightLessRequired) )
1037 // If both dimensions are smaller than the desired one, we were done at the last iteration:
1038 if ( (fittingMode == FittingMode::SHRINK_TO_FIT) && ( widthLessRequired && heightLessRequired ) )
1042 // If the width is smaller than the desired one, we were done at the last iteration:
1043 if ( fittingMode == FittingMode::FIT_WIDTH && widthLessRequired )
1047 // If the width is smaller than the desired one, we were done at the last iteration:
1048 if ( fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired )
1052 // This factor stays is within our fitting mode constraint so remember it:
1053 scaleFactorIndex = i;
1057 // Regardless of requested size, downscale to avoid exceeding the maximum texture size:
1058 for( int i = scaleFactorIndex; i < numFactors; ++i )
1060 // Continue downscaling to below maximum texture size (if possible)
1061 scaleFactorIndex = i;
1063 if( TJSCALED(postXformImageWidth, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) &&
1064 TJSCALED(postXformImageHeight, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) )
1066 // Current scale-factor downscales to below maximum texture size
1071 // We have finally chosen the scale-factor, return width/height values
1072 if( scaleFactorIndex > 0 )
1074 preXformImageWidth = TJSCALED(preXformImageWidth, (factors[scaleFactorIndex]));
1075 preXformImageHeight = TJSCALED(preXformImageHeight, (factors[scaleFactorIndex]));
1076 postXformImageWidth = TJSCALED(postXformImageWidth, (factors[scaleFactorIndex]));
1077 postXformImageHeight = TJSCALED(postXformImageHeight, (factors[scaleFactorIndex]));
1084 ExifHandle LoadExifData( FILE* fp )
1086 auto exifData = MakeNullExifData();
1087 unsigned char dataBuffer[1024];
1089 if( fseek( fp, 0, SEEK_SET ) )
1091 DALI_LOG_ERROR("Error seeking to start of file\n");
1095 auto exifLoader = std::unique_ptr<ExifLoader, decltype(exif_loader_unref)*>{
1096 exif_loader_new(), exif_loader_unref };
1100 int size = fread( dataBuffer, 1, sizeof( dataBuffer ), fp );
1105 if( ! exif_loader_write( exifLoader.get(), dataBuffer, size ) )
1111 exifData.reset( exif_loader_get_data( exifLoader.get() ) );
1117 bool LoadJpegHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height )
1119 unsigned int requiredWidth = input.scalingParameters.dimensions.GetWidth();
1120 unsigned int requiredHeight = input.scalingParameters.dimensions.GetHeight();
1121 FILE* const fp = input.file;
1123 bool success = false;
1124 if( requiredWidth == 0 && requiredHeight == 0 )
1126 success = LoadJpegHeader( fp, width, height );
1130 // Double check we get the same width/height from the header
1131 unsigned int headerWidth;
1132 unsigned int headerHeight;
1133 if( LoadJpegHeader( fp, headerWidth, headerHeight ) )
1135 auto transform = JpegTransform::NONE;
1137 if( input.reorientationRequested )
1139 auto exifData = LoadExifData( fp );
1142 transform = ConvertExifOrientation(exifData.get());
1145 int preXformImageWidth = headerWidth;
1146 int preXformImageHeight = headerHeight;
1147 int postXformImageWidth = headerWidth;
1148 int postXformImageHeight = headerHeight;
1150 success = TransformSize( requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight );
1153 width = postXformImageWidth;
1154 height = postXformImageHeight;
1160 width = headerWidth;
1161 height = headerHeight;
1169 } // namespace TizenPlatform