Revert "[Tizen] Add codes for Dali Windows Backend"
[platform/core/uifw/dali-adaptor.git] / dali / internal / imaging / common / loader-jpeg-turbo.cpp
1 /*
2  * Copyright (c) 2017 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18  // CLASS HEADER
19 #include <dali/internal/imaging/common/loader-jpeg.h>
20
21 // EXTERNAL HEADERS
22 #include <functional>
23 #include <array>
24 #include <utility>
25 #include <memory>
26 #include <libexif/exif-data.h>
27 #include <libexif/exif-loader.h>
28 #include <libexif/exif-tag.h>
29 #include <turbojpeg.h>
30 #include <jpeglib.h>
31 #include <cstring>
32 #include <setjmp.h>
33
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>
37
38
39 // INTERNAL HEADERS
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>
44
45 namespace
46 {
47 using Dali::Vector;
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;
53
54 /** Transformations that can be applied to decoded pixels to respect exif orientation
55   *  codes in image headers */
56 enum class JpegTransform
57 {
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
66 };
67
68 /**
69   * @brief Error handling bookeeping for the JPEG Turbo library's
70   * setjmp/longjmp simulated exceptions.
71   */
72 struct JpegErrorState
73 {
74   struct jpeg_error_mgr errorManager;
75   jmp_buf jumpBuffer;
76 };
77
78 /**
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.
81   */
82 void  JpegErrorHandler ( j_common_ptr cinfo )
83 {
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 );
87
88   /* Return control to the setjmp point */
89   longjmp( myerr->jumpBuffer, 1 );
90 }
91
92 void JpegOutputMessageHandler( j_common_ptr cinfo )
93 {
94   /* Stop libjpeg from printing to stderr - Do Nothing */
95 }
96
97 /**
98   * LibJPEG Turbo tjDecompress2 API doesn't distinguish between errors that still allow
99   * the JPEG to be displayed and fatal errors.
100   */
101 bool IsJpegErrorFatal( const std::string& errorMessage )
102 {
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 ))
111   {
112     return false;
113   }
114   return true;
115 }
116
117 // helpers for safe exif memory handling
118 using ExifHandle = std::unique_ptr<ExifData, decltype(exif_data_free)*>;
119
120 ExifHandle MakeNullExifData()
121 {
122   return ExifHandle{nullptr, exif_data_free};
123 }
124
125 ExifHandle MakeExifDataFromData(unsigned char* data, unsigned int size)
126 {
127   return ExifHandle{exif_data_new_from_data(data, size), exif_data_free};
128 }
129
130 // Helpers for safe Jpeg memory handling
131 using JpegHandle = std::unique_ptr<void /*tjhandle*/, decltype(tjDestroy)*>;
132
133 JpegHandle MakeJpegCompressor()
134 {
135   return JpegHandle{tjInitCompress(), tjDestroy};
136 }
137
138 JpegHandle MakeJpegDecompressor()
139 {
140   return JpegHandle{tjInitDecompress(), tjDestroy};
141 }
142
143 using JpegMemoryHandle = std::unique_ptr<unsigned char, decltype(tjFree)*>;
144
145 JpegMemoryHandle MakeJpegMemory()
146 {
147   return JpegMemoryHandle{nullptr, tjFree};
148 }
149
150 template<class T, class Deleter>
151 class UniquePointerSetter final
152 {
153 public:
154   UniquePointerSetter(std::unique_ptr<T, Deleter>& uniquePointer)
155   : mUniquePointer(uniquePointer),
156     mRawPointer(nullptr)
157   {}
158
159   /// @brief Pointer to Pointer cast operator
160   operator T** () { return &mRawPointer; }
161
162   /// @brief Destructor, reset the unique_ptr
163   ~UniquePointerSetter() { mUniquePointer.reset(mRawPointer); }
164
165 private:
166   std::unique_ptr<T, Deleter>& mUniquePointer;
167   T* mRawPointer;
168 };
169
170 template<typename T, typename Deleter>
171 UniquePointerSetter<T, Deleter> SetPointer(std::unique_ptr<T, Deleter>& uniquePointer)
172 {
173   return UniquePointerSetter<T, Deleter>{uniquePointer};
174 }
175
176 using TransformFunction = std::function<void(PixelArray,unsigned, unsigned)>;
177 using TransformFunctionArray = std::array<TransformFunction, 3>; // 1, 3 and 4 bytes per pixel
178
179 /// @brief Select the transform function depending on the pixel format
180 TransformFunction GetTransformFunction(const TransformFunctionArray& functions,
181                                        Pixel::Format pixelFormat)
182 {
183   auto function = TransformFunction{};
184
185   int decodedPixelSize = Pixel::GetBytesPerPixel(pixelFormat);
186   switch( decodedPixelSize )
187   {
188     case DECODED_L8:
189     {
190       function = functions[0];
191       break;
192     }
193     case DECODED_RGB888:
194     {
195       function = functions[1];
196       break;
197     }
198     case DECODED_RGBA8888:
199     {
200       function = functions[2];
201       break;
202     }
203     default:
204     {
205       DALI_LOG_ERROR("Transform operation not supported on this Pixel::Format!");
206       function = functions[1];
207       break;
208     }
209   }
210   return function;
211 }
212
213 // Storing Exif fields as properties
214 template<class R, class V>
215 R ConvertExifNumeric( const ExifEntry& entry )
216 {
217   return static_cast<R>((*reinterpret_cast<V*>(entry.data)));
218 }
219
220 void AddExifFieldPropertyMap( Dali::Property::Map& out, const ExifEntry& entry, ExifIfd ifd )
221 {
222   auto shortName = std::string(exif_tag_get_name_in_ifd(entry.tag, ifd ));
223   switch( entry.format )
224   {
225     case EXIF_FORMAT_ASCII:
226     {
227       out.Insert( shortName, std::string( reinterpret_cast<char *>(entry.data), entry.size ) );
228       break;
229     }
230     case EXIF_FORMAT_SHORT:
231     {
232       out.Insert( shortName, ConvertExifNumeric<int, unsigned short>(entry) );
233       break;
234     }
235     case EXIF_FORMAT_LONG:
236     {
237       out.Insert( shortName, ConvertExifNumeric<int, unsigned long>(entry) );
238       break;
239     }
240     case EXIF_FORMAT_SSHORT:
241     {
242       out.Insert( shortName, ConvertExifNumeric<int, short>(entry) );
243       break;
244     }
245     case EXIF_FORMAT_SLONG:
246     {
247       out.Insert( shortName, ConvertExifNumeric<int, long>(entry) );
248       break;
249     }
250     case EXIF_FORMAT_FLOAT:
251     {
252       out.Insert (shortName, ConvertExifNumeric<float, float>(entry) );
253       break;
254     }
255     case EXIF_FORMAT_DOUBLE:
256     {
257       out.Insert( shortName, ConvertExifNumeric<float, double>(entry) );
258       break;
259     }
260     case EXIF_FORMAT_RATIONAL:
261     {
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);
267       break;
268     }
269     case EXIF_FORMAT_SBYTE:
270     {
271       out.Insert(shortName, "EXIF_FORMAT_SBYTE Unsupported");
272       break;
273     }
274     case EXIF_FORMAT_BYTE:
275     {
276       out.Insert(shortName, "EXIF_FORMAT_BYTE Unsupported");
277       break;
278     }
279     case EXIF_FORMAT_SRATIONAL:
280     {
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);
286       break;
287     }
288     case EXIF_FORMAT_UNDEFINED:
289     default:
290     {
291       std::stringstream ss;
292       ss << "EXIF_FORMAT_UNDEFINED, size: " << entry.size << ", components: " << entry.components;
293       out.Insert( shortName, ss.str());
294     }
295   }
296 }
297
298 /// @brief Apply a transform to a buffer
299 bool Transform(const TransformFunctionArray& transformFunctions,
300                PixelArray buffer,
301                int width,
302                int height,
303                Pixel::Format pixelFormat )
304 {
305   auto transformFunction = GetTransformFunction(transformFunctions, pixelFormat);
306   if(transformFunction)
307   {
308     transformFunction(buffer, width, height);
309   }
310   return bool(transformFunction);
311 }
312
313 /// @brief Auxiliar type to represent pixel data with different number of bytes
314 template<size_t N>
315 struct PixelType
316 {
317   char _[N];
318 };
319
320 template<size_t N>
321 void FlipVertical(PixelArray buffer, int width, int height)
322 {
323   // Destination pixel, set as the first pixel of screen
324   auto to = reinterpret_cast<PixelType<N>*>( buffer );
325
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;
329
330   for (auto ix = 0, endLoop = (width * height) / 2; ix < endLoop; ++ix, ++to, --from)
331   {
332     std::swap(*from, *to);
333   }
334 }
335
336 template<size_t N>
337 void FlipHorizontal(PixelArray buffer, int width, int height)
338 {
339   for(auto iy = 0; iy < height; ++iy)
340   {
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)
346     {
347       std::swap(*from, *to);
348     }
349   }
350 }
351
352 template<size_t N>
353 void Transpose(PixelArray buffer, int width, int height)
354 {
355   //Transform vertically only
356   for(auto iy = 0; iy < height / 2; ++iy)
357   {
358     for(auto ix = 0; ix < width; ++ix)
359     {
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);
363     }
364   }
365 }
366
367 template<size_t N>
368 void Transverse(PixelArray buffer, int width, int height)
369 {
370   using PixelT = PixelType<N>;
371   Vector<PixelT> data;
372   data.Resize( width * height );
373   auto dataPtr = data.Begin();
374
375   auto original = reinterpret_cast<PixelT*>(buffer);
376   std::copy(original, original + width * height, dataPtr);
377
378   auto to = original;
379   for( auto iy = 0; iy < width; ++iy )
380   {
381     for( auto ix = 0; ix < height; ++ix, ++to )
382     {
383       auto from = dataPtr + ix * width + iy;
384       *to = *from;
385     }
386   }
387 }
388
389
390 template<size_t N>
391 void Rotate90(PixelArray buffer, int width, int height)
392 {
393   using PixelT = PixelType<N>;
394   Vector<PixelT> data;
395   data.Resize(width * height);
396   auto dataPtr = data.Begin();
397
398   auto original = reinterpret_cast<PixelT*>(buffer);
399   std::copy(original, original + width * height, dataPtr);
400
401   std::swap(width, height);
402   auto hw = width * height;
403   hw = - hw - 1;
404
405   auto to = original + width - 1;
406   auto from = dataPtr;
407
408   for(auto ix = width; --ix >= 0;)
409   {
410     for(auto iy = height; --iy >= 0; ++from)
411     {
412       *to = *from;
413       to += width;
414     }
415     to += hw;
416   }
417 }
418
419 template<size_t N>
420 void Rotate180(PixelArray buffer, int width, int height)
421 {
422   using PixelT = PixelType<N>;
423   Vector<PixelT> data;
424   data.Resize(width * height);
425   auto dataPtr = data.Begin();
426
427   auto original = reinterpret_cast<PixelT*>(buffer);
428   std::copy(original, original + width * height, dataPtr);
429
430   auto to = original;
431   for( auto iy = 0; iy < width; iy++ )
432   {
433     for( auto ix = 0; ix < height; ix++ )
434     {
435       auto from = dataPtr + (height - ix) * width - 1 - iy;
436       *to = *from;
437       ++to;
438     }
439   }
440 }
441
442
443 template<size_t N>
444 void Rotate270(PixelArray buffer, int width, int height)
445 {
446   using PixelT = PixelType<N>;
447   Vector<PixelT> data;
448   data.Resize(width * height);
449   auto dataPtr = data.Begin();
450
451   auto original = reinterpret_cast<PixelT*>(buffer);
452   std::copy(original, original + width * height, dataPtr);
453
454   auto w = height;
455   std::swap(width, height);
456   auto hw = width * height;
457
458   auto* to = original + hw  - width;
459   auto* from = dataPtr;
460
461   w = -w;
462   hw =  hw + 1;
463   for(auto ix = width; --ix >= 0;)
464   {
465     for(auto iy = height; --iy >= 0;)
466     {
467       *to = *from;
468       ++from;
469       to += w;
470     }
471     to += hw;
472   }
473 }
474
475 } // namespace
476
477 namespace Dali
478 {
479
480 namespace TizenPlatform
481 {
482
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 );
489
490 bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height )
491 {
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 );
496
497   jerr.errorManager.output_message = JpegOutputMessageHandler;
498   jerr.errorManager.error_exit = JpegErrorHandler;
499
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))
503   {
504     jpeg_destroy_decompress(&cinfo);
505     return false;
506   }
507
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
513
514   jpeg_stdio_src( &cinfo, fp );
515
516   // Check header to see if it is  JPEG file
517   if( jpeg_read_header( &cinfo, TRUE ) != JPEG_HEADER_OK )
518   {
519     width = height = 0;
520     jpeg_destroy_decompress( &cinfo );
521     return false;
522   }
523
524   width = cinfo.image_width;
525   height = cinfo.image_height;
526
527   jpeg_destroy_decompress( &cinfo );
528   return true;
529 }
530
531 bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
532 {
533   const int flags= 0;
534   FILE* const fp = input.file;
535
536   if( fseek(fp,0,SEEK_END) )
537   {
538     DALI_LOG_ERROR("Error seeking to end of file\n");
539     return false;
540   }
541
542   long positionIndicator = ftell(fp);
543   unsigned int jpegBufferSize = 0u;
544   if( positionIndicator > -1L )
545   {
546     jpegBufferSize = static_cast<unsigned int>(positionIndicator);
547   }
548
549   if( 0u == jpegBufferSize )
550   {
551     return false;
552   }
553
554   if( fseek(fp, 0, SEEK_SET) )
555   {
556     DALI_LOG_ERROR("Error seeking to start of file\n");
557     return false;
558   }
559
560   Vector<unsigned char> jpegBuffer;
561   try
562   {
563     jpegBuffer.Resize( jpegBufferSize );
564   }
565   catch(...)
566   {
567     DALI_LOG_ERROR( "Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U );
568     return false;
569   }
570   unsigned char * const jpegBufferPtr = jpegBuffer.Begin();
571
572   // Pull the compressed JPEG image bytes out of a file and into memory:
573   if( fread( jpegBufferPtr, 1, jpegBufferSize, fp ) != jpegBufferSize )
574   {
575     DALI_LOG_WARNING("Error on image file read.\n");
576     return false;
577   }
578
579   if( fseek(fp, 0, SEEK_SET) )
580   {
581     DALI_LOG_ERROR("Error seeking to start of file\n");
582   }
583
584   auto jpeg = MakeJpegDecompressor();
585
586   if(!jpeg)
587   {
588     DALI_LOG_ERROR("%s\n", tjGetErrorStr());
589     return false;
590   }
591
592   auto transform = JpegTransform::NONE;
593
594   // extract exif data
595   auto exifData = MakeExifDataFromData(jpegBufferPtr, jpegBufferSize);
596
597   if( exifData && input.reorientationRequested )
598   {
599     transform = ConvertExifOrientation(exifData.get());
600   }
601
602   std::unique_ptr<Property::Map> exifMap;
603   exifMap.reset( new Property::Map() );
604
605   for( auto k = 0u; k < EXIF_IFD_COUNT; ++k )
606   {
607     auto content = exifData->ifd[k];
608     for (auto i = 0u; i < content->count; ++i)
609     {
610       auto       &&tag      = content->entries[i];
611       const char *shortName = exif_tag_get_name_in_ifd(tag->tag, static_cast<ExifIfd>(k));
612       if(shortName)
613       {
614         AddExifFieldPropertyMap(*exifMap, *tag, static_cast<ExifIfd>(k));
615       }
616     }
617   }
618
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;
622
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 )
628   {
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.
631   }
632 #else
633   if( tjDecompressHeader2( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling ) == -1 )
634   {
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.
637   }
638 #endif
639
640   if(preXformImageWidth == 0 || preXformImageHeight == 0)
641   {
642     DALI_LOG_WARNING("Invalid Image!\n");
643     return false;
644   }
645
646   int requiredWidth  = input.scalingParameters.dimensions.GetWidth();
647   int requiredHeight = input.scalingParameters.dimensions.GetHeight();
648
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;
654
655
656   int scaledPreXformWidth   = preXformImageWidth;
657   int scaledPreXformHeight  = preXformImageHeight;
658   int scaledPostXformWidth  = postXformImageWidth;
659   int scaledPostXformHeight = postXformImageHeight;
660
661   TransformSize( requiredWidth, requiredHeight,
662                  input.scalingParameters.scalingMode,
663                  input.scalingParameters.samplingMode,
664                  transform,
665                  scaledPreXformWidth, scaledPreXformHeight,
666                  scaledPostXformWidth, scaledPostXformHeight );
667
668
669   // Colorspace conversion options
670   TJPF pixelLibJpegType = TJPF_RGB;
671   Pixel::Format pixelFormat = Pixel::RGB888;
672 #ifndef DALI_PROFILE_UBUNTU
673   switch (jpegColorspace)
674   {
675     case TJCS_RGB:
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.
678     case TJCS_YCbCr:
679     {
680       pixelLibJpegType = TJPF_RGB;
681       pixelFormat = Pixel::RGB888;
682       break;
683     }
684     case TJCS_GRAY:
685     {
686       pixelLibJpegType = TJPF_GRAY;
687       pixelFormat = Pixel::L8;
688       break;
689     }
690     case TJCS_CMYK:
691     case TJCS_YCCK:
692     {
693       pixelLibJpegType = TJPF_CMYK;
694       pixelFormat = Pixel::RGBA8888;
695       break;
696     }
697     default:
698     {
699       pixelLibJpegType = TJPF_RGB;
700       pixelFormat = Pixel::RGB888;
701       break;
702     }
703   }
704 #endif
705   // Allocate a bitmap and decompress the jpeg buffer into its pixel buffer:
706   bitmap = Dali::Devel::PixelBuffer::New(scaledPostXformWidth, scaledPostXformHeight, pixelFormat);
707
708   // set metadata
709   GetImplementation(bitmap).SetMetadata( std::move(exifMap) );
710
711   auto bitmapPixelBuffer = bitmap.GetBuffer();
712
713   if( tjDecompress2( jpeg.get(), jpegBufferPtr, jpegBufferSize, reinterpret_cast<unsigned char*>( bitmapPixelBuffer ), scaledPreXformWidth, 0, scaledPreXformHeight, pixelLibJpegType, flags ) == -1 )
714   {
715     std::string errorString = tjGetErrorStr();
716
717     if( IsJpegErrorFatal( errorString ) )
718     {
719         DALI_LOG_ERROR("%s\n", errorString.c_str() );
720         return false;
721     }
722     else
723     {
724         DALI_LOG_WARNING("%s\n", errorString.c_str() );
725     }
726   }
727
728   const unsigned int  bufferWidth  = GetTextureDimension( scaledPreXformWidth );
729   const unsigned int  bufferHeight = GetTextureDimension( scaledPreXformHeight );
730
731   bool result = false;
732   switch(transform)
733   {
734     case JpegTransform::NONE:
735     {
736       result = true;
737       break;
738     }
739     // 3 orientation changes for a camera held perpendicular to the ground or upside-down:
740     case JpegTransform::ROTATE_180:
741     {
742       static auto rotate180Functions = TransformFunctionArray {
743         &Rotate180<1>,
744         &Rotate180<3>,
745         &Rotate180<4>,
746       };
747       result = Transform(rotate180Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
748       break;
749     }
750     case JpegTransform::ROTATE_270:
751     {
752       static auto rotate270Functions = TransformFunctionArray {
753         &Rotate270<1>,
754         &Rotate270<3>,
755         &Rotate270<4>,
756       };
757       result = Transform(rotate270Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
758       break;
759     }
760     case JpegTransform::ROTATE_90:
761     {
762       static auto rotate90Functions = TransformFunctionArray {
763         &Rotate90<1>,
764         &Rotate90<3>,
765         &Rotate90<4>,
766       };
767       result = Transform(rotate90Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
768       break;
769     }
770     case JpegTransform::FLIP_VERTICAL:
771     {
772       static auto flipVerticalFunctions = TransformFunctionArray {
773         &FlipVertical<1>,
774         &FlipVertical<3>,
775         &FlipVertical<4>,
776       };
777       result = Transform(flipVerticalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
778       break;
779     }
780     // Less-common orientation changes, since they don't correspond to a camera's physical orientation:
781     case JpegTransform::FLIP_HORIZONTAL:
782     {
783       static auto flipHorizontalFunctions = TransformFunctionArray {
784         &FlipHorizontal<1>,
785         &FlipHorizontal<3>,
786         &FlipHorizontal<4>,
787       };
788       result = Transform(flipHorizontalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
789       break;
790     }
791     case JpegTransform::TRANSPOSE:
792     {
793       static auto transposeFunctions = TransformFunctionArray {
794         &Transpose<1>,
795         &Transpose<3>,
796         &Transpose<4>,
797       };
798       result = Transform(transposeFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
799       break;
800     }
801     case JpegTransform::TRANSVERSE:
802     {
803       static auto transverseFunctions = TransformFunctionArray {
804         &Transverse<1>,
805         &Transverse<3>,
806         &Transverse<4>,
807       };
808       result = Transform(transverseFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
809       break;
810     }
811     default:
812     {
813       DALI_LOG_ERROR( "Unsupported JPEG Orientation transformation: %x.\n", transform );
814       break;
815     }
816   }
817
818   return result;
819 }
820
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 )
823 {
824
825   if( !pixelBuffer )
826   {
827     DALI_LOG_ERROR("Null input buffer\n");
828     return false;
829   }
830
831   // Translate pixel format enum:
832   int jpegPixelFormat = -1;
833
834   switch( pixelFormat )
835   {
836     case Pixel::RGB888:
837     {
838       jpegPixelFormat = TJPF_RGB;
839       break;
840     }
841     case Pixel::RGBA8888:
842     {
843       // Ignore the alpha:
844       jpegPixelFormat = TJPF_RGBX;
845       break;
846     }
847     case Pixel::BGRA8888:
848     {
849       // Ignore the alpha:
850       jpegPixelFormat = TJPF_BGRX;
851       break;
852     }
853     default:
854     {
855       DALI_LOG_ERROR( "Unsupported pixel format for encoding to JPEG.\n" );
856       return false;
857     }
858   }
859
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 );
863   if( quality < 1 )
864   {
865     quality = 1;
866   }
867   if( quality > 100 )
868   {
869     quality = 100;
870   }
871
872   // Initialise a JPEG codec:
873   {
874     auto jpeg = MakeJpegCompressor();
875     if( jpeg )
876     {
877       DALI_LOG_ERROR( "JPEG Compressor init failed: %s\n", tjGetErrorStr() );
878       return false;
879     }
880
881
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();
886
887     // Run the compressor:
888     unsigned long dstBufferSize = 0;
889     const int flags = 0;
890
891     if( tjCompress2( jpeg.get(),
892                      const_cast<unsigned char*>(pixelBuffer),
893                      width, 0, height,
894                      jpegPixelFormat, SetPointer(dstBuffer), &dstBufferSize,
895                      TJSAMP_444, quality, flags ) )
896     {
897       DALI_LOG_ERROR("JPEG Compression failed: %s\n", tjGetErrorStr());
898       return false;
899     }
900
901     encodedPixels.Resize( dstBufferSize );
902     memcpy( encodedPixels.Begin(), dstBuffer.get(), dstBufferSize );
903   }
904   return true;
905 }
906
907
908 JpegTransform ConvertExifOrientation(ExifData* exifData)
909 {
910   auto transform = JpegTransform::NONE;
911   ExifEntry * const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
912   int orientation = 0;
913   if( entry )
914   {
915     orientation = exif_get_short(entry->data, exif_data_get_byte_order(entry->parent->parent));
916     switch( orientation )
917     {
918       case 1:
919       {
920         transform = JpegTransform::NONE;
921         break;
922       }
923       case 2:
924       {
925         transform = JpegTransform::FLIP_HORIZONTAL;
926         break;
927       }
928       case 3:
929       {
930         transform = JpegTransform::FLIP_VERTICAL;
931         break;
932       }
933       case 4:
934       {
935         transform = JpegTransform::TRANSPOSE;
936         break;
937       }
938       case 5:
939       {
940         transform = JpegTransform::TRANSVERSE;
941         break;
942       }
943       case 6:
944       {
945         transform = JpegTransform::ROTATE_90;
946         break;
947       }
948       case 7:
949       {
950         transform = JpegTransform::ROTATE_180;
951         break;
952       }
953       case 8:
954       {
955         transform = JpegTransform::ROTATE_270;
956         break;
957       }
958       default:
959       {
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 );
962         break;
963       }
964     }
965   }
966   return transform;
967 }
968
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 )
974 {
975   bool success = true;
976
977   if( transform == JpegTransform::ROTATE_90 || transform == JpegTransform::ROTATE_270 || transform == JpegTransform::ROTATE_180 || transform == JpegTransform::TRANSVERSE)
978   {
979     std::swap( requiredWidth, requiredHeight );
980     std::swap( postXformImageWidth, postXformImageHeight );
981   }
982
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();
987
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:
991
992   int numFactors = 0;
993   tjscalingfactor* factors = tjGetScalingFactors( &numFactors );
994   if( factors == NULL )
995   {
996     DALI_LOG_WARNING("TurboJpeg tjGetScalingFactors error!\n");
997     success = false;
998   }
999   else
1000   {
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 )
1006     {
1007       case SamplingMode::BOX:
1008       case SamplingMode::BOX_THEN_NEAREST:
1009       case SamplingMode::BOX_THEN_LINEAR:
1010       case SamplingMode::DONT_CARE:
1011       {
1012         downscale = true;
1013         break;
1014       }
1015       case SamplingMode::NO_FILTER:
1016       case SamplingMode::NEAREST:
1017       case SamplingMode::LINEAR:
1018       {
1019         downscale = false;
1020         break;
1021       }
1022     }
1023
1024     int scaleFactorIndex( 0 );
1025     if( downscale )
1026     {
1027       // Find nearest supported scaling factor (factors are in sequential order, getting smaller)
1028       for( int i = 1; i < numFactors; ++i )
1029       {
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) )
1034         {
1035           break;
1036         }
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 ) )
1039         {
1040           break;
1041         }
1042         // If the width is smaller than the desired one, we were done at the last iteration:
1043         if ( fittingMode == FittingMode::FIT_WIDTH && widthLessRequired )
1044         {
1045           break;
1046         }
1047         // If the width is smaller than the desired one, we were done at the last iteration:
1048         if ( fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired )
1049         {
1050           break;
1051         }
1052         // This factor stays is within our fitting mode constraint so remember it:
1053         scaleFactorIndex = i;
1054       }
1055     }
1056
1057     // Regardless of requested size, downscale to avoid exceeding the maximum texture size:
1058     for( int i = scaleFactorIndex; i < numFactors; ++i )
1059     {
1060       // Continue downscaling to below maximum texture size (if possible)
1061       scaleFactorIndex = i;
1062
1063       if( TJSCALED(postXformImageWidth,  (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) &&
1064           TJSCALED(postXformImageHeight, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) )
1065       {
1066         // Current scale-factor downscales to below maximum texture size
1067         break;
1068       }
1069     }
1070
1071     // We have finally chosen the scale-factor, return width/height values
1072     if( scaleFactorIndex > 0 )
1073     {
1074       preXformImageWidth   = TJSCALED(preXformImageWidth,   (factors[scaleFactorIndex]));
1075       preXformImageHeight  = TJSCALED(preXformImageHeight,  (factors[scaleFactorIndex]));
1076       postXformImageWidth  = TJSCALED(postXformImageWidth,  (factors[scaleFactorIndex]));
1077       postXformImageHeight = TJSCALED(postXformImageHeight, (factors[scaleFactorIndex]));
1078     }
1079   }
1080
1081   return success;
1082 }
1083
1084 ExifHandle LoadExifData( FILE* fp )
1085 {
1086   auto exifData = MakeNullExifData();
1087   unsigned char dataBuffer[1024];
1088
1089   if( fseek( fp, 0, SEEK_SET ) )
1090   {
1091     DALI_LOG_ERROR("Error seeking to start of file\n");
1092   }
1093   else
1094   {
1095     auto exifLoader = std::unique_ptr<ExifLoader, decltype(exif_loader_unref)*>{
1096         exif_loader_new(), exif_loader_unref };
1097
1098     while( !feof(fp) )
1099     {
1100       int size = fread( dataBuffer, 1, sizeof( dataBuffer ), fp );
1101       if( size <= 0 )
1102       {
1103         break;
1104       }
1105       if( ! exif_loader_write( exifLoader.get(), dataBuffer, size ) )
1106       {
1107         break;
1108       }
1109     }
1110
1111     exifData.reset( exif_loader_get_data( exifLoader.get() ) );
1112   }
1113
1114   return exifData;
1115 }
1116
1117 bool LoadJpegHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height )
1118 {
1119   unsigned int requiredWidth  = input.scalingParameters.dimensions.GetWidth();
1120   unsigned int requiredHeight = input.scalingParameters.dimensions.GetHeight();
1121   FILE* const fp = input.file;
1122
1123   bool success = false;
1124   if( requiredWidth == 0 && requiredHeight == 0 )
1125   {
1126     success = LoadJpegHeader( fp, width, height );
1127   }
1128   else
1129   {
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 ) )
1134     {
1135       auto transform = JpegTransform::NONE;
1136
1137       if( input.reorientationRequested )
1138       {
1139         auto exifData = LoadExifData( fp );
1140         if( exifData )
1141         {
1142           transform = ConvertExifOrientation(exifData.get());
1143         }
1144
1145         int preXformImageWidth = headerWidth;
1146         int preXformImageHeight = headerHeight;
1147         int postXformImageWidth = headerWidth;
1148         int postXformImageHeight = headerHeight;
1149
1150         success = TransformSize( requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight );
1151         if(success)
1152         {
1153           width = postXformImageWidth;
1154           height = postXformImageHeight;
1155         }
1156       }
1157       else
1158       {
1159         success = true;
1160         width = headerWidth;
1161         height = headerHeight;
1162       }
1163     }
1164   }
1165   return success;
1166 }
1167
1168
1169 } // namespace TizenPlatform
1170
1171 } // namespace Dali