80824ac410d8a59b8802c1703b3519f710a1d805
[platform/core/uifw/dali-adaptor.git] / dali / internal / imaging / common / image-loader.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 #include <dali/internal/imaging/common/image-loader.h>
18
19 #include <dali/devel-api/common/ref-counted-dali-vector.h>
20 #include <dali/internal/imaging/common/pixel-buffer-impl.h>
21
22 #include <dali/internal/imaging/common/loader-astc.h>
23 #include <dali/internal/imaging/common/loader-bmp.h>
24 #include <dali/internal/imaging/common/loader-gif.h>
25 #include <dali/internal/imaging/common/loader-ico.h>
26 #include <dali/internal/imaging/common/loader-jpeg.h>
27 #include <dali/internal/imaging/common/loader-ktx.h>
28 #include <dali/internal/imaging/common/loader-png.h>
29 #include <dali/internal/imaging/common/loader-wbmp.h>
30 #include <dali/internal/imaging/common/image-operations.h>
31 #include <dali/internal/imaging/common/image-loader-input.h>
32 #include <dali/internal/system/common/file-reader.h>
33
34 using namespace Dali::Integration;
35
36 namespace Dali
37 {
38 namespace TizenPlatform
39 {
40
41 namespace
42 {
43 typedef bool (*LoadBitmapFunction)( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& pixelData );
44 typedef bool (*LoadBitmapHeaderFunction)( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
45
46 #if defined(DEBUG_ENABLED)
47 Integration::Log::Filter* gLogFilter = Debug::Filter::New( Debug::Concise, false, "LOG_IMAGE_LOADING" );
48 #endif
49
50 /**
51  * Stores the magic bytes, and the loader and header functions used for each image loader.
52  */
53 struct BitmapLoader
54 {
55   unsigned char magicByte1;        ///< The first byte in the file should be this
56   unsigned char magicByte2;        ///< The second byte in the file should be this
57   LoadBitmapFunction loader;       ///< The function which decodes the file
58   LoadBitmapHeaderFunction header; ///< The function which decodes the header of the file
59   Bitmap::Profile profile;         ///< The kind of bitmap to be created
60                                    ///  (addressable packed pixels or an opaque compressed blob).
61 };
62
63 /**
64  * Enum for file formats, has to be in sync with BITMAP_LOADER_LOOKUP_TABLE
65  */
66 enum FileFormats
67 {
68   // Unknown file format
69   FORMAT_UNKNOWN = -1,
70
71   // formats that use magic bytes
72   FORMAT_PNG = 0,
73   FORMAT_JPEG,
74   FORMAT_BMP,
75   FORMAT_GIF,
76   FORMAT_KTX,
77   FORMAT_ASTC,
78   FORMAT_ICO,
79   FORMAT_MAGIC_BYTE_COUNT,
80
81   // formats after this one do not use magic bytes
82   FORMAT_WBMP = FORMAT_MAGIC_BYTE_COUNT,
83   FORMAT_TOTAL_COUNT
84 };
85
86 /**
87  * A lookup table containing all the bitmap loaders with the appropriate information.
88  * Has to be in sync with enum FileFormats
89  */
90 const BitmapLoader BITMAP_LOADER_LOOKUP_TABLE[FORMAT_TOTAL_COUNT] =
91 {
92   { Png::MAGIC_BYTE_1,  Png::MAGIC_BYTE_2,  LoadBitmapFromPng,  LoadPngHeader,  Bitmap::BITMAP_2D_PACKED_PIXELS },
93   { Jpeg::MAGIC_BYTE_1, Jpeg::MAGIC_BYTE_2, LoadBitmapFromJpeg, LoadJpegHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
94   { Bmp::MAGIC_BYTE_1,  Bmp::MAGIC_BYTE_2,  LoadBitmapFromBmp,  LoadBmpHeader,  Bitmap::BITMAP_2D_PACKED_PIXELS },
95   { Gif::MAGIC_BYTE_1,  Gif::MAGIC_BYTE_2,  LoadBitmapFromGif,  LoadGifHeader,  Bitmap::BITMAP_2D_PACKED_PIXELS },
96   { Ktx::MAGIC_BYTE_1,  Ktx::MAGIC_BYTE_2,  LoadBitmapFromKtx,  LoadKtxHeader,  Bitmap::BITMAP_COMPRESSED       },
97   { Astc::MAGIC_BYTE_1, Astc::MAGIC_BYTE_2, LoadBitmapFromAstc, LoadAstcHeader, Bitmap::BITMAP_COMPRESSED       },
98   { Ico::MAGIC_BYTE_1,  Ico::MAGIC_BYTE_2,  LoadBitmapFromIco,  LoadIcoHeader,  Bitmap::BITMAP_2D_PACKED_PIXELS },
99   { 0x0,                0x0,                LoadBitmapFromWbmp, LoadWbmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
100 };
101
102 const unsigned int MAGIC_LENGTH = 2;
103
104 /**
105  * This code tries to predict the file format from the filename to help with format picking.
106  */
107 struct FormatExtension
108 {
109   const std::string extension;
110   FileFormats format;
111 };
112
113 const FormatExtension FORMAT_EXTENSIONS[] =
114 {
115  { ".png",  FORMAT_PNG  },
116  { ".jpg",  FORMAT_JPEG },
117  { ".bmp",  FORMAT_BMP  },
118  { ".gif",  FORMAT_GIF  },
119  { ".ktx",  FORMAT_KTX  },
120  { ".astc", FORMAT_ASTC },
121  { ".ico",  FORMAT_ICO  },
122  { ".wbmp", FORMAT_WBMP }
123 };
124
125 const unsigned int FORMAT_EXTENSIONS_COUNT = sizeof(FORMAT_EXTENSIONS) / sizeof(FormatExtension);
126
127 FileFormats GetFormatHint( const std::string& filename )
128 {
129   FileFormats format = FORMAT_UNKNOWN;
130
131   for ( unsigned int i = 0; i < FORMAT_EXTENSIONS_COUNT; ++i )
132   {
133     unsigned int length = FORMAT_EXTENSIONS[i].extension.size();
134     if ( ( filename.size() > length ) &&
135          ( 0 == filename.compare( filename.size() - length, length, FORMAT_EXTENSIONS[i].extension ) ) )
136     {
137       format = FORMAT_EXTENSIONS[i].format;
138       break;
139     }
140   }
141
142   return format;
143 }
144
145 /**
146  * Checks the magic bytes of the file first to determine which Image decoder to use to decode the
147  * bitmap.
148  * @param[in]   fp      The file to decode
149  * @param[in]   format  Hint about what format to try first
150  * @param[out]  loader  Set with the function to use to decode the image
151  * @param[out]  header  Set with the function to use to decode the header
152  * @param[out]  profile The kind of bitmap to hold the bits loaded for the bitmap.
153  * @return true, if we can decode the image, false otherwise
154  */
155 bool GetBitmapLoaderFunctions( FILE *fp,
156                                FileFormats format,
157                                LoadBitmapFunction& loader,
158                                LoadBitmapHeaderFunction& header,
159                                Bitmap::Profile& profile )
160 {
161   unsigned char magic[MAGIC_LENGTH];
162   size_t read = fread(magic, sizeof(unsigned char), MAGIC_LENGTH, fp);
163
164   // Reset to the start of the file.
165   if( fseek(fp, 0, SEEK_SET) )
166   {
167     DALI_LOG_ERROR("Error seeking to start of file\n");
168   }
169
170   if (read != MAGIC_LENGTH)
171   {
172     return false;
173   }
174
175   bool loaderFound = false;
176   const BitmapLoader *lookupPtr = BITMAP_LOADER_LOOKUP_TABLE;
177   ImageLoader::Input defaultInput( fp );
178
179   // try hinted format first
180   if ( format != FORMAT_UNKNOWN )
181   {
182     lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + format;
183     if ( format >= FORMAT_MAGIC_BYTE_COUNT ||
184          ( lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1] ) )
185     {
186       unsigned int width = 0;
187       unsigned int height = 0;
188       loaderFound = lookupPtr->header( fp, width, height );
189     }
190   }
191
192   // then try to get a match with formats that have magic bytes
193   if ( false == loaderFound )
194   {
195     for ( lookupPtr = BITMAP_LOADER_LOOKUP_TABLE;
196           lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT;
197           ++lookupPtr )
198     {
199       if ( lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1] )
200       {
201         // to seperate ico file format and wbmp file format
202         unsigned int width = 0;
203         unsigned int height = 0;
204         loaderFound = lookupPtr->header(fp, width, height);
205       }
206       if (loaderFound)
207       {
208         break;
209       }
210     }
211   }
212
213   // finally try formats that do not use magic bytes
214   if ( false == loaderFound )
215   {
216     for ( lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT;
217           lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_TOTAL_COUNT;
218           ++lookupPtr )
219     {
220       // to seperate ico file format and wbmp file format
221       unsigned int width = 0;
222       unsigned int height = 0;
223       loaderFound = lookupPtr->header(fp, width, height);
224       if (loaderFound)
225       {
226         break;
227       }
228     }
229   }
230
231   // if a loader was found set the outputs
232   if ( loaderFound )
233   {
234     loader  = lookupPtr->loader;
235     header  = lookupPtr->header;
236     profile = lookupPtr->profile;
237   }
238
239   // Reset to the start of the file.
240   if( fseek(fp, 0, SEEK_SET) )
241   {
242     DALI_LOG_ERROR("Error seeking to start of file\n");
243   }
244
245   return loaderFound;
246 }
247
248 } // anonymous namespace
249
250
251 namespace ImageLoader
252 {
253
254 bool ConvertStreamToBitmap( const BitmapResourceType& resource, std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer )
255 {
256   DALI_LOG_TRACE_METHOD( gLogFilter );
257
258   bool result = false;
259
260   if (fp != NULL)
261   {
262     LoadBitmapFunction function;
263     LoadBitmapHeaderFunction header;
264
265     Bitmap::Profile profile;
266
267     if ( GetBitmapLoaderFunctions( fp,
268                                    GetFormatHint( path ),
269                                    function,
270                                    header,
271                                    profile ) )
272     {
273       const ScalingParameters scalingParameters( resource.size, resource.scalingMode, resource.samplingMode );
274       const ImageLoader::Input input( fp, scalingParameters, resource.orientationCorrection );
275
276       // Run the image type decoder:
277       result = function( input, pixelBuffer );
278
279       if (!result)
280       {
281         DALI_LOG_WARNING( "Unable to convert %s\n", path.c_str() );
282         pixelBuffer.Reset();
283       }
284
285       pixelBuffer = Internal::Platform::ApplyAttributesToBitmap( pixelBuffer, resource.size, resource.scalingMode, resource.samplingMode );
286     }
287     else
288     {
289       DALI_LOG_WARNING( "Image Decoder for %s unavailable\n", path.c_str() );
290     }
291   }
292
293   return result;
294 }
295
296 ResourcePointer LoadImageSynchronously( const Integration::BitmapResourceType& resource, const std::string& path )
297 {
298   ResourcePointer result;
299   Dali::Devel::PixelBuffer bitmap;
300
301   Internal::Platform::FileReader fileReader( path );
302   FILE * const fp = fileReader.GetFile();
303   if( fp != NULL )
304   {
305     bool success = ConvertStreamToBitmap(resource, path, fp, bitmap);
306     if (success && bitmap)
307     {
308       Bitmap::Profile profile{Bitmap::Profile::BITMAP_2D_PACKED_PIXELS};
309
310       // For backward compatibility the Bitmap must be created
311       auto retval = Bitmap::New(profile, Dali::ResourcePolicy::OWNED_DISCARD);
312
313       DALI_LOG_SET_OBJECT_STRING( retval, path );
314
315       retval->GetPackedPixelsProfile()->ReserveBuffer(
316               bitmap.GetPixelFormat(),
317               bitmap.GetWidth(),
318               bitmap.GetHeight(),
319               bitmap.GetWidth(),
320               bitmap.GetHeight()
321             );
322
323       auto& impl = Dali::GetImplementation(bitmap);
324
325       std::copy( impl.GetBuffer(), impl.GetBuffer()+impl.GetBufferSize(), retval->GetBuffer());
326       result.Reset(retval);
327     }
328   }
329   return result;
330 }
331
332 ///@ToDo: Rename GetClosestImageSize() functions. Make them use the orientation correction and scaling information. Requires jpeg loader to tell us about reorientation. [Is there still a requirement for this functionality at all?]
333 ImageDimensions  GetClosestImageSize( const std::string& filename,
334                                       ImageDimensions size,
335                                       FittingMode::Type fittingMode,
336                                       SamplingMode::Type samplingMode,
337                                       bool orientationCorrection )
338 {
339   unsigned int width = 0;
340   unsigned int height = 0;
341
342   Internal::Platform::FileReader fileReader( filename );
343   FILE *fp = fileReader.GetFile();
344   if (fp != NULL)
345   {
346     LoadBitmapFunction loaderFunction;
347     LoadBitmapHeaderFunction headerFunction;
348     Bitmap::Profile profile;
349
350     if ( GetBitmapLoaderFunctions( fp,
351                                    GetFormatHint(filename),
352                                    loaderFunction,
353                                    headerFunction,
354                                    profile ) )
355     {
356       const ImageLoader::Input input( fp, ScalingParameters( size, fittingMode, samplingMode ), orientationCorrection );
357
358       const bool read_res = headerFunction( input, width, height );
359       if(!read_res)
360       {
361         DALI_LOG_WARNING("Image Decoder failed to read header for %s\n", filename.c_str());
362       }
363     }
364     else
365     {
366       DALI_LOG_WARNING("Image Decoder for %s unavailable\n", filename.c_str());
367     }
368   }
369   return ImageDimensions( width, height );
370 }
371
372 ImageDimensions GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
373                                      ImageDimensions size,
374                                      FittingMode::Type fittingMode,
375                                      SamplingMode::Type samplingMode,
376                                      bool orientationCorrection )
377 {
378   unsigned int width = 0;
379   unsigned int height = 0;
380
381   // Get the blob of binary data that we need to decode:
382   DALI_ASSERT_DEBUG( resourceBuffer );
383   Dali::RefCountedVector<uint8_t>* const encodedBlob = reinterpret_cast<Dali::RefCountedVector<uint8_t>*>( resourceBuffer.Get() );
384
385   if( encodedBlob != 0 )
386   {
387     if( encodedBlob->GetVector().Size() )
388     {
389       // Open a file handle on the memory buffer:
390       Internal::Platform::FileReader fileReader( encodedBlob->GetVector() );
391       FILE *fp = fileReader.GetFile();
392       if ( fp != NULL )
393       {
394         LoadBitmapFunction loaderFunction;
395         LoadBitmapHeaderFunction headerFunction;
396         Bitmap::Profile profile;
397
398         if ( GetBitmapLoaderFunctions( fp,
399                                        FORMAT_UNKNOWN,
400                                        loaderFunction,
401                                        headerFunction,
402                                        profile ) )
403         {
404           const ImageLoader::Input input( fp, ScalingParameters( size, fittingMode, samplingMode ), orientationCorrection );
405           const bool read_res = headerFunction( input, width, height );
406           if( !read_res )
407           {
408             DALI_LOG_WARNING( "Image Decoder failed to read header for resourceBuffer\n" );
409           }
410         }
411       }
412     }
413   }
414   return ImageDimensions( width, height );
415 }
416
417 } // ImageLoader
418 } // TizenPlatform
419 } // Dali