| 1 | #include "image_loader.h" |
| 2 | |
| 3 | #include <base/dbg.h> |
| 4 | #include <base/io.h> |
| 5 | #include <base/log.h> |
| 6 | #include <base/mem.h> |
| 7 | #include <base/str.h> |
| 8 | |
| 9 | #include <png.h> |
| 10 | |
| 11 | #include <csetjmp> |
| 12 | #include <cstdlib> |
| 13 | |
| 14 | bool CByteBufferReader::Read(void *pData, size_t Size) |
| 15 | { |
| 16 | if(m_Error) |
| 17 | return false; |
| 18 | |
| 19 | if(m_ReadOffset + Size <= m_Size) |
| 20 | { |
| 21 | mem_copy(dest: pData, source: &m_pData[m_ReadOffset], size: Size); |
| 22 | m_ReadOffset += Size; |
| 23 | return true; |
| 24 | } |
| 25 | else |
| 26 | { |
| 27 | m_Error = true; |
| 28 | return false; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | void CByteBufferWriter::Write(const void *pData, size_t Size) |
| 33 | { |
| 34 | if(!Size) |
| 35 | return; |
| 36 | |
| 37 | const size_t WriteOffset = m_vBuffer.size(); |
| 38 | m_vBuffer.resize(sz: WriteOffset + Size); |
| 39 | mem_copy(dest: &m_vBuffer[WriteOffset], source: pData, size: Size); |
| 40 | } |
| 41 | |
| 42 | class CUserErrorStruct |
| 43 | { |
| 44 | public: |
| 45 | const char *m_pContextName; |
| 46 | std::jmp_buf m_JmpBuf; |
| 47 | }; |
| 48 | |
| 49 | [[noreturn]] static void PngErrorCallback(png_structp pPngStruct, png_const_charp pErrorMessage) |
| 50 | { |
| 51 | CUserErrorStruct *pUserStruct = static_cast<CUserErrorStruct *>(png_get_error_ptr(png_ptr: pPngStruct)); |
| 52 | log_error("png" , "error for file \"%s\": %s" , pUserStruct->m_pContextName, pErrorMessage); |
| 53 | std::longjmp(env: pUserStruct->m_JmpBuf, val: 1); |
| 54 | } |
| 55 | |
| 56 | static void PngWarningCallback(png_structp pPngStruct, png_const_charp pWarningMessage) |
| 57 | { |
| 58 | CUserErrorStruct *pUserStruct = static_cast<CUserErrorStruct *>(png_get_error_ptr(png_ptr: pPngStruct)); |
| 59 | log_warn("png" , "warning for file \"%s\": %s" , pUserStruct->m_pContextName, pWarningMessage); |
| 60 | } |
| 61 | |
| 62 | static void PngReadDataCallback(png_structp pPngStruct, png_bytep pOutBytes, png_size_t ByteCountToRead) |
| 63 | { |
| 64 | CByteBufferReader *pReader = static_cast<CByteBufferReader *>(png_get_io_ptr(png_ptr: pPngStruct)); |
| 65 | if(!pReader->Read(pData: pOutBytes, Size: ByteCountToRead)) |
| 66 | { |
| 67 | png_error(png_ptr: pPngStruct, error_message: "Could not read all bytes, file was too small" ); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | static CImageInfo::EImageFormat ImageFormatFromChannelCount(int ColorChannelCount) |
| 72 | { |
| 73 | switch(ColorChannelCount) |
| 74 | { |
| 75 | case 1: |
| 76 | return CImageInfo::FORMAT_R; |
| 77 | case 2: |
| 78 | return CImageInfo::FORMAT_RA; |
| 79 | case 3: |
| 80 | return CImageInfo::FORMAT_RGB; |
| 81 | case 4: |
| 82 | return CImageInfo::FORMAT_RGBA; |
| 83 | default: |
| 84 | dbg_assert_failed("ColorChannelCount invalid" ); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | static int PngliteIncompatibility(png_structp pPngStruct, png_infop pPngInfo) |
| 89 | { |
| 90 | int Result = 0; |
| 91 | |
| 92 | const int ColorType = png_get_color_type(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 93 | switch(ColorType) |
| 94 | { |
| 95 | case PNG_COLOR_TYPE_GRAY: |
| 96 | case PNG_COLOR_TYPE_RGB: |
| 97 | case PNG_COLOR_TYPE_RGB_ALPHA: |
| 98 | case PNG_COLOR_TYPE_GRAY_ALPHA: |
| 99 | break; |
| 100 | default: |
| 101 | log_debug("png" , "color type %d unsupported by pnglite" , ColorType); |
| 102 | Result |= CImageLoader::PNGLITE_COLOR_TYPE; |
| 103 | } |
| 104 | |
| 105 | const int BitDepth = png_get_bit_depth(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 106 | switch(BitDepth) |
| 107 | { |
| 108 | case 8: |
| 109 | case 16: |
| 110 | break; |
| 111 | default: |
| 112 | log_debug("png" , "bit depth %d unsupported by pnglite" , BitDepth); |
| 113 | Result |= CImageLoader::PNGLITE_BIT_DEPTH; |
| 114 | } |
| 115 | |
| 116 | const int InterlaceType = png_get_interlace_type(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 117 | if(InterlaceType != PNG_INTERLACE_NONE) |
| 118 | { |
| 119 | log_debug("png" , "interlace type %d unsupported by pnglite" , InterlaceType); |
| 120 | Result |= CImageLoader::PNGLITE_INTERLACE_TYPE; |
| 121 | } |
| 122 | |
| 123 | if(png_get_compression_type(png_ptr: pPngStruct, info_ptr: pPngInfo) != PNG_COMPRESSION_TYPE_BASE) |
| 124 | { |
| 125 | log_debug("png" , "non-default compression type unsupported by pnglite" ); |
| 126 | Result |= CImageLoader::PNGLITE_COMPRESSION_TYPE; |
| 127 | } |
| 128 | |
| 129 | if(png_get_filter_type(png_ptr: pPngStruct, info_ptr: pPngInfo) != PNG_FILTER_TYPE_BASE) |
| 130 | { |
| 131 | log_debug("png" , "non-default filter type unsupported by pnglite" ); |
| 132 | Result |= CImageLoader::PNGLITE_FILTER_TYPE; |
| 133 | } |
| 134 | |
| 135 | return Result; |
| 136 | } |
| 137 | |
| 138 | bool CImageLoader::LoadPng(CByteBufferReader &Reader, const char *pContextName, CImageInfo &Image, int &PngliteIncompatible) |
| 139 | { |
| 140 | CUserErrorStruct UserErrorStruct = {.m_pContextName: pContextName, .m_JmpBuf: {}}; |
| 141 | |
| 142 | if(setjmp(UserErrorStruct.m_JmpBuf)) |
| 143 | { |
| 144 | return false; |
| 145 | } |
| 146 | |
| 147 | png_structp pPngStruct = png_create_read_struct(PNG_LIBPNG_VER_STRING, error_ptr: &UserErrorStruct, error_fn: PngErrorCallback, warn_fn: PngWarningCallback); |
| 148 | if(pPngStruct == nullptr) |
| 149 | { |
| 150 | log_error("png" , "libpng internal failure: png_create_read_struct failed." ); |
| 151 | return false; |
| 152 | } |
| 153 | |
| 154 | png_infop pPngInfo = png_create_info_struct(png_ptr: pPngStruct); |
| 155 | if(pPngInfo == nullptr) |
| 156 | { |
| 157 | png_destroy_read_struct(png_ptr_ptr: &pPngStruct, info_ptr_ptr: nullptr, end_info_ptr_ptr: nullptr); |
| 158 | log_error("png" , "libpng internal failure: png_create_info_struct failed." ); |
| 159 | return false; |
| 160 | } |
| 161 | |
| 162 | // Written after setjmp and read by Cleanup after longjmp, which is only defined for volatile locals |
| 163 | volatile png_bytepp pRowPointers = nullptr; |
| 164 | const auto &&Cleanup = [&](bool Success) { |
| 165 | delete[] pRowPointers; |
| 166 | png_destroy_info_struct(png_ptr: pPngStruct, info_ptr_ptr: &pPngInfo); |
| 167 | png_destroy_read_struct(png_ptr_ptr: &pPngStruct, info_ptr_ptr: nullptr, end_info_ptr_ptr: nullptr); |
| 168 | if(!Success) |
| 169 | { |
| 170 | Image.Free(); |
| 171 | } |
| 172 | }; |
| 173 | if(setjmp(UserErrorStruct.m_JmpBuf)) |
| 174 | { |
| 175 | Cleanup(false); |
| 176 | return false; |
| 177 | } |
| 178 | |
| 179 | png_byte aSignature[8]; |
| 180 | if(!Reader.Read(pData: aSignature, Size: sizeof(aSignature)) || png_sig_cmp(sig: aSignature, start: 0, num_to_check: sizeof(aSignature)) != 0) |
| 181 | { |
| 182 | Cleanup(false); |
| 183 | log_error("png" , "file is not a valid PNG file (signature mismatch)." ); |
| 184 | return false; |
| 185 | } |
| 186 | |
| 187 | png_set_read_fn(png_ptr: pPngStruct, io_ptr: (png_bytep)&Reader, read_data_fn: PngReadDataCallback); |
| 188 | png_set_sig_bytes(png_ptr: pPngStruct, num_bytes: sizeof(aSignature)); |
| 189 | |
| 190 | png_read_info(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 191 | |
| 192 | if(Reader.Error()) |
| 193 | { |
| 194 | // error already logged |
| 195 | Cleanup(false); |
| 196 | return false; |
| 197 | } |
| 198 | |
| 199 | const size_t Width = png_get_image_width(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 200 | const size_t Height = png_get_image_height(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 201 | const png_byte BitDepth = png_get_bit_depth(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 202 | const int ColorType = png_get_color_type(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 203 | const int Incompatible = PngliteIncompatibility(pPngStruct, pPngInfo); |
| 204 | |
| 205 | if(Width == 0 || Height == 0) |
| 206 | { |
| 207 | log_error("png" , "image has width (%" PRIzu ") or height (%" PRIzu ") of 0." , Width, Height); |
| 208 | Cleanup(false); |
| 209 | return false; |
| 210 | } |
| 211 | |
| 212 | if(BitDepth == 16) |
| 213 | { |
| 214 | png_set_strip_16(png_ptr: pPngStruct); |
| 215 | } |
| 216 | else if(BitDepth > 8 || BitDepth == 0) |
| 217 | { |
| 218 | log_error("png" , "bit depth %d not supported." , BitDepth); |
| 219 | Cleanup(false); |
| 220 | return false; |
| 221 | } |
| 222 | |
| 223 | if(ColorType == PNG_COLOR_TYPE_PALETTE) |
| 224 | { |
| 225 | png_set_palette_to_rgb(png_ptr: pPngStruct); |
| 226 | } |
| 227 | |
| 228 | if(ColorType == PNG_COLOR_TYPE_GRAY && BitDepth < 8) |
| 229 | { |
| 230 | png_set_expand_gray_1_2_4_to_8(png_ptr: pPngStruct); |
| 231 | } |
| 232 | |
| 233 | if(png_get_valid(png_ptr: pPngStruct, info_ptr: pPngInfo, PNG_INFO_tRNS)) |
| 234 | { |
| 235 | png_set_tRNS_to_alpha(png_ptr: pPngStruct); |
| 236 | } |
| 237 | |
| 238 | png_read_update_info(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 239 | |
| 240 | const int ColorChannelCount = png_get_channels(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 241 | const size_t BytesInRow = png_get_rowbytes(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 242 | dbg_assert(BytesInRow == Width * ColorChannelCount, "bytes in row incorrect." ); |
| 243 | |
| 244 | Image.m_Width = Width; |
| 245 | Image.m_Height = Height; |
| 246 | Image.m_Format = ImageFormatFromChannelCount(ColorChannelCount); |
| 247 | Image.Allocate(); |
| 248 | |
| 249 | pRowPointers = new png_bytep[Height]; |
| 250 | for(size_t y = 0; y < Height; ++y) |
| 251 | { |
| 252 | pRowPointers[y] = &Image.m_pData[y * BytesInRow]; |
| 253 | } |
| 254 | png_read_image(png_ptr: pPngStruct, image: pRowPointers); |
| 255 | |
| 256 | const bool Success = !Reader.Error(); |
| 257 | if(Success) |
| 258 | { |
| 259 | PngliteIncompatible = Incompatible; |
| 260 | } |
| 261 | Cleanup(Success); |
| 262 | return Success; |
| 263 | } |
| 264 | |
| 265 | bool CImageLoader::LoadPng(IOHANDLE File, const char *pFilename, CImageInfo &Image, int &PngliteIncompatible) |
| 266 | { |
| 267 | if(!File) |
| 268 | { |
| 269 | log_error("png" , "failed to open file for reading. filename='%s'" , pFilename); |
| 270 | return false; |
| 271 | } |
| 272 | |
| 273 | void *pFileData; |
| 274 | unsigned FileDataSize; |
| 275 | const bool ReadSuccess = io_read_all(io: File, result: &pFileData, result_len: &FileDataSize); |
| 276 | io_close(io: File); |
| 277 | if(!ReadSuccess) |
| 278 | { |
| 279 | log_error("png" , "failed to read file. filename='%s'" , pFilename); |
| 280 | return false; |
| 281 | } |
| 282 | |
| 283 | CByteBufferReader ImageReader(static_cast<const uint8_t *>(pFileData), FileDataSize); |
| 284 | |
| 285 | const bool LoadResult = CImageLoader::LoadPng(Reader&: ImageReader, pContextName: pFilename, Image, PngliteIncompatible); |
| 286 | free(ptr: pFileData); |
| 287 | if(!LoadResult) |
| 288 | { |
| 289 | log_error("png" , "failed to load image from file. filename='%s'" , pFilename); |
| 290 | return false; |
| 291 | } |
| 292 | |
| 293 | if(Image.m_Format != CImageInfo::FORMAT_RGB && Image.m_Format != CImageInfo::FORMAT_RGBA) |
| 294 | { |
| 295 | log_error("png" , "image has unsupported format. filename='%s' format='%s'" , pFilename, Image.FormatName()); |
| 296 | Image.Free(); |
| 297 | return false; |
| 298 | } |
| 299 | |
| 300 | return true; |
| 301 | } |
| 302 | |
| 303 | static void PngWriteDataCallback(png_structp pPngStruct, png_bytep pOutBytes, png_size_t ByteCountToWrite) |
| 304 | { |
| 305 | CByteBufferWriter *pWriter = static_cast<CByteBufferWriter *>(png_get_io_ptr(png_ptr: pPngStruct)); |
| 306 | pWriter->Write(pData: pOutBytes, Size: ByteCountToWrite); |
| 307 | } |
| 308 | |
| 309 | static void PngOutputFlushCallback(png_structp pPngStruct) |
| 310 | { |
| 311 | // no need to flush memory buffer |
| 312 | } |
| 313 | |
| 314 | static int PngColorTypeFromFormat(CImageInfo::EImageFormat Format) |
| 315 | { |
| 316 | switch(Format) |
| 317 | { |
| 318 | case CImageInfo::FORMAT_R: |
| 319 | return PNG_COLOR_TYPE_GRAY; |
| 320 | case CImageInfo::FORMAT_RA: |
| 321 | return PNG_COLOR_TYPE_GRAY_ALPHA; |
| 322 | case CImageInfo::FORMAT_RGB: |
| 323 | return PNG_COLOR_TYPE_RGB; |
| 324 | case CImageInfo::FORMAT_RGBA: |
| 325 | return PNG_COLOR_TYPE_RGBA; |
| 326 | default: |
| 327 | dbg_assert_failed("Format invalid" ); |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | bool CImageLoader::SavePng(CByteBufferWriter &Writer, const CImageInfo &Image) |
| 332 | { |
| 333 | png_structp pPngStruct = png_create_write_struct(PNG_LIBPNG_VER_STRING, error_ptr: nullptr, error_fn: nullptr, warn_fn: nullptr); |
| 334 | if(pPngStruct == nullptr) |
| 335 | { |
| 336 | log_error("png" , "libpng internal failure: png_create_write_struct failed." ); |
| 337 | return false; |
| 338 | } |
| 339 | |
| 340 | png_infop pPngInfo = png_create_info_struct(png_ptr: pPngStruct); |
| 341 | if(pPngInfo == nullptr) |
| 342 | { |
| 343 | png_destroy_read_struct(png_ptr_ptr: &pPngStruct, info_ptr_ptr: nullptr, end_info_ptr_ptr: nullptr); |
| 344 | log_error("png" , "libpng internal failure: png_create_info_struct failed." ); |
| 345 | return false; |
| 346 | } |
| 347 | |
| 348 | png_set_write_fn(png_ptr: pPngStruct, io_ptr: (png_bytep)&Writer, write_data_fn: PngWriteDataCallback, output_flush_fn: PngOutputFlushCallback); |
| 349 | |
| 350 | png_set_IHDR(png_ptr: pPngStruct, info_ptr: pPngInfo, width: Image.m_Width, height: Image.m_Height, bit_depth: 8, color_type: PngColorTypeFromFormat(Format: Image.m_Format), PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); |
| 351 | png_write_info(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 352 | |
| 353 | const size_t WidthBytes = Image.m_Width * Image.PixelSize(); |
| 354 | for(size_t y = 0; y < Image.m_Height; ++y) |
| 355 | { |
| 356 | png_write_row(png_ptr: pPngStruct, row: Image.m_pData + y * WidthBytes); |
| 357 | } |
| 358 | png_write_end(png_ptr: pPngStruct, info_ptr: pPngInfo); |
| 359 | |
| 360 | png_destroy_info_struct(png_ptr: pPngStruct, info_ptr_ptr: &pPngInfo); |
| 361 | png_destroy_write_struct(png_ptr_ptr: &pPngStruct, info_ptr_ptr: nullptr); |
| 362 | |
| 363 | return true; |
| 364 | } |
| 365 | |
| 366 | bool CImageLoader::SavePng(IOHANDLE File, const char *pFilename, const CImageInfo &Image) |
| 367 | { |
| 368 | if(!File) |
| 369 | { |
| 370 | log_error("png" , "failed to open file for writing. filename='%s'" , pFilename); |
| 371 | return false; |
| 372 | } |
| 373 | |
| 374 | CByteBufferWriter Writer; |
| 375 | if(!CImageLoader::SavePng(Writer, Image)) |
| 376 | { |
| 377 | // error already logged |
| 378 | io_close(io: File); |
| 379 | return false; |
| 380 | } |
| 381 | |
| 382 | const bool WriteSuccess = io_write(io: File, buffer: Writer.Data(), size: Writer.Size()) == Writer.Size(); |
| 383 | if(!WriteSuccess) |
| 384 | { |
| 385 | log_error("png" , "failed to write PNG data to file. filename='%s'" , pFilename); |
| 386 | } |
| 387 | io_close(io: File); |
| 388 | return WriteSuccess; |
| 389 | } |
| 390 | |