[4.0] support 1, 2, 4 bit depths about PNG_COLOR_TYPE_GRAY
[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       colortype == PNG_COLOR_TYPE_GRAY_ALPHA )
167   {
168     if( png_get_valid(png, info, PNG_INFO_tRNS) )
169     {
170       colortype = PNG_COLOR_TYPE_GRAY_ALPHA;
171       /* expand transparency entry -> alpha channel if present */
172       png_set_tRNS_to_alpha(png);
173       pixelFormat = Pixel::LA88;
174     }
175     else
176     {
177       colortype = PNG_COLOR_TYPE_GRAY;
178       pixelFormat = Pixel::L8;
179     }
180
181     if( colordepth < 8 )
182     {
183       /* expand gray (w/reduced bits) -> 8-bit RGB if necessary */
184       png_set_expand_gray_1_2_4_to_8(png);
185       /* pack all pixels to byte boundaries */
186       png_set_packing(png);
187     }
188     valid = true;
189   }
190   else if(colortype == PNG_COLOR_TYPE_RGB )
191   {
192     switch(colordepth)
193     {
194       case 8:
195       {
196         pixelFormat = Pixel::RGB888;
197         valid = true;
198         break;
199       }
200       case 5:      /// @todo is this correct for RGB16 5-6-5 ?
201       {
202         pixelFormat = Pixel::RGB565;
203         valid = true;
204         break;
205       }
206       default:
207       {
208         break;
209       }
210     }
211   }
212   else if(colortype == PNG_COLOR_TYPE_RGBA)
213   {
214     switch(colordepth)
215     {
216       case 8:
217       {
218         pixelFormat = Pixel::RGBA8888;
219         valid = true;
220         break;
221       }
222       default:
223       {
224         break;
225       }
226     }
227   }
228   else if(colortype == PNG_COLOR_TYPE_PALETTE)
229   {
230     switch(colordepth)
231     {
232       case 1:
233       {
234         pixelFormat = Pixel::LA88;
235         valid = true;
236         break;
237       }
238
239       case 2:
240       case 4:
241       case 8:
242       {
243         /* Expand paletted or RGB images with transparency to full alpha channels
244          * so the data will be available as RGBA quartets. PNG_INFO_tRNS = 0x10
245          */
246         if(png_get_valid(png, info, PNG_INFO_tRNS) == 0x10)
247         {
248           pixelFormat = Pixel::RGBA8888;
249           valid = true;
250         }
251         else
252         {
253           pixelFormat = Pixel::RGB888;
254           png_set_packing(png);
255           png_set_packswap(png);
256           png_set_palette_to_rgb(png);
257           valid = true;
258         }
259         break;
260       }
261       default:
262       {
263         break;
264       }
265     }
266   }
267
268   if( !valid )
269   {
270     DALI_LOG_WARNING( "Unsupported png format\n" );
271     return false;
272   }
273
274   // bytes per pixel
275   bpp = Pixel::GetBytesPerPixel(pixelFormat);
276
277   png_read_update_info(png, info);
278
279   if(setjmp(png_jmpbuf(png)))
280   {
281     DALI_LOG_WARNING("error during png_read_image\n");
282     return false;
283   }
284
285   unsigned int rowBytes = png_get_rowbytes(png, info);
286
287   unsigned int bufferWidth   = GetTextureDimension(width);
288   unsigned int bufferHeight  = GetTextureDimension(height);
289   unsigned int stride        = bufferWidth*bpp;
290
291   // not sure if this ever happens
292   if( rowBytes > stride )
293   {
294     stride = GetTextureDimension(rowBytes);
295
296     bpp = stride / bufferWidth;
297     switch(bpp)
298     {
299       case 3:
300         pixelFormat = Pixel::RGB888;
301         break;
302       case 4:
303         pixelFormat = Pixel::RGBA8888;
304         break;
305       default:
306         break;
307     }
308
309   }
310
311   // decode the whole image into bitmap buffer
312   pixels = bitmap.GetPackedPixelsProfile()->ReserveBuffer(pixelFormat, width, height, bufferWidth, bufferHeight);
313
314   DALI_ASSERT_DEBUG(pixels);
315   rows = reinterpret_cast< png_bytep* >( malloc(sizeof(png_bytep) * height) );
316   for(y=0; y<height; y++)
317   {
318     rows[y] = pixels + y * stride;
319   }
320
321   // decode image
322   png_read_image(png, rows);
323
324   free(rows);
325
326   return true;
327 }
328
329 // simple class to enforce clean-up of PNG structures
330 struct AutoPngWrite
331 {
332   AutoPngWrite(png_structp& _png, png_infop& _info)
333   : png(_png),
334     info(_info)
335   {
336   }
337
338   ~AutoPngWrite()
339   {
340     if(NULL != png)
341     {
342       png_destroy_write_struct(&png, &info);
343     }
344   }
345
346   png_structp& png;
347   png_infop& info;
348 }; // struct AutoPngWrite;
349
350 namespace
351 {
352   // Custom libpng write callbacks that buffer to a vector instead of a file:
353
354   /**
355    * extern "C" linkage is used because this is a callback that we pass to a C
356    * library which is part of the underlying platform and so potentially compiled
357    * as C rather than C++.
358    * @see http://stackoverflow.com/a/2594222
359    * */
360   extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length)
361   {
362     DALI_ASSERT_DEBUG(png_ptr && data);
363     if(!png_ptr || !data)
364     {
365       return;
366     }
367     // Make sure we don't try to propagate a C++ exception up the call stack of a pure C library:
368     try
369     {
370       // Recover our buffer for writing into:
371       Vector<unsigned char>* const encoded_img = static_cast< Vector<unsigned char>* >( png_get_io_ptr(png_ptr) );
372       if(encoded_img)
373       {
374         const Vector<unsigned char>::SizeType bufferSize = encoded_img->Count();
375         encoded_img->Resize( bufferSize + length ); //< Can throw OOM.
376         unsigned char* const bufferBack = encoded_img->Begin() + bufferSize;
377         memcpy(bufferBack, data, length);
378       }
379       else
380       {
381         DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.\n");
382       }
383     }
384     catch(...)
385     {
386       DALI_LOG_ERROR("C++ Exception caught\n");
387     }
388   }
389
390   /** Override the flush with a NOP to prevent libpng trying cstdlib file io. */
391   extern "C" void FlushData(png_structp png_ptr)
392   {
393 #ifdef DEBUG_ENABLED
394     Debug::LogMessage(Debug::DebugInfo, "PNG Flush");
395 #endif // DEBUG_ENABLED
396   }
397 }
398
399 /**
400  * Potential improvements:
401  * 1. Detect <= 256 colours and write in palette mode.
402  * 2. Detect grayscale (will early-out quickly for colour images).
403  * 3. Store colour space / gamma correction info related to the device screen?
404  *    http://www.libpng.org/pub/png/book/chapter10.html
405  * 4. Refactor with callers to write straight through to disk and save keeping a big buffer around.
406  * 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)>.
407  * 6. Set the modification time with png_set_tIME(png_ptr, info_ptr, mod_time);
408  * 7. If caller asks for no compression, bypass libpng and blat raw data to
409  *    disk, topped and tailed with header/tail blocks.
410  */
411 bool EncodeToPng( const unsigned char* const pixelBuffer, Vector<unsigned char>& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat )
412 {
413   // Translate pixel format enum:
414   int pngPixelFormat = -1;
415   unsigned pixelBytes = 0;
416   bool rgbaOrder = true;
417
418   // Account for RGB versus BGR and presence of alpha in input pixels:
419   switch( pixelFormat )
420   {
421     case Pixel::RGB888:
422     {
423       pngPixelFormat = PNG_COLOR_TYPE_RGB;
424       pixelBytes = 3;
425       break;
426     }
427     case Pixel::BGRA8888:
428     {
429       rgbaOrder = false;
430       ///! No break: fall through:
431     }
432     case Pixel::RGBA8888:
433     {
434       pngPixelFormat = PNG_COLOR_TYPE_RGB_ALPHA;
435       pixelBytes = 4;
436       break;
437     }
438     default:
439     {
440       DALI_LOG_ERROR( "Unsupported pixel format for encoding to PNG.\n" );
441       return false;
442     }
443   }
444
445   const int interlace = PNG_INTERLACE_NONE;
446
447   png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
448   if(!png_ptr)
449   {
450     return false;
451   }
452   /* Allocate/initialize the image information data.  REQUIRED */
453   png_infop info_ptr = png_create_info_struct( png_ptr );
454   if(!info_ptr)
455   {
456     png_destroy_write_struct(&png_ptr, NULL);
457     return false;
458   }
459
460   /* Set error handling.  REQUIRED if you aren't supplying your own
461    * error handling functions in the png_create_write_struct() call.
462    */
463   if(setjmp(png_jmpbuf(png_ptr)))
464   {
465     png_destroy_write_struct(&png_ptr, &info_ptr);
466     return false;
467   }
468
469   // Since we are going to write to memory instead of a file, lets provide
470   // libpng with a custom write function and ask it to pass back our
471   // Vector buffer each time it calls back to flush data to "file":
472   png_set_write_fn(png_ptr, &encodedPixels, WriteData, FlushData);
473
474   // png_set_compression_level( png_ptr, Z_BEST_COMPRESSION);
475   png_set_compression_level(png_ptr, Z_BEST_SPEED);
476   // png_set_compression_level( png_ptr, Z_NO_COMPRESSION); //! We could just generate png directly without libpng in this case.
477
478   // Explicitly limit the number of filters used per scanline to speed us up:
479   // png_set_filter(png_ptr, 0, PNG_FILTER_NONE); ///!ToDo: Try this once baseline profile is in place.
480        // PNG_FILTER_SUB   |
481        // PNG_FILTER_UP    |
482        // PNG_FILTER_AVE   |
483        // PNG_FILTER_PAETH |
484        // PNG_ALL_FILTERS);
485   // Play with Zlib parameters in optimisation phase:
486     // png_set_compression_mem_level(png_ptr, 8);
487     // png_set_compression_strategy(png_ptr,
488         // Z_DEFAULT_STRATEGY);
489     // png_set_compression_window_bits(png_ptr, 15);
490     // png_set_compression_method(png_ptr, 8);
491     // png_set_compression_buffer_size(png_ptr, 8192)
492
493   // Let lib_png know if the pixel bytes are in BGR(A) order:
494   if(!rgbaOrder)
495   {
496     png_set_bgr( png_ptr );
497   }
498
499   // Set the image information:
500   png_set_IHDR(png_ptr, info_ptr, width, height, 8,
501      pngPixelFormat, interlace,
502      PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
503
504   // Start to output the PNG data to our buffer:
505   png_write_info(png_ptr, info_ptr);
506
507   // Walk the rows:
508   const unsigned row_step = width * pixelBytes;
509   png_bytep row_ptr = const_cast<png_bytep>(pixelBuffer);
510   const png_bytep row_end = row_ptr + height * row_step;
511   for(; row_ptr < row_end; row_ptr += row_step)
512   {
513     png_write_row(png_ptr, row_ptr);
514   }
515
516   /* It is REQUIRED to call this to finish writing the rest of the file */
517   png_write_end(png_ptr, info_ptr);
518   /* Clean up after the write, and free any memory allocated */
519   png_destroy_write_struct(&png_ptr, &info_ptr);
520   return true;
521 }
522
523 } // namespace TizenPlatform
524
525 } // namespace Dali