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