llpngwrapper.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /**
  2. * @file llpngwrapper.cpp
  3. * @brief Encapsulates libpng read/write functionality.
  4. *
  5. * $LicenseInfo:firstyear=2007&license=viewergpl$
  6. *
  7. * Copyright (c) 2007-2009, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * $/LicenseInfo$
  31. */
  32. #include "linden_common.h"
  33. #include "llpngwrapper.h"
  34. // ---------------------------------------------------------------------------
  35. // LLPngWrapper
  36. // ---------------------------------------------------------------------------
  37. LLPngWrapper::LLPngWrapper()
  38. : mReadPngPtr(NULL),
  39. mReadInfoPtr(NULL),
  40. mWritePngPtr(NULL),
  41. mWriteInfoPtr(NULL),
  42. mRowPointers(NULL),
  43. mWidth(0),
  44. mHeight(0),
  45. mBitDepth(0),
  46. mColorType(0),
  47. mChannels(0),
  48. mInterlaceType(0),
  49. mCompressionType(0),
  50. mFilterMethod(0),
  51. mFinalSize(0),
  52. mGamma(0.f)
  53. {
  54. }
  55. LLPngWrapper::~LLPngWrapper()
  56. {
  57. releaseResources();
  58. }
  59. // Checks the src for a valid PNG header
  60. bool LLPngWrapper::isValidPng(U8* src)
  61. {
  62. constexpr int PNG_BYTES_TO_CHECK = 8;
  63. int sig = png_sig_cmp((png_bytep)src, (png_size_t)0, PNG_BYTES_TO_CHECK);
  64. if (sig != 0)
  65. {
  66. mErrorMessage = "Invalid or corrupt PNG file";
  67. return false;
  68. }
  69. return true;
  70. }
  71. // Called by the libpng library when a fatal encoding or decoding error occurs.
  72. // We simply throw the error message and let our try/catch lock clean up.
  73. void LLPngWrapper::errorHandler(png_structp png_ptr, png_const_charp msg)
  74. {
  75. throw msg;
  76. }
  77. // Called by the libpng library when reading (decoding) the PNG file. We copy
  78. // the PNG data from our internal buffer into the PNG's data buffer.
  79. void LLPngWrapper::readDataCallback(png_structp png_ptr, png_bytep dest,
  80. png_size_t length)
  81. {
  82. PngDataInfo* dataInfo = (PngDataInfo*)png_get_io_ptr(png_ptr);
  83. if (S32(dataInfo->mOffset + length) > dataInfo->mDataSize)
  84. {
  85. png_error(png_ptr,
  86. "Data read error. Requested data size exceeds available data size.");
  87. return;
  88. }
  89. U8* src = &dataInfo->mData[dataInfo->mOffset];
  90. memcpy(dest, src, length);
  91. dataInfo->mOffset += static_cast<U32>(length);
  92. }
  93. // Called by the libpng library when writing (encoding) the PNG file. We copy
  94. // the encoded result into our data buffer.
  95. void LLPngWrapper::writeDataCallback(png_structp png_ptr, png_bytep src,
  96. png_size_t length)
  97. {
  98. PngDataInfo* dataInfo = (PngDataInfo*)png_get_io_ptr(png_ptr);
  99. U8* dest = &dataInfo->mData[dataInfo->mOffset];
  100. memcpy(dest, src, length);
  101. dataInfo->mOffset += static_cast<U32>(length);
  102. }
  103. // Read the PNG file using the libpng. The low level interface is used here
  104. // because we want to do various transformations (including setting applying
  105. // gamma) which cannot be done with the high-level interface. The scanline also
  106. // begins at the bottom of the image (per SecondLife conventions) instead of at
  107. // the top, so we must assign row-pointers in "reverse" order.
  108. bool LLPngWrapper::readPng(U8* src, S32 data_size, LLImageRaw* raw_image,
  109. ImageInfo* infop)
  110. {
  111. try
  112. {
  113. // Create and initialize the png structures
  114. mReadPngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  115. this, &errorHandler, NULL);
  116. if (mReadPngPtr == NULL)
  117. {
  118. #if 0
  119. throw "Problem creating png read structure";
  120. #else
  121. mErrorMessage = "Problem creating png read structure";
  122. releaseResources();
  123. return false;
  124. #endif
  125. }
  126. // Allocate/initialize the memory for image information.
  127. mReadInfoPtr = png_create_info_struct(mReadPngPtr);
  128. // Set up the input control
  129. PngDataInfo dataPtr;
  130. dataPtr.mData = src;
  131. dataPtr.mOffset = 0;
  132. dataPtr.mDataSize = data_size;
  133. png_set_read_fn(mReadPngPtr, &dataPtr, &readDataCallback);
  134. png_set_sig_bytes(mReadPngPtr, 0);
  135. // Set up low-level read and get header information
  136. png_read_info(mReadPngPtr, mReadInfoPtr);
  137. png_get_IHDR(mReadPngPtr, mReadInfoPtr, &mWidth, &mHeight,
  138. &mBitDepth, &mColorType, &mInterlaceType,
  139. &mCompressionType, &mFilterMethod);
  140. // Normalize the image, then get updated image information after
  141. // transformations have been applied
  142. normalizeImage();
  143. updateMetaData();
  144. // If a raw object is supplied, read the PNG image into its data space
  145. if (raw_image)
  146. {
  147. if (!raw_image->resize(static_cast<U16>(mWidth),
  148. static_cast<U16>(mHeight), mChannels))
  149. {
  150. mErrorMessage = "Out of memory";
  151. releaseResources();
  152. return false;
  153. }
  154. U8* dest = raw_image->getData();
  155. int offset = mWidth * mChannels;
  156. // Set up the row pointers and read the image
  157. mRowPointers = new (std::nothrow) U8*[mHeight];
  158. if (mRowPointers == NULL)
  159. {
  160. mErrorMessage = "Out of memory";
  161. releaseResources();
  162. return false;
  163. }
  164. for (U32 i = 0; i < mHeight; ++i)
  165. {
  166. mRowPointers[i] = &dest[(mHeight - i - 1) * offset];
  167. }
  168. png_read_image(mReadPngPtr, mRowPointers);
  169. // Finish up, ensures all metadata are updated
  170. png_read_end(mReadPngPtr, NULL);
  171. }
  172. // If an info object is supplied, copy the relevant info
  173. if (infop)
  174. {
  175. infop->mHeight = static_cast<U16>(mHeight);
  176. infop->mWidth = static_cast<U16>(mWidth);
  177. infop->mComponents = mChannels;
  178. }
  179. mFinalSize = dataPtr.mOffset;
  180. }
  181. catch (png_const_charp msg)
  182. {
  183. mErrorMessage = msg;
  184. releaseResources();
  185. return false;
  186. }
  187. // Clean up and return
  188. releaseResources();
  189. return true;
  190. }
  191. // Do transformations to normalize the input to 8-bpp RGBA
  192. void LLPngWrapper::normalizeImage()
  193. {
  194. // 1. Expand any palettes
  195. // 2. Convert grayscales to RGB
  196. // 3. Create alpha layer from transparency
  197. // 4. Ensure 8-bpp for all images
  198. // 5. Set (or guess) gamma
  199. if (mColorType == PNG_COLOR_TYPE_PALETTE)
  200. {
  201. png_set_palette_to_rgb(mReadPngPtr);
  202. }
  203. if (mColorType == PNG_COLOR_TYPE_GRAY && mBitDepth < 8)
  204. {
  205. png_set_expand_gray_1_2_4_to_8(mReadPngPtr);
  206. }
  207. if (mColorType == PNG_COLOR_TYPE_GRAY ||
  208. mColorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  209. {
  210. png_set_gray_to_rgb(mReadPngPtr);
  211. }
  212. if (png_get_valid(mReadPngPtr, mReadInfoPtr, PNG_INFO_tRNS))
  213. {
  214. png_set_tRNS_to_alpha(mReadPngPtr);
  215. }
  216. if (mBitDepth < 8)
  217. {
  218. png_set_packing(mReadPngPtr);
  219. }
  220. else if (mBitDepth == 16)
  221. {
  222. png_set_strip_16(mReadPngPtr);
  223. }
  224. #if LL_DARWIN
  225. constexpr F64 SCREEN_GAMMA = 1.8;
  226. #else
  227. constexpr F64 SCREEN_GAMMA = 2.2;
  228. #endif
  229. if (png_get_gAMA(mReadPngPtr, mReadInfoPtr, &mGamma))
  230. {
  231. png_set_gamma(mReadPngPtr, SCREEN_GAMMA, mGamma);
  232. }
  233. else
  234. {
  235. png_set_gamma(mReadPngPtr, SCREEN_GAMMA, 1/SCREEN_GAMMA);
  236. }
  237. }
  238. // Read out the image meta-data
  239. void LLPngWrapper::updateMetaData()
  240. {
  241. png_read_update_info(mReadPngPtr, mReadInfoPtr);
  242. mWidth = png_get_image_width(mReadPngPtr, mReadInfoPtr);
  243. mHeight = png_get_image_height(mReadPngPtr, mReadInfoPtr);
  244. mBitDepth = png_get_bit_depth(mReadPngPtr, mReadInfoPtr);
  245. mColorType = png_get_color_type(mReadPngPtr, mReadInfoPtr);
  246. mChannels = png_get_channels(mReadPngPtr, mReadInfoPtr);
  247. }
  248. // Method to write raw image into PNG at dest. The raw scanline begins at the
  249. // bottom of the image per SecondLife conventions.
  250. bool LLPngWrapper::writePng(const LLImageRaw* raw_image, U8* dest)
  251. {
  252. try
  253. {
  254. S8 numComponents = raw_image->getComponents();
  255. switch (numComponents)
  256. {
  257. case 1:
  258. mColorType = PNG_COLOR_TYPE_GRAY;
  259. break;
  260. case 2:
  261. mColorType = PNG_COLOR_TYPE_GRAY_ALPHA;
  262. break;
  263. case 3:
  264. mColorType = PNG_COLOR_TYPE_RGB;
  265. break;
  266. case 4:
  267. mColorType = PNG_COLOR_TYPE_RGB_ALPHA;
  268. break;
  269. default:
  270. mColorType = -1;
  271. }
  272. if (mColorType == -1)
  273. {
  274. throw "Unsupported image: unexpected number of channels";
  275. }
  276. mWritePngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  277. NULL, &errorHandler, NULL);
  278. if (!mWritePngPtr)
  279. {
  280. throw "Problem creating png write structure";
  281. }
  282. mWriteInfoPtr = png_create_info_struct(mWritePngPtr);
  283. // Setup write function
  284. PngDataInfo dataPtr;
  285. dataPtr.mData = dest;
  286. dataPtr.mOffset = 0;
  287. png_set_write_fn(mWritePngPtr, &dataPtr, &writeDataCallback, &writeFlush);
  288. // Setup image params
  289. mWidth = raw_image->getWidth();
  290. mHeight = raw_image->getHeight();
  291. mBitDepth = 8; // Fixed to 8-bpp in SL
  292. mChannels = numComponents;
  293. mInterlaceType = PNG_INTERLACE_NONE;
  294. mCompressionType = PNG_COMPRESSION_TYPE_DEFAULT;
  295. mFilterMethod = PNG_FILTER_TYPE_DEFAULT;
  296. // Write header
  297. png_set_IHDR(mWritePngPtr, mWriteInfoPtr, mWidth, mHeight,
  298. mBitDepth, mColorType, mInterlaceType,
  299. mCompressionType, mFilterMethod);
  300. // Get data and compute row size
  301. const U8* data = raw_image->getData();
  302. S32 offset = mWidth * mChannels;
  303. // Ready to write, start with the header
  304. png_write_info(mWritePngPtr, mWriteInfoPtr);
  305. // Write image (sorry, must const-cast for libpng)
  306. for (U32 i = 0; i < mHeight; ++i)
  307. {
  308. const U8* row_pointer = &data[(mHeight - 1 - i) * offset];
  309. png_write_row(mWritePngPtr, const_cast<png_bytep>(row_pointer));
  310. }
  311. // Finish up
  312. png_write_end(mWritePngPtr, mWriteInfoPtr);
  313. mFinalSize = dataPtr.mOffset;
  314. }
  315. catch (png_const_charp msg)
  316. {
  317. mErrorMessage = msg;
  318. releaseResources();
  319. return false;
  320. }
  321. releaseResources();
  322. return true;
  323. }
  324. // Cleanup various internal structures
  325. void LLPngWrapper::releaseResources()
  326. {
  327. if (mReadPngPtr || mReadInfoPtr)
  328. {
  329. png_destroy_read_struct(&mReadPngPtr, &mReadInfoPtr, NULL);
  330. mReadPngPtr = NULL;
  331. mReadInfoPtr = NULL;
  332. }
  333. if (mWritePngPtr || mWriteInfoPtr)
  334. {
  335. png_destroy_write_struct(&mWritePngPtr, &mWriteInfoPtr);
  336. mWritePngPtr = NULL;
  337. mWriteInfoPtr = NULL;
  338. }
  339. if (mRowPointers)
  340. {
  341. delete[] mRowPointers;
  342. mRowPointers = NULL;
  343. }
  344. }