openMSX
PNG.cc
Go to the documentation of this file.
1#include "PNG.hh"
2
3#include "File.hh"
4#include "MSXException.hh"
5#include "PixelOperations.hh"
6#include "Version.hh"
7
8#include "endian.hh"
9#include "narrow.hh"
10#include "one_of.hh"
11#include "vla.hh"
12#include "cstdiop.hh"
13
14#include <png.h>
15#include <SDL.h>
16
17#include <array>
18#include <bit>
19#include <cassert>
20#include <cstring>
21#include <cstdlib>
22#include <ctime>
23#include <iostream>
24#include <limits>
25#include <tuple>
26
27namespace openmsx::PNG {
28
29[[noreturn]] static void handleError(png_structp png_ptr, png_const_charp error_msg)
30{
31 const auto* operation = std::bit_cast<const char*>(
32 png_get_error_ptr(png_ptr));
33 throw MSXException("Error while ", operation, " PNG: ", error_msg);
34}
35
36static void handleWarning(png_structp png_ptr, png_const_charp warning_msg)
37{
38 const auto* operation = std::bit_cast<const char*>(
39 png_get_error_ptr(png_ptr));
40 std::cerr << "Warning while " << operation << " PNG: "
41 << warning_msg << '\n';
42}
43
44/*
45The copyright notice below applies to the original PNG load code, which was
46imported from SDL_image 1.2.10, file "IMG_png.c", function "IMG_LoadPNG_RW".
47===============================================================================
48 File: SDL_png.c
49 Purpose: A PNG loader and saver for the SDL library
50 Revision:
51 Created by: Philippe Lavoie (2 November 1998)
52 lavoie@zeus.genie.uottawa.ca
53 Modified by:
54
55 Copyright notice:
56 Copyright (C) 1998 Philippe Lavoie
57
58 This library is free software; you can redistribute it and/or
59 modify it under the terms of the GNU Library General Public
60 License as published by the Free Software Foundation; either
61 version 2 of the License, or (at your option) any later version.
62
63 This library is distributed in the hope that it will be useful,
64 but WITHOUT ANY WARRANTY; without even the implied warranty of
65 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
66 Library General Public License for more details.
67
68 You should have received a copy of the GNU Library General Public
69 License along with this library; if not, write to the Free
70 Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
71
72 Comments: The load and save routine are basically the ones you can find
73 in the example.c file from the libpng distribution.
74
75 Changes:
76 1999-05-17: Modified to use the new SDL data sources - Sam Lantinga
77 2009-12-29: Modified for use in openMSX - Maarten ter Huurne
78 and Wouter Vermaelen
79
80===============================================================================
81*/
82
84 PNGReadHandle() = default;
86 {
87 if (ptr) {
88 png_destroy_read_struct(&ptr, info ? &info : nullptr, nullptr);
89 }
90 }
91 PNGReadHandle(const PNGReadHandle&) = delete;
93
94 png_structp ptr = nullptr;
95 png_infop info = nullptr;
96};
97
98static void readData(png_structp ctx, png_bytep area, png_size_t size)
99{
100 auto* file = std::bit_cast<File*>(png_get_io_ptr(ctx));
101 file->read(std::span{area, size});
102}
103
104SDLSurfacePtr load(const std::string& filename, bool want32bpp)
105{
106 File file(filename);
107
108 try {
109 // Create the PNG loading context structure.
110 PNGReadHandle png;
111 png.ptr = png_create_read_struct(
112 PNG_LIBPNG_VER_STRING,
113 const_cast<char*>("decoding"), handleError, handleWarning);
114 if (!png.ptr) {
115 throw MSXException("Failed to allocate main struct");
116 }
117
118 // Allocate/initialize the memory for image information.
119 png.info = png_create_info_struct(png.ptr);
120 if (!png.info) {
121 throw MSXException("Failed to allocate image info struct");
122 }
123
124 // Set up the input control.
125 png_set_read_fn(png.ptr, &file, readData);
126
127 // Read PNG header info.
128 png_read_info(png.ptr, png.info);
129 png_uint_32 width, height;
130 int bit_depth, color_type, interlace_type;
131 png_get_IHDR(png.ptr, png.info, &width, &height, &bit_depth,
132 &color_type, &interlace_type, nullptr, nullptr);
133
134 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
135 png_set_strip_16(png.ptr);
136
137 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
138 // byte into separate bytes (useful for paletted and grayscale images).
139 png_set_packing(png.ptr);
140
141 // The following enables:
142 // - transformation of grayscale images of less than 8 to 8 bits
143 // - changes paletted images to RGB
144 // - adds a full alpha channel if there is transparency information in a tRNS chunk
145 png_set_expand(png.ptr);
146
147 if (want32bpp) {
148 png_set_filler(png.ptr, 0xff, PNG_FILLER_AFTER);
149 }
150
151 // always convert grayscale to RGB
152 // together with all the above conversions, the resulting image will
153 // be either RGB or RGBA with 8 bits per component.
154 png_set_gray_to_rgb(png.ptr);
155
156 png_read_update_info(png.ptr, png.info);
157
158 png_get_IHDR(png.ptr, png.info, &width, &height, &bit_depth,
159 &color_type, &interlace_type, nullptr, nullptr);
160
161 // Allocate the SDL surface to hold the image.
162 constexpr unsigned MAX_SIZE = 2048;
163 if (width > MAX_SIZE) {
164 throw MSXException(
165 "Attempted to create a surface with excessive width: ",
166 width, ", max ", MAX_SIZE);
167 }
168 if (height > MAX_SIZE) {
169 throw MSXException(
170 "Attempted to create a surface with excessive height: ",
171 height, ", max ", MAX_SIZE);
172 }
173 int bpp = png_get_channels(png.ptr, png.info) * 8;
174 assert(bpp == one_of(24, 32));
175 PixelOperations pixelOps;
176 SDLSurfacePtr surface(width, height, bpp,
177 pixelOps.getRmask(), pixelOps.getGmask(), pixelOps.getBmask(),
178 ((bpp == 32) ? pixelOps.getAmask() : 0));
179
180 // Create the array of pointers to image data.
181 VLA(png_bytep, rowPointers, height);
182 for (auto row : xrange(height)) {
183 rowPointers[row] = std::bit_cast<png_bytep>(
184 surface.getLinePtr(row));
185 }
186
187 // Read the entire image in one go.
188 png_read_image(png.ptr, rowPointers.data());
189
190 // In some cases it can't read PNGs created by some popular programs
191 // (ACDSEE), we do not want to process comments, so we omit png_read_end
192 //png_read_end(png.ptr, png.info);
193
194 return surface;
195 } catch (MSXException& e) {
196 throw MSXException(
197 "Error while loading PNG file \"", filename, "\": ",
198 e.getMessage());
199 }
200}
201
202
203/* PNG save code by Darren Grant sdl@lokigames.com */
204/* heavily modified for openMSX by Joost Damad joost@lumatec.be */
205
207 PNGWriteHandle() = default;
209 {
210 if (ptr) {
211 png_destroy_write_struct(&ptr, info ? &info : nullptr);
212 }
213 }
216
217 png_structp ptr = nullptr;
218 png_infop info = nullptr;
219};
220
221static void writeData(png_structp ctx, png_bytep area, png_size_t size)
222{
223 auto* file = std::bit_cast<File*>(png_get_io_ptr(ctx));
224 file->write(std::span{area, size});
225}
226
227static void flushData(png_structp ctx)
228{
229 auto* file = std::bit_cast<File*>(png_get_io_ptr(ctx));
230 file->flush();
231}
232
233static void IMG_SavePNG_RW(size_t width, std::span<const void*> rowPointers,
234 const std::string& filename, bool color)
235{
236 auto height = rowPointers.size();
237 assert(width <= std::numeric_limits<png_uint_32>::max());
238 assert(height <= std::numeric_limits<png_uint_32>::max());
239 try {
240 File file(filename, File::TRUNCATE);
241
242 PNGWriteHandle png;
243 png.ptr = png_create_write_struct(
244 PNG_LIBPNG_VER_STRING,
245 const_cast<char*>("encoding"), handleError, handleWarning);
246 if (!png.ptr) {
247 throw MSXException("Failed to allocate main struct");
248 }
249
250 // Allocate/initialize the image information data. REQUIRED
251 png.info = png_create_info_struct(png.ptr);
252 if (!png.info) {
253 // Couldn't create image information for PNG file
254 throw MSXException("Failed to allocate image info struct");
255 }
256
257 // Set up the output control.
258 png_set_write_fn(png.ptr, &file, writeData, flushData);
259
260 // Mark this image as being generated by openMSX and add creation time.
261 std::string version = Version::full();
262 std::array<png_text, 2> text;
263 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
264 text[0].key = const_cast<char*>("Software");
265 text[0].text = const_cast<char*>(version.c_str());
266 text[1].compression = PNG_TEXT_COMPRESSION_NONE;
267 text[1].key = const_cast<char*>("Creation Time");
268
269 // A buffer size of 20 characters is large enough till the year
270 // 9999. But the compiler doesn't understand calendars and
271 // warns that the snprintf output could be truncated (e.g.
272 // because the year is -2147483647). To silence this warning
273 // (and also to work around the windows _snprintf stuff) we add
274 // some extra buffer space.
275 static constexpr size_t size = (10 + 1 + 8 + 1) + 44;
276 time_t now = time(nullptr);
277 struct tm* tm = localtime(&now);
278 std::array<char, size> timeStr;
279 snprintf(timeStr.data(), sizeof(timeStr), "%04d-%02d-%02d %02d:%02d:%02d",
280 1900 + tm->tm_year, tm->tm_mon + 1, tm->tm_mday,
281 tm->tm_hour, tm->tm_min, tm->tm_sec);
282 text[1].text = timeStr.data();
283
284 png_set_text(png.ptr, png.info, text.data(), narrow<int>(text.size()));
285
286 png_set_IHDR(png.ptr, png.info,
287 narrow<png_uint_32>(width), narrow<png_uint_32>(height),
288 8,
289 color ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_GRAY,
290 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
291 PNG_FILTER_TYPE_BASE);
292
293 // Write the file header information. REQUIRED
294 png_write_info(png.ptr, png.info);
295
296 // Write out the entire image data in one call.
297 png_write_image(
298 png.ptr,
299 std::bit_cast<png_bytep*>(const_cast<void**>(rowPointers.data())));
300 png_write_end(png.ptr, png.info);
301 } catch (MSXException& e) {
302 throw MSXException(
303 "Error while writing PNG file \"", filename, "\": ",
304 e.getMessage());
305 }
306}
307
308static void save(SDL_Surface* image, const std::string& filename)
309{
310 SDLAllocFormatPtr frmt24(SDL_AllocFormat(
311 Endian::BIG ? SDL_PIXELFORMAT_BGR24 : SDL_PIXELFORMAT_RGB24));
312 SDLSurfacePtr surf24(SDL_ConvertSurface(image, frmt24.get(), 0));
313
314 // Create the array of pointers to image data
315 VLA(const void*, row_pointers, image->h);
316 for (auto i : xrange(image->h)) {
317 row_pointers[i] = surf24.getLinePtr(i);
318 }
319
320 IMG_SavePNG_RW(image->w, row_pointers, filename, true);
321}
322
323void saveRGBA(size_t width, std::span<const void*> rowPointers,
324 const std::string& filename)
325{
326 // this implementation creates 1 extra copy, can be optimized if required
327 auto height = narrow<unsigned>(rowPointers.size());
328 static constexpr int bpp = 32;
329 PixelOperations pixelOps;
330 SDLSurfacePtr surface(
331 narrow<unsigned>(width), height, bpp,
332 pixelOps.getRmask(), pixelOps.getGmask(),
333 pixelOps.getBmask(), pixelOps.getAmask());
334 for (auto y : xrange(height)) {
335 memcpy(surface.getLinePtr(y),
336 rowPointers[y], width * sizeof(uint32_t));
337 }
338 save(surface.get(), filename);
339}
340
341void saveGrayscale(size_t width, std::span<const void*> rowPointers,
342 const std::string& filename)
343{
344 IMG_SavePNG_RW(width, rowPointers, filename, false);
345}
346
347} // namespace openmsx::PNG
std::string image
Definition HDImageCLI.cc:16
std::unique_ptr< SDL_PixelFormat, SDLFreeFormat > SDLAllocFormatPtr
Wrapper around a SDL_Surface.
SDL_Surface * get()
void * getLinePtr(unsigned y)
static std::string full()
Definition Version.cc:8
constexpr bool BIG
Definition endian.hh:16
constexpr double e
Definition Math.hh:21
Utility functions to hide the complexity of saving to a PNG file.
Definition PNG.cc:27
void saveRGBA(size_t width, std::span< const void * > rowPointers, const std::string &filename)
Definition PNG.cc:323
void saveGrayscale(size_t width, std::span< const void * > rowPointers, const std::string &filename)
Definition PNG.cc:341
SDLSurfacePtr load(const std::string &filename, bool want32bpp)
Load the given PNG file in a SDL_Surface.
Definition PNG.cc:104
size_t size(std::string_view utf8)
PNGReadHandle & operator=(const PNGReadHandle &)=delete
PNGReadHandle(const PNGReadHandle &)=delete
PNGWriteHandle & operator=(const PNGWriteHandle &)=delete
PNGWriteHandle(const PNGWriteHandle &)=delete
#define VLA(TYPE, NAME, LENGTH)
Definition vla.hh:12
constexpr auto xrange(T e)
Definition xrange.hh:132