Cleanup ResourceLoading and PlatformAbstraction
[platform/core/uifw/dali-adaptor.git] / platform-abstractions / tizen / image-loaders / 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 // INTERNAL HEADERS
19 #include "loader-jpeg.h"
20 #include <dali/integration-api/bitmap.h>
21 #include "platform-capabilities.h"
22 #include "image-operations.h"
23
24 // EXTERNAL HEADERS
25 #include <libexif/exif-data.h>
26 #include <libexif/exif-loader.h>
27 #include <libexif/exif-tag.h>
28 #include <turbojpeg.h>
29 #include <jpeglib.h>
30 #include <cstring>
31 #include <setjmp.h>
32
33 namespace Dali
34 {
35 using Integration::Bitmap;
36
37 namespace TizenPlatform
38 {
39
40 namespace
41 {
42   const unsigned DECODED_PIXEL_SIZE = 3;
43   const TJPF DECODED_PIXEL_LIBJPEG_TYPE = TJPF_RGB;
44
45   /** Transformations that can be applied to decoded pixels to respect exif orientation
46    *  codes in image headers */
47   enum JPGFORM_CODE
48   {
49     JPGFORM_NONE = 1, /* no transformation 0th-Row = top & 0th-Column = left */
50     JPGFORM_FLIP_H,   /* horizontal flip 0th-Row = top & 0th-Column = right */
51     JPGFORM_FLIP_V,   /* vertical flip   0th-Row = bottom & 0th-Column = right*/
52     JPGFORM_TRANSPOSE, /* transpose across UL-to-LR axis  0th-Row = bottom & 0th-Column = left*/
53     JPGFORM_TRANSVERSE,/* transpose across UR-to-LL axis  0th-Row = left   & 0th-Column = top*/
54     JPGFORM_ROT_90,    /* 90-degree clockwise rotation  0th-Row = right  & 0th-Column = top*/
55     JPGFORM_ROT_180,   /* 180-degree rotation  0th-Row = right  & 0th-Column = bottom*/
56     JPGFORM_ROT_270    /* 270-degree clockwise (or 90 ccw) 0th-Row = left  & 0th-Column = bottom*/
57   };
58
59   struct RGB888Type
60   {
61      char R;
62      char G;
63      char B;
64   };
65
66   /**
67    * @brief Error handling bookeeping for the JPEG Turbo library's
68    * setjmp/longjmp simulated exceptions.
69    */
70   struct JpegErrorState {
71     struct jpeg_error_mgr errorManager;
72     jmp_buf jumpBuffer;
73   };
74
75   /**
76    * @brief Called by the JPEG library when it hits an error.
77    * We jump out of the library so our loader code can return an error.
78    */
79   void  JpegErrorHandler ( j_common_ptr cinfo )
80   {
81     DALI_LOG_ERROR( "JpegErrorHandler(): libjpeg-turbo fatal error in JPEG decoding.\n" );
82     /* cinfo->err really points to a JpegErrorState struct, so coerce pointer */
83     JpegErrorState * myerr = reinterpret_cast<JpegErrorState *>( cinfo->err );
84
85     /* Return control to the setjmp point */
86     longjmp( myerr->jumpBuffer, 1 );
87   }
88
89   void JpegOutputMessageHandler( j_common_ptr cinfo )
90   {
91     /* Stop libjpeg from printing to stderr - Do Nothing */
92   }
93
94   /**
95    * LibJPEG Turbo tjDecompress2 API doesn't distinguish between errors that still allow
96    * the JPEG to be displayed and fatal errors.
97    */
98   bool IsJpegErrorFatal( const std::string& errorMessage )
99   {
100     if( ( errorMessage.find("Corrupt JPEG data") != std::string::npos ) ||
101         ( errorMessage.find("Invalid SOS parameters") != std::string::npos ) )
102     {
103       return false;
104     }
105     return true;
106   }
107
108
109   /** Simple struct to ensure xif data is deleted. */
110   struct ExifAutoPtr
111   {
112     ExifAutoPtr( ExifData* data)
113     :mData( data )
114     {}
115
116     ~ExifAutoPtr()
117     {
118       exif_data_free( mData);
119     }
120     ExifData *mData;
121   };
122
123   /** simple class to enforce clean-up of JPEG structures. */
124   struct AutoJpg
125   {
126     AutoJpg(const tjhandle jpgHandle)
127     : mHnd(jpgHandle)
128     {
129     }
130
131     ~AutoJpg()
132     {
133       // clean up JPG resources
134       tjDestroy( mHnd );
135     }
136
137     tjhandle GetHandle() const
138     {
139       return mHnd ;
140     }
141
142   private:
143     AutoJpg( const AutoJpg& ); //< not defined
144     AutoJpg& operator= ( const AutoJpg& ); //< not defined
145
146     tjhandle mHnd;
147   }; // struct AutoJpg;
148
149   /** RAII wrapper to free memory allocated by the jpeg-turbo library. */
150   struct AutoJpgMem
151   {
152     AutoJpgMem(unsigned char * const tjMem)
153     : mTjMem(tjMem)
154     {
155     }
156
157     ~AutoJpgMem()
158     {
159       tjFree(mTjMem);
160     }
161
162     unsigned char * Get() const
163     {
164       return mTjMem;
165     }
166
167   private:
168     AutoJpgMem( const AutoJpgMem& ); //< not defined
169     AutoJpgMem& operator= ( const AutoJpgMem& ); //< not defined
170
171     unsigned char * const mTjMem;
172   };
173
174   // Workaround to avoid exceeding the maximum texture size
175   const int MAX_TEXTURE_WIDTH  = 4096;
176   const int MAX_TEXTURE_HEIGHT = 4096;
177
178 } // namespace
179
180 bool JpegRotate90 (unsigned char *buffer, int width, int height, int bpp);
181 bool JpegRotate180(unsigned char *buffer, int width, int height, int bpp);
182 bool JpegRotate270(unsigned char *buffer, int width, int height, int bpp);
183 JPGFORM_CODE ConvertExifOrientation(ExifData* exifData);
184 bool TransformSize( int requiredWidth, int requiredHeight,
185                     FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
186                     JPGFORM_CODE transform,
187                     int& preXformImageWidth, int& preXformImageHeight,
188                     int& postXformImageWidth, int& postXformImageHeight );
189
190 bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height )
191 {
192   // using libjpeg API to avoid having to read the whole file in a buffer
193   struct jpeg_decompress_struct cinfo;
194   struct JpegErrorState jerr;
195   cinfo.err = jpeg_std_error( &jerr.errorManager );
196
197   jerr.errorManager.output_message = JpegOutputMessageHandler;
198   jerr.errorManager.error_exit = JpegErrorHandler;
199
200   // On error exit from the JPEG lib, control will pass via JpegErrorHandler
201   // into this branch body for cleanup and error return:
202   if(setjmp(jerr.jumpBuffer))
203   {
204     jpeg_destroy_decompress(&cinfo);
205     return false;
206   }
207
208   jpeg_create_decompress( &cinfo );
209
210   jpeg_stdio_src( &cinfo, fp );
211
212   // Check header to see if it is  JPEG file
213   if( jpeg_read_header( &cinfo, TRUE ) != JPEG_HEADER_OK )
214   {
215     width = height = 0;
216     jpeg_destroy_decompress( &cinfo );
217     return false;
218   }
219
220   width = cinfo.image_width;
221   height = cinfo.image_height;
222
223   jpeg_destroy_decompress( &cinfo );
224   return true;
225 }
226
227 bool LoadBitmapFromJpeg( const ImageLoader::Input& input, Integration::Bitmap& bitmap )
228 {
229   const int flags= 0;
230   FILE* const fp = input.file;
231
232   if( fseek(fp,0,SEEK_END) )
233   {
234     DALI_LOG_ERROR("Error seeking to end of file\n");
235     return false;
236   }
237
238   long positionIndicator = ftell(fp);
239   unsigned int jpegBufferSize = 0u;
240   if( positionIndicator > -1L )
241   {
242     jpegBufferSize = static_cast<unsigned int>(positionIndicator);
243   }
244
245   if( 0u == jpegBufferSize )
246   {
247     return false;
248   }
249
250   if( fseek(fp, 0, SEEK_SET) )
251   {
252     DALI_LOG_ERROR("Error seeking to start of file\n");
253     return false;
254   }
255
256   Vector<unsigned char> jpegBuffer;
257   try
258   {
259     jpegBuffer.Resize( jpegBufferSize );
260   }
261   catch(...)
262   {
263     DALI_LOG_ERROR( "Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U );
264     return false;
265   }
266   unsigned char * const jpegBufferPtr = jpegBuffer.Begin();
267
268   // Pull the compressed JPEG image bytes out of a file and into memory:
269   if( fread( jpegBufferPtr, 1, jpegBufferSize, fp ) != jpegBufferSize )
270   {
271     DALI_LOG_WARNING("Error on image file read.\n");
272     return false;
273   }
274
275   if( fseek(fp, 0, SEEK_SET) )
276   {
277     DALI_LOG_ERROR("Error seeking to start of file\n");
278   }
279
280   AutoJpg autoJpg(tjInitDecompress());
281
282   if(autoJpg.GetHandle() == NULL)
283   {
284     DALI_LOG_ERROR("%s\n", tjGetErrorStr());
285     return false;
286   }
287
288   JPGFORM_CODE transform = JPGFORM_NONE;
289
290   if( input.reorientationRequested )
291   {
292     ExifAutoPtr exifData( exif_data_new_from_data(jpegBufferPtr, jpegBufferSize) );
293     if( exifData.mData )
294     {
295       transform = ConvertExifOrientation(exifData.mData);
296     }
297   }
298
299   // Push jpeg data in memory buffer through TurboJPEG decoder to make a raw pixel array:
300   int chrominanceSubsampling = -1;
301   int preXformImageWidth = 0, preXformImageHeight = 0;
302   if( tjDecompressHeader2( autoJpg.GetHandle(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling ) == -1 )
303   {
304     DALI_LOG_ERROR("%s\n", tjGetErrorStr());
305     // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
306   }
307
308   if(preXformImageWidth == 0 || preXformImageHeight == 0)
309   {
310     DALI_LOG_WARNING("Invalid Image!\n");
311     return false;
312   }
313
314   int requiredWidth  = input.scalingParameters.dimensions.GetWidth();
315   int requiredHeight = input.scalingParameters.dimensions.GetHeight();
316
317   // If transform is a 90 or 270 degree rotation, the logical width and height
318   // request from the client needs to be adjusted to account by effectively
319   // rotating that too, and the final width and height need to be swapped:
320   int postXformImageWidth = preXformImageWidth;
321   int postXformImageHeight = preXformImageHeight;
322
323
324   int scaledPreXformWidth   = preXformImageWidth;
325   int scaledPreXformHeight  = preXformImageHeight;
326   int scaledPostXformWidth  = postXformImageWidth;
327   int scaledPostXformHeight = postXformImageHeight;
328
329   TransformSize( requiredWidth, requiredHeight,
330                  input.scalingParameters.scalingMode,
331                  input.scalingParameters.samplingMode,
332                  transform,
333                  scaledPreXformWidth, scaledPreXformHeight,
334                  scaledPostXformWidth, scaledPostXformHeight );
335
336   // Allocate a bitmap and decompress the jpeg buffer into its pixel buffer:
337
338   unsigned char * const bitmapPixelBuffer =  bitmap.GetPackedPixelsProfile()->ReserveBuffer(Pixel::RGB888, scaledPostXformWidth, scaledPostXformHeight);
339
340   if( tjDecompress2( autoJpg.GetHandle(), jpegBufferPtr, jpegBufferSize, bitmapPixelBuffer, scaledPreXformWidth, 0, scaledPreXformHeight, DECODED_PIXEL_LIBJPEG_TYPE, flags ) == -1 )
341   {
342     std::string errorString = tjGetErrorStr();
343
344     if( IsJpegErrorFatal( errorString ) )
345     {
346         DALI_LOG_ERROR("%s\n", errorString.c_str());
347         return false;
348     }
349     else
350     {
351         DALI_LOG_WARNING("%s\n", errorString.c_str());
352     }
353   }
354
355   const unsigned int  bufferWidth  = GetTextureDimension( scaledPreXformWidth );
356   const unsigned int  bufferHeight = GetTextureDimension( scaledPreXformHeight );
357
358   bool result = false;
359   switch(transform)
360   {
361     case JPGFORM_NONE:
362     {
363       result = true;
364       break;
365     }
366     // 3 orientation changes for a camera held perpendicular to the ground or upside-down:
367     case JPGFORM_ROT_180:
368     {
369       result = JpegRotate180(bitmapPixelBuffer, bufferWidth, bufferHeight, DECODED_PIXEL_SIZE);
370       break;
371     }
372     case JPGFORM_ROT_270:
373     {
374       result = JpegRotate270(bitmapPixelBuffer, bufferWidth, bufferHeight, DECODED_PIXEL_SIZE);
375       break;
376     }
377     case JPGFORM_ROT_90:
378     {
379       result = JpegRotate90(bitmapPixelBuffer, bufferWidth, bufferHeight, DECODED_PIXEL_SIZE);
380       break;
381     }
382     /// Less-common orientation changes, since they don't correspond to a camera's
383     // physical orientation:
384     case JPGFORM_FLIP_H:
385     case JPGFORM_FLIP_V:
386     case JPGFORM_TRANSPOSE:
387     case JPGFORM_TRANSVERSE:
388     {
389       DALI_LOG_WARNING( "Unsupported JPEG Orientation transformation: %x.\n", transform );
390       break;
391     }
392   }
393   return result;
394 }
395
396 ///@Todo: Move all these rotation functions to portable/image-operations and take "Jpeg" out of their names.
397 bool JpegRotate90(unsigned char *buffer, int width, int height, int bpp)
398 {
399   int  w, iw, ih, hw = 0;
400   int ix, iy = 0;
401   iw = width;
402   ih = height;
403   Vector<unsigned char> data;
404   data.Resize(width * height * bpp);
405   unsigned char *dataPtr = data.Begin();
406   memcpy(dataPtr, buffer, width * height * bpp);
407   w = ih;
408   ih = iw;
409   iw = w;
410   hw = iw * ih;
411   hw = - hw - 1;
412   switch(bpp)
413   {
414     case 3:
415     {
416       RGB888Type* to = reinterpret_cast<RGB888Type*>(buffer) + iw - 1;
417       RGB888Type* from = reinterpret_cast<RGB888Type*>( dataPtr );
418
419       for(ix = iw; -- ix >= 0;)
420       {
421         for(iy = ih; -- iy >= 0; ++from )
422         {
423           *to = *from;
424           to += iw;
425         }
426         to += hw;
427       }
428       break;
429     }
430
431     default:
432     {
433       return false;
434     }
435   }
436
437   return true;
438 }
439
440 bool JpegRotate180(unsigned char *buffer, int width, int height, int bpp)
441 {
442   int  ix, iw, ih, hw = 0;
443   iw = width;
444   ih = height;
445   hw = iw * ih;
446   ix = hw;
447
448   switch(bpp)
449   {
450     case 3:
451     {
452       RGB888Type tmp;
453       RGB888Type* to = reinterpret_cast<RGB888Type*>(buffer) ;
454       RGB888Type* from = reinterpret_cast<RGB888Type*>( buffer ) + hw - 1;
455       for(; --ix >= (hw / 2); ++to, --from)
456       {
457         tmp = *to;
458         *to = *from;
459         *from = tmp;
460       }
461       break;
462     }
463
464     default:
465     {
466       return false;
467     }
468   }
469
470   return true;
471 }
472
473 bool JpegRotate270(unsigned char *buffer, int width, int height, int bpp)
474 {
475   int  w, iw, ih, hw = 0;
476   int ix, iy = 0;
477
478   iw = width;
479   ih = height;
480   Vector<unsigned char> data;
481   data.Resize(width * height * bpp);
482   unsigned char *dataPtr = data.Begin();
483   memcpy(dataPtr, buffer, width * height * bpp);
484   w = ih;
485   ih = iw;
486   iw = w;
487   hw = iw * ih;
488
489   switch(bpp)
490   {
491     case 3:
492     {
493       RGB888Type* to = reinterpret_cast<RGB888Type*>(buffer) + hw  - iw;
494       RGB888Type* from = reinterpret_cast<RGB888Type*>( dataPtr );
495
496       w = -w;
497       hw =  hw + 1;
498       for(ix = iw; -- ix >= 0;)
499       {
500         for(iy = ih; -- iy >= 0;)
501         {
502           *to = *from;
503           from += 1;
504           to += w;
505         }
506         to += hw;
507       }
508       break;
509     }
510     default:
511     {
512       return false;
513     }
514   }
515
516   return true;
517 }
518
519 bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char >& encodedPixels,
520                    const std::size_t width, const std::size_t height, const Pixel::Format pixelFormat, unsigned quality )
521 {
522
523   if( !pixelBuffer )
524   {
525     DALI_LOG_ERROR("Null input buffer\n");
526     return false;
527   }
528
529   // Translate pixel format enum:
530   int jpegPixelFormat = -1;
531
532   switch( pixelFormat )
533   {
534     case Pixel::RGB888:
535     {
536       jpegPixelFormat = TJPF_RGB;
537       break;
538     }
539     case Pixel::RGBA8888:
540     {
541       // Ignore the alpha:
542       jpegPixelFormat = TJPF_RGBX;
543       break;
544     }
545     case Pixel::BGRA8888:
546     {
547       // Ignore the alpha:
548       jpegPixelFormat = TJPF_BGRX;
549       break;
550     }
551     default:
552     {
553       DALI_LOG_ERROR( "Unsupported pixel format for encoding to JPEG.\n" );
554       return false;
555     }
556   }
557
558   // Assert quality is in the documented allowable range of the jpeg-turbo lib:
559   DALI_ASSERT_DEBUG( quality >= 1 );
560   DALI_ASSERT_DEBUG( quality <= 100 );
561   if( quality < 1 )
562   {
563     quality = 1;
564   }
565   if( quality > 100 )
566   {
567     quality = 100;
568   }
569
570   // Initialise a JPEG codec:
571   AutoJpg autoJpg( tjInitCompress() );
572   {
573     if( autoJpg.GetHandle() == NULL )
574     {
575       DALI_LOG_ERROR( "JPEG Compressor init failed: %s\n", tjGetErrorStr() );
576       return false;
577     }
578
579     // Run the compressor:
580     unsigned char* dstBuffer = NULL;
581     unsigned long dstBufferSize = 0;
582     const int flags = 0;
583
584     if( tjCompress2( autoJpg.GetHandle(), const_cast<unsigned char*>(pixelBuffer), width, 0, height, jpegPixelFormat, &dstBuffer, &dstBufferSize, TJSAMP_444, quality, flags ) )
585     {
586       DALI_LOG_ERROR("JPEG Compression failed: %s\n", tjGetErrorStr());
587       return false;
588     }
589
590     // Safely wrap the jpeg codec's buffer in case we are about to throw, then
591     // save the pixels to a persistent buffer that we own and let our cleaner
592     // class clean up the buffer as it goes out of scope:
593     AutoJpgMem cleaner( dstBuffer );
594     encodedPixels.Resize( dstBufferSize );
595     memcpy( encodedPixels.Begin(), dstBuffer, dstBufferSize );
596   }
597   return true;
598 }
599
600
601 JPGFORM_CODE ConvertExifOrientation(ExifData* exifData)
602 {
603   JPGFORM_CODE transform = JPGFORM_NONE;
604   ExifEntry * const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
605   int orientation = 0;
606   if( entry )
607   {
608     orientation = exif_get_short(entry->data, exif_data_get_byte_order(entry->parent->parent));
609     switch( orientation )
610     {
611       case 1:
612       {
613         transform = JPGFORM_NONE;
614         break;
615       }
616       case 2:
617       {
618         transform = JPGFORM_FLIP_H;
619         break;
620       }
621       case 3:
622       {
623         transform = JPGFORM_FLIP_V;
624         break;
625       }
626       case 4:
627       {
628         transform = JPGFORM_TRANSPOSE;
629         break;
630       }
631       case 5:
632       {
633         transform = JPGFORM_TRANSVERSE;
634         break;
635       }
636       case 6:
637       {
638         transform = JPGFORM_ROT_90;
639         break;
640       }
641       case 7:
642       {
643         transform = JPGFORM_ROT_180;
644         break;
645       }
646       case 8:
647       {
648         transform = JPGFORM_ROT_270;
649         break;
650       }
651       default:
652       {
653         // Try to keep loading the file, but let app developer know there was something fishy:
654         DALI_LOG_WARNING( "Incorrect/Unknown Orientation setting found in EXIF header of JPEG image (%x). Orientation setting will be ignored.\n", entry );
655         break;
656       }
657     }
658   }
659   return transform;
660 }
661
662 bool TransformSize( int requiredWidth, int requiredHeight,
663                     FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
664                     JPGFORM_CODE transform,
665                     int& preXformImageWidth, int& preXformImageHeight,
666                     int& postXformImageWidth, int& postXformImageHeight )
667 {
668   bool success = true;
669
670   if( transform == JPGFORM_ROT_90 || transform == JPGFORM_ROT_270 )
671   {
672     std::swap( requiredWidth, requiredHeight );
673     std::swap( postXformImageWidth, postXformImageHeight );
674   }
675
676   // Apply the special rules for when there are one or two zeros in requested dimensions:
677   const ImageDimensions correctedDesired = Internal::Platform::CalculateDesiredDimensions( ImageDimensions( postXformImageWidth, postXformImageHeight), ImageDimensions( requiredWidth, requiredHeight ) );
678   requiredWidth = correctedDesired.GetWidth();
679   requiredHeight = correctedDesired.GetHeight();
680
681   // Rescale image during decode using one of the decoder's built-in rescaling
682   // ratios (expected to be powers of 2), keeping the final image at least as
683   // wide and high as was requested:
684
685   int numFactors = 0;
686   tjscalingfactor* factors = tjGetScalingFactors( &numFactors );
687   if( factors == NULL )
688   {
689     DALI_LOG_WARNING("TurboJpeg tjGetScalingFactors error!\n");
690     success = false;
691   }
692   else
693   {
694     // Internal jpeg downscaling is the same as our BOX_X sampling modes so only
695     // apply it if the application requested one of those:
696     // (use a switch case here so this code will fail to compile if other modes are added)
697     bool downscale = true;
698     switch( samplingMode )
699     {
700       case SamplingMode::BOX:
701       case SamplingMode::BOX_THEN_NEAREST:
702       case SamplingMode::BOX_THEN_LINEAR:
703       case SamplingMode::DONT_CARE:
704       {
705         downscale = true;
706         break;
707       }
708       case SamplingMode::NO_FILTER:
709       case SamplingMode::NEAREST:
710       case SamplingMode::LINEAR:
711       {
712         downscale = false;
713         break;
714       }
715     }
716
717     int scaleFactorIndex( 0 );
718     if( downscale )
719     {
720       // Find nearest supported scaling factor (factors are in sequential order, getting smaller)
721       for( int i = 1; i < numFactors; ++i )
722       {
723         bool widthLessRequired  = TJSCALED( postXformImageWidth,  factors[i]) < requiredWidth;
724         bool heightLessRequired = TJSCALED( postXformImageHeight, factors[i]) < requiredHeight;
725         // If either scaled dimension is smaller than the desired one, we were done at the last iteration
726         if ( (fittingMode == FittingMode::SCALE_TO_FILL) && (widthLessRequired || heightLessRequired) )
727         {
728           break;
729         }
730         // If both dimensions are smaller than the desired one, we were done at the last iteration:
731         if ( (fittingMode == FittingMode::SHRINK_TO_FIT) && ( widthLessRequired && heightLessRequired ) )
732         {
733           break;
734         }
735         // If the width is smaller than the desired one, we were done at the last iteration:
736         if ( fittingMode == FittingMode::FIT_WIDTH && widthLessRequired )
737         {
738           break;
739         }
740         // If the width is smaller than the desired one, we were done at the last iteration:
741         if ( fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired )
742         {
743           break;
744         }
745         // This factor stays is within our fitting mode constraint so remember it:
746         scaleFactorIndex = i;
747       }
748     }
749
750     // Regardless of requested size, downscale to avoid exceeding the maximum texture size:
751     for( int i = scaleFactorIndex; i < numFactors; ++i )
752     {
753       // Continue downscaling to below maximum texture size (if possible)
754       scaleFactorIndex = i;
755
756       if( TJSCALED(postXformImageWidth,  (factors[i])) < MAX_TEXTURE_WIDTH &&
757           TJSCALED(postXformImageHeight, (factors[i])) < MAX_TEXTURE_HEIGHT )
758       {
759         // Current scale-factor downscales to below maximum texture size
760         break;
761       }
762     }
763
764     // We have finally chosen the scale-factor, return width/height values
765     if( scaleFactorIndex > 0 )
766     {
767       preXformImageWidth   = TJSCALED(preXformImageWidth,   (factors[scaleFactorIndex]));
768       preXformImageHeight  = TJSCALED(preXformImageHeight,  (factors[scaleFactorIndex]));
769       postXformImageWidth  = TJSCALED(postXformImageWidth,  (factors[scaleFactorIndex]));
770       postXformImageHeight = TJSCALED(postXformImageHeight, (factors[scaleFactorIndex]));
771     }
772   }
773
774   return success;
775 }
776
777 ExifData* LoadExifData( FILE* fp )
778 {
779   ExifData*     exifData=NULL;
780   ExifLoader*   exifLoader;
781   unsigned char dataBuffer[1024];
782
783   if( fseek( fp, 0, SEEK_SET ) )
784   {
785     DALI_LOG_ERROR("Error seeking to start of file\n");
786   }
787   else
788   {
789     exifLoader = exif_loader_new ();
790
791     while( !feof(fp) )
792     {
793       int size = fread( dataBuffer, 1, sizeof( dataBuffer ), fp );
794       if( size <= 0 )
795       {
796         break;
797       }
798       if( ! exif_loader_write( exifLoader, dataBuffer, size ) )
799       {
800         break;
801       }
802     }
803
804     exifData = exif_loader_get_data( exifLoader );
805     exif_loader_unref( exifLoader );
806   }
807
808   return exifData;
809 }
810
811 bool LoadJpegHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
812 {
813   unsigned int requiredWidth  = input.scalingParameters.dimensions.GetWidth();
814   unsigned int requiredHeight = input.scalingParameters.dimensions.GetHeight();
815   FILE* const fp = input.file;
816
817   bool success = false;
818   if( requiredWidth == 0 && requiredHeight == 0 )
819   {
820     success = LoadJpegHeader( fp, width, height );
821   }
822   else
823   {
824     // Double check we get the same width/height from the header
825     unsigned int headerWidth;
826     unsigned int headerHeight;
827     if( LoadJpegHeader( fp, headerWidth, headerHeight ) )
828     {
829       JPGFORM_CODE transform = JPGFORM_NONE;
830
831       if( input.reorientationRequested )
832       {
833         ExifAutoPtr exifData( LoadExifData( fp ) );
834         if( exifData.mData )
835         {
836           transform = ConvertExifOrientation(exifData.mData);
837         }
838
839         int preXformImageWidth = headerWidth;
840         int preXformImageHeight = headerHeight;
841         int postXformImageWidth = headerWidth;
842         int postXformImageHeight = headerHeight;
843
844         success = TransformSize( requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight );
845         if(success)
846         {
847           width = postXformImageWidth;
848           height = postXformImageHeight;
849         }
850       }
851       else
852       {
853         success = true;
854         width = headerWidth;
855         height = headerHeight;
856       }
857     }
858   }
859   return success;
860 }
861
862
863 } // namespace TizenPlatform
864
865 } // namespace Dali