2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "loader-png.h"
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"
36 using Integration::Bitmap;
37 using Dali::Integration::PixelBuffer;
39 namespace TizenPlatform
45 // simple class to enforce clean-up of PNG structures
48 auto_png(png_structp& _png, png_infop& _info)
58 png_destroy_read_struct(&png, &info, NULL);
64 }; // struct auto_png;
66 bool LoadPngHeader(FILE *fp, unsigned int &width, unsigned int &height, png_structp &png, png_infop &info)
68 png_byte header[8] = { 0 };
70 // Check header to see if it is a PNG file
71 size_t size = fread(header, 1, 8, fp);
77 if(png_sig_cmp(header, 0, 8))
82 png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
86 DALI_LOG_WARNING("Can't create PNG read structure\n");
90 info = png_create_info_struct(png);
93 DALI_LOG_WARNING("png_create_info_struct failed\n");
99 if(setjmp(png_jmpbuf(png)))
101 DALI_LOG_WARNING("error during png_init_io\n");
105 png_init_io(png, fp);
106 png_set_sig_bytes(png, 8);
109 png_read_info(png, info);
112 width = png_get_image_width(png, info);
113 height = png_get_image_height(png, info);
118 } // namespace - anonymous
120 bool LoadPngHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
122 png_structp png = NULL;
123 png_infop info = NULL;
124 auto_png autoPng(png, info);
126 bool success = LoadPngHeader( input.file, width, height, png, info );
131 bool LoadBitmapFromPng( const ResourceLoadingClient& client, const ImageLoader::Input& input, Integration::Bitmap& bitmap )
133 png_structp png = NULL;
134 png_infop info = NULL;
135 auto_png autoPng(png, info);
137 /// @todo: consider parameters
139 unsigned int width, height;
140 unsigned char *pixels;
142 unsigned int bpp = 0; // bytes per pixel
145 // Load info from the header
146 if( !LoadPngHeader( input.file, width, height, png, info ) )
151 Pixel::Format pixelFormat = Pixel::RGBA8888;
153 // decide pixel format
154 unsigned int colordepth = png_get_bit_depth(png, info);
156 // Ask PNGLib to convert high precision images into something we can use:
157 if (colordepth == 16)
159 png_set_strip_16(png);
163 png_byte colortype = png_get_color_type(png, info);
165 if(colortype == PNG_COLOR_TYPE_GRAY)
171 pixelFormat = Pixel::L8;
181 else if(colortype == PNG_COLOR_TYPE_GRAY_ALPHA)
187 pixelFormat = Pixel::LA88;
197 else if(colortype == PNG_COLOR_TYPE_RGB )
203 pixelFormat = Pixel::RGB888;
207 case 5: /// @todo is this correct for RGB16 5-6-5 ?
209 pixelFormat = Pixel::RGB565;
219 else if(colortype == PNG_COLOR_TYPE_RGBA)
225 pixelFormat = Pixel::RGBA8888;
235 else if(colortype == PNG_COLOR_TYPE_PALETTE)
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
246 if(png_get_valid(png, info, PNG_INFO_tRNS) == 0x10)
248 pixelFormat = Pixel::RGBA8888;
253 pixelFormat = Pixel::RGB888;
254 png_set_packing(png);
255 png_set_packswap(png);
256 png_set_palette_to_rgb(png);
270 DALI_LOG_WARNING( "Unsupported png format\n" );
275 bpp = Pixel::GetBytesPerPixel(pixelFormat);
277 png_read_update_info(png, info);
279 if(setjmp(png_jmpbuf(png)))
281 DALI_LOG_WARNING("error during png_read_image\n");
285 unsigned int rowBytes = png_get_rowbytes(png, info);
287 unsigned int bufferWidth = GetTextureDimension(width);
288 unsigned int bufferHeight = GetTextureDimension(height);
289 unsigned int stride = bufferWidth*bpp;
291 // not sure if this ever happens
292 if( rowBytes > stride )
294 stride = GetTextureDimension(rowBytes);
295 bufferWidth = stride / bpp;
298 // decode the whole image into bitmap buffer
299 pixels = bitmap.GetPackedPixelsProfile()->ReserveBuffer(pixelFormat, width, height, bufferWidth, bufferHeight);
301 DALI_ASSERT_DEBUG(pixels);
302 rows = (png_bytep*) malloc(sizeof(png_bytep) * height);
303 for(y=0; y<height; y++)
305 rows[y] = (png_byte*) (pixels + y * stride);
309 png_read_image(png, rows);
316 // simple class to enforce clean-up of PNG structures
319 AutoPngWrite(png_structp& _png, png_infop& _info)
323 DALI_ASSERT_DEBUG(&_png != 0 && &_info != 0);
330 png_destroy_write_struct(&png, &info);
336 }; // struct AutoPngWrite;
340 // Custom libpng write callbacks that buffer to a vector instead of a file:
343 * extern "C" linkage is used because this is a callback that we pass to a C
344 * library which is part of the underlying platform and so potentially compiled
345 * as C rather than C++.
346 * @see http://stackoverflow.com/a/2594222
348 extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length)
350 using Dali::TizenPlatform::PngBuffer;
351 DALI_ASSERT_DEBUG(png_ptr && data);
352 if(!png_ptr || !data)
356 // Make sure we don't try to propagate a C++ exception up the call stack of a pure C library:
358 // Recover our buffer for writing into:
359 PngBuffer* const encoded_img = (PngBuffer*) png_get_io_ptr(png_ptr);
362 const PngBuffer::size_type bufferSize = encoded_img->size();
363 encoded_img->resize(encoded_img->size() + length); //< Can throw OOM.
364 PngBuffer::value_type* const bufferBack = &((*encoded_img)[bufferSize]);
365 memcpy(bufferBack, data, length);
369 DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.");
373 DALI_LOG_ERROR("C++ Exception caught");
377 /** Override the flush with a NOP to prevent libpng trying cstdlib file io. */
378 extern "C" void FlushData(png_structp png_ptr)
381 Debug::LogMessage(Debug::DebugInfo, "PNG Flush");
382 #endif // DEBUG_ENABLED
387 * Potential improvements:
388 * 1. Detect <= 256 colours and write in palette mode.
389 * 2. Detect grayscale (will early-out quickly for colour images).
390 * 3. Store colour space / gamma correction info related to the device screen?
391 * http://www.libpng.org/pub/png/book/chapter10.html
392 * 4. Refactor with callers to write straight through to disk and save keeping a big buffer around.
393 * 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)>.
394 * 6. Set the modification time with png_set_tIME(png_ptr, info_ptr, mod_time);
395 * 7. If caller asks for no compression, bypass libpng and blat raw data to
396 * disk, topped and tailed with header/tail blocks.
398 bool EncodeToPng( const unsigned char* const pixelBuffer, PngBuffer& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat )
400 // Translate pixel format enum:
401 int pngPixelFormat = -1;
402 unsigned pixelBytes = 0;
403 bool rgbaOrder = true;
405 // Account for RGB versus BGR and presence of alpha in input pixels:
406 switch( pixelFormat )
410 pngPixelFormat = PNG_COLOR_TYPE_RGB;
414 case Pixel::BGRA8888:
417 ///! No break: fall through:
419 case Pixel::RGBA8888:
421 pngPixelFormat = PNG_COLOR_TYPE_RGB_ALPHA;
427 DALI_LOG_ERROR( "Unsupported pixel format for encoding to PNG." );
432 const int interlace = PNG_INTERLACE_NONE;
434 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
439 /* Allocate/initialize the image information data. REQUIRED */
440 png_infop info_ptr = png_create_info_struct( png_ptr );
443 png_destroy_write_struct(&png_ptr, NULL);
447 /* Set error handling. REQUIRED if you aren't supplying your own
448 * error handling functions in the png_create_write_struct() call.
450 if(setjmp(png_jmpbuf(png_ptr)))
452 png_destroy_write_struct(&png_ptr, &info_ptr);
456 // Since we are going to write to memory instead of a file, lets provide
457 // libpng with a custom write function and ask it to pass back our
458 // std::vector buffer each time it calls back to flush data to "file":
459 png_set_write_fn(png_ptr, &encodedPixels, WriteData, FlushData);
461 // png_set_compression_level( png_ptr, Z_BEST_COMPRESSION);
462 png_set_compression_level(png_ptr, Z_BEST_SPEED);
463 // png_set_compression_level( png_ptr, Z_NO_COMPRESSION); //! We could just generate png directly without libpng in this case.
465 // Explicitly limit the number of filters used per scanline to speed us up:
466 // png_set_filter(png_ptr, 0, PNG_FILTER_NONE); ///!ToDo: Try this once baseline profile is in place.
470 // PNG_FILTER_PAETH |
472 // Play with Zlib parameters in optimisation phase:
473 // png_set_compression_mem_level(png_ptr, 8);
474 // png_set_compression_strategy(png_ptr,
475 // Z_DEFAULT_STRATEGY);
476 // png_set_compression_window_bits(png_ptr, 15);
477 // png_set_compression_method(png_ptr, 8);
478 // png_set_compression_buffer_size(png_ptr, 8192)
480 // Let lib_png know if the pixel bytes are in BGR(A) order:
483 png_set_bgr( png_ptr );
486 // Set the image information:
487 png_set_IHDR(png_ptr, info_ptr, width, height, 8,
488 pngPixelFormat, interlace,
489 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
491 // Start to output the PNG data to our buffer:
492 png_write_info(png_ptr, info_ptr);
495 const unsigned row_step = width * pixelBytes;
496 png_bytep row_ptr = const_cast<png_bytep>(pixelBuffer);
497 const png_bytep row_end = row_ptr + height * row_step;
498 for(; row_ptr < row_end; row_ptr += row_step)
500 png_write_row(png_ptr, row_ptr);
503 /* It is REQUIRED to call this to finish writing the rest of the file */
504 png_write_end(png_ptr, info_ptr);
505 /* Clean up after the write, and free any memory allocated */
506 png_destroy_write_struct(&png_ptr, &info_ptr);
510 } // namespace TizenPlatform