Try to fix png crash issue
[platform/core/uifw/dali-adaptor.git] / platform-abstractions / tizen / image-loaders / loader-png.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 #include "loader-png.h"
19
20 #include <cstring>
21 #include <cstdlib>
22
23 #include <zlib.h>
24 #include <png.h>
25
26 #include <dali/integration-api/bitmap.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/public-api/images/image.h>
29 #include "dali/public-api/math/math-utils.h"
30 #include "dali/public-api/math/vector2.h"
31 #include "platform-capabilities.h"
32
33 namespace Dali
34 {
35
36 using Integration::Bitmap;
37 using Dali::Integration::PixelBuffer;
38
39 namespace TizenPlatform
40 {
41
42 namespace
43 {
44
45 // simple class to enforce clean-up of PNG structures
46 struct auto_png
47 {
48   auto_png(png_structp& _png, png_infop& _info)
49   : png(_png),
50     info(_info)
51   {
52   }
53
54   ~auto_png()
55   {
56     if(NULL != png)
57     {
58       png_destroy_read_struct(&png, &info, NULL);
59     }
60   }
61
62   png_structp& png;
63   png_infop& info;
64 }; // struct auto_png;
65
66 bool LoadPngHeader(FILE *fp, unsigned int &width, unsigned int &height, png_structp &png, png_infop &info)
67 {
68   png_byte header[8] = { 0 };
69
70   // Check header to see if it is a PNG file
71   size_t size = fread(header, 1, 8, fp);
72   if(size != 8)
73   {
74     return false;
75   }
76
77   if(png_sig_cmp(header, 0, 8))
78   {
79     return false;
80   }
81
82   png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
83
84   if(!png)
85   {
86     DALI_LOG_WARNING("Can't create PNG read structure\n");
87     return false;
88   }
89
90   info = png_create_info_struct(png);
91   if(!info)
92   {
93     DALI_LOG_WARNING("png_create_info_struct failed\n");
94     return false;
95   }
96
97   png_set_expand(png);
98
99   if(setjmp(png_jmpbuf(png)))
100   {
101     DALI_LOG_WARNING("error during png_init_io\n");
102     return false;
103   }
104
105   png_init_io(png, fp);
106   png_set_sig_bytes(png, 8);
107
108   // read image info
109   png_read_info(png, info);
110
111   // dimensions
112   width = png_get_image_width(png, info);
113   height = png_get_image_height(png, info);
114
115   return true;
116 }
117
118 } // namespace - anonymous
119
120 bool LoadPngHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
121 {
122   png_structp png = NULL;
123   png_infop info = NULL;
124   auto_png autoPng(png, info);
125
126   bool success = LoadPngHeader( input.file, width, height, png, info );
127
128   return success;
129 }
130
131 bool LoadBitmapFromPng( const ImageLoader::Input& input, Integration::Bitmap& bitmap )
132 {
133   png_structp png = NULL;
134   png_infop info = NULL;
135   auto_png autoPng(png, info);
136
137   /// @todo: consider parameters
138   unsigned int y;
139   unsigned int width, height;
140   unsigned char *pixels;
141   png_bytep *rows;
142   unsigned int bpp = 0; // bytes per pixel
143   bool valid = false;
144
145   // Load info from the header
146   if( !LoadPngHeader( input.file, width, height, png, info ) )
147   {
148     return false;
149   }
150
151   Pixel::Format pixelFormat = Pixel::RGBA8888;
152
153   // decide pixel format
154   unsigned int colordepth = png_get_bit_depth(png, info);
155
156   // Ask PNGLib to convert high precision images into something we can use:
157   if (colordepth == 16)
158   {
159     png_set_strip_16(png);
160     colordepth = 8;
161   }
162
163   png_byte colortype = png_get_color_type(png, info);
164
165   if(colortype == PNG_COLOR_TYPE_GRAY)
166   {
167     switch( colordepth )
168     {
169       case 8:
170       {
171         pixelFormat = Pixel::L8;
172         valid = true;
173         break;
174       }
175       default:
176       {
177         break;
178       }
179     }
180   }
181   else if(colortype == PNG_COLOR_TYPE_GRAY_ALPHA)
182   {
183     switch(colordepth)
184     {
185       case 8:
186       {
187         pixelFormat = Pixel::LA88;
188         valid = true;
189         break;
190       }
191       default:
192       {
193         break;
194       }
195     }
196   }
197   else if(colortype == PNG_COLOR_TYPE_RGB )
198   {
199     switch(colordepth)
200     {
201       case 8:
202       {
203         pixelFormat = Pixel::RGB888;
204         valid = true;
205         break;
206       }
207       case 5:      /// @todo is this correct for RGB16 5-6-5 ?
208       {
209         pixelFormat = Pixel::RGB565;
210         valid = true;
211         break;
212       }
213       default:
214       {
215         break;
216       }
217     }
218   }
219   else if(colortype == PNG_COLOR_TYPE_RGBA)
220   {
221     switch(colordepth)
222     {
223       case 8:
224       {
225         pixelFormat = Pixel::RGBA8888;
226         valid = true;
227         break;
228       }
229       default:
230       {
231         break;
232       }
233     }
234   }
235   else if(colortype == PNG_COLOR_TYPE_PALETTE)
236   {
237     switch(colordepth)
238     {
239       case 1:
240       {
241         pixelFormat = Pixel::LA88;
242         valid = true;
243         break;
244       }
245
246       case 2:
247       case 4:
248       case 8:
249       {
250         /* Expand paletted or RGB images with transparency to full alpha channels
251          * so the data will be available as RGBA quartets. PNG_INFO_tRNS = 0x10
252          */
253         if(png_get_valid(png, info, PNG_INFO_tRNS) == 0x10)
254         {
255           pixelFormat = Pixel::RGBA8888;
256           valid = true;
257         }
258         else
259         {
260           pixelFormat = Pixel::RGB888;
261           png_set_packing(png);
262           png_set_packswap(png);
263           png_set_palette_to_rgb(png);
264           valid = true;
265         }
266         break;
267       }
268       default:
269       {
270         break;
271       }
272     }
273   }
274
275   if( !valid )
276   {
277     DALI_LOG_WARNING( "Unsupported png format\n" );
278     return false;
279   }
280
281   // bytes per pixel
282   bpp = Pixel::GetBytesPerPixel(pixelFormat);
283
284   png_read_update_info(png, info);
285
286   if(setjmp(png_jmpbuf(png)))
287   {
288     DALI_LOG_WARNING("error during png_read_image\n");
289     return false;
290   }
291
292   unsigned int rowBytes = png_get_rowbytes(png, info);
293
294   unsigned int bufferWidth   = GetTextureDimension(width);
295   unsigned int bufferHeight  = GetTextureDimension(height);
296   unsigned int stride        = bufferWidth*bpp;
297
298   // not sure if this ever happens
299   if( rowBytes > stride )
300   {
301     stride = GetTextureDimension(rowBytes);
302
303     bpp = stride / bufferWidth;
304     switch(bpp)
305     {
306       case 3:
307         pixelFormat = Pixel::RGB888;
308         break;
309       case 4:
310         pixelFormat = Pixel::RGBA8888;
311         break;
312       default:
313         break;
314     }
315
316   }
317
318   // decode the whole image into bitmap buffer
319   pixels = bitmap.GetPackedPixelsProfile()->ReserveBuffer(pixelFormat, width, height, bufferWidth, bufferHeight);
320
321   DALI_ASSERT_DEBUG(pixels);
322   rows = reinterpret_cast< png_bytep* >( malloc(sizeof(png_bytep) * height) );
323   for(y=0; y<height; y++)
324   {
325     rows[y] = pixels + y * stride;
326   }
327
328   // decode image
329   png_read_image(png, rows);
330
331   free(rows);
332
333   return true;
334 }
335
336 // simple class to enforce clean-up of PNG structures
337 struct AutoPngWrite
338 {
339   AutoPngWrite(png_structp& _png, png_infop& _info)
340   : png(_png),
341     info(_info)
342   {
343   }
344
345   ~AutoPngWrite()
346   {
347     if(NULL != png)
348     {
349       png_destroy_write_struct(&png, &info);
350     }
351   }
352
353   png_structp& png;
354   png_infop& info;
355 }; // struct AutoPngWrite;
356
357 namespace
358 {
359   // Custom libpng write callbacks that buffer to a vector instead of a file:
360
361   /**
362    * extern "C" linkage is used because this is a callback that we pass to a C
363    * library which is part of the underlying platform and so potentially compiled
364    * as C rather than C++.
365    * @see http://stackoverflow.com/a/2594222
366    * */
367   extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length)
368   {
369     DALI_ASSERT_DEBUG(png_ptr && data);
370     if(!png_ptr || !data)
371     {
372       return;
373     }
374     // Make sure we don't try to propagate a C++ exception up the call stack of a pure C library:
375     try
376     {
377       // Recover our buffer for writing into:
378       Vector<unsigned char>* const encoded_img = static_cast< Vector<unsigned char>* >( png_get_io_ptr(png_ptr) );
379       if(encoded_img)
380       {
381         const Vector<unsigned char>::SizeType bufferSize = encoded_img->Count();
382         encoded_img->Resize( bufferSize + length ); //< Can throw OOM.
383         unsigned char* const bufferBack = encoded_img->Begin() + bufferSize;
384         memcpy(bufferBack, data, length);
385       }
386       else
387       {
388         DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.\n");
389       }
390     }
391     catch(...)
392     {
393       DALI_LOG_ERROR("C++ Exception caught\n");
394     }
395   }
396
397   /** Override the flush with a NOP to prevent libpng trying cstdlib file io. */
398   extern "C" void FlushData(png_structp png_ptr)
399   {
400 #ifdef DEBUG_ENABLED
401     Debug::LogMessage(Debug::DebugInfo, "PNG Flush");
402 #endif // DEBUG_ENABLED
403   }
404 }
405
406 /**
407  * Potential improvements:
408  * 1. Detect <= 256 colours and write in palette mode.
409  * 2. Detect grayscale (will early-out quickly for colour images).
410  * 3. Store colour space / gamma correction info related to the device screen?
411  *    http://www.libpng.org/pub/png/book/chapter10.html
412  * 4. Refactor with callers to write straight through to disk and save keeping a big buffer around.
413  * 5. Prealloc buffer (reserve) to input size / <A number greater than 2 (expexcted few realloc but without using lots of memory) | 1 (expected zero reallocs but using a lot of memory)>.
414  * 6. Set the modification time with png_set_tIME(png_ptr, info_ptr, mod_time);
415  * 7. If caller asks for no compression, bypass libpng and blat raw data to
416  *    disk, topped and tailed with header/tail blocks.
417  */
418 bool EncodeToPng( const unsigned char* const pixelBuffer, Vector<unsigned char>& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat )
419 {
420   // Translate pixel format enum:
421   int pngPixelFormat = -1;
422   unsigned pixelBytes = 0;
423   bool rgbaOrder = true;
424
425   // Account for RGB versus BGR and presence of alpha in input pixels:
426   switch( pixelFormat )
427   {
428     case Pixel::RGB888:
429     {
430       pngPixelFormat = PNG_COLOR_TYPE_RGB;
431       pixelBytes = 3;
432       break;
433     }
434     case Pixel::BGRA8888:
435     {
436       rgbaOrder = false;
437       ///! No break: fall through:
438     }
439     case Pixel::RGBA8888:
440     {
441       pngPixelFormat = PNG_COLOR_TYPE_RGB_ALPHA;
442       pixelBytes = 4;
443       break;
444     }
445     default:
446     {
447       DALI_LOG_ERROR( "Unsupported pixel format for encoding to PNG.\n" );
448       return false;
449     }
450   }
451
452   const int interlace = PNG_INTERLACE_NONE;
453
454   png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
455   if(!png_ptr)
456   {
457     return false;
458   }
459   /* Allocate/initialize the image information data.  REQUIRED */
460   png_infop info_ptr = png_create_info_struct( png_ptr );
461   if(!info_ptr)
462   {
463     png_destroy_write_struct(&png_ptr, NULL);
464     return false;
465   }
466
467   /* Set error handling.  REQUIRED if you aren't supplying your own
468    * error handling functions in the png_create_write_struct() call.
469    */
470   if(setjmp(png_jmpbuf(png_ptr)))
471   {
472     png_destroy_write_struct(&png_ptr, &info_ptr);
473     return false;
474   }
475
476   // Since we are going to write to memory instead of a file, lets provide
477   // libpng with a custom write function and ask it to pass back our
478   // Vector buffer each time it calls back to flush data to "file":
479   png_set_write_fn(png_ptr, &encodedPixels, WriteData, FlushData);
480
481   // png_set_compression_level( png_ptr, Z_BEST_COMPRESSION);
482   png_set_compression_level(png_ptr, Z_BEST_SPEED);
483   // png_set_compression_level( png_ptr, Z_NO_COMPRESSION); //! We could just generate png directly without libpng in this case.
484
485   // Explicitly limit the number of filters used per scanline to speed us up:
486   // png_set_filter(png_ptr, 0, PNG_FILTER_NONE); ///!ToDo: Try this once baseline profile is in place.
487        // PNG_FILTER_SUB   |
488        // PNG_FILTER_UP    |
489        // PNG_FILTER_AVE   |
490        // PNG_FILTER_PAETH |
491        // PNG_ALL_FILTERS);
492   // Play with Zlib parameters in optimisation phase:
493     // png_set_compression_mem_level(png_ptr, 8);
494     // png_set_compression_strategy(png_ptr,
495         // Z_DEFAULT_STRATEGY);
496     // png_set_compression_window_bits(png_ptr, 15);
497     // png_set_compression_method(png_ptr, 8);
498     // png_set_compression_buffer_size(png_ptr, 8192)
499
500   // Let lib_png know if the pixel bytes are in BGR(A) order:
501   if(!rgbaOrder)
502   {
503     png_set_bgr( png_ptr );
504   }
505
506   // Set the image information:
507   png_set_IHDR(png_ptr, info_ptr, width, height, 8,
508      pngPixelFormat, interlace,
509      PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
510
511   // Start to output the PNG data to our buffer:
512   png_write_info(png_ptr, info_ptr);
513
514   // Walk the rows:
515   const unsigned row_step = width * pixelBytes;
516   png_bytep row_ptr = const_cast<png_bytep>(pixelBuffer);
517   const png_bytep row_end = row_ptr + height * row_step;
518   for(; row_ptr < row_end; row_ptr += row_step)
519   {
520     png_write_row(png_ptr, row_ptr);
521   }
522
523   /* It is REQUIRED to call this to finish writing the rest of the file */
524   png_write_end(png_ptr, info_ptr);
525   /* Clean up after the write, and free any memory allocated */
526   png_destroy_write_struct(&png_ptr, &info_ptr);
527   return true;
528 }
529
530 } // namespace TizenPlatform
531
532 } // namespace Dali