Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : /*
24 : * PNG codec using libpng.
25 : */
26 :
27 : #include "precompiled.h"
28 :
29 : #include "tex_codec.h"
30 :
31 : #include "lib/alignment.h"
32 : #include "lib/allocators/dynarray.h"
33 : #include "lib/allocators/shared_ptr.h"
34 : #include "lib/byte_order.h"
35 : #include "lib/code_annotation.h"
36 : #include "lib/debug.h"
37 : #include "lib/external_libraries/png.h"
38 : #include "lib/os_path.h"
39 : #include "lib/status.h"
40 : #include "lib/sysdep/compiler.h"
41 : #include "lib/tex/tex.h"
42 :
43 : #include <csetjmp>
44 : #include <cstring>
45 : #include <memory>
46 : #include <vector>
47 :
48 : #if MSC_VERSION
49 :
50 : // squelch "dtor / setjmp interaction" warnings.
51 : // all attempts to resolve the underlying problem failed; apparently
52 : // the warning is generated if setjmp is used at all in C++ mode.
53 : // (png_*_impl have no code that would trigger ctors/dtors, nor are any
54 : // called in their prolog/epilog code).
55 : # pragma warning(disable: 4611)
56 :
57 : #endif // MSC_VERSION
58 :
59 :
60 : //-----------------------------------------------------------------------------
61 : //
62 : //-----------------------------------------------------------------------------
63 :
64 : class MemoryStream
65 : {
66 : public:
67 3 : MemoryStream(std::uint8_t* RESTRICT data, size_t size)
68 3 : : data(data), size(size), pos(0)
69 : {
70 : }
71 :
72 54 : size_t RemainingSize() const
73 : {
74 54 : ASSERT(pos <= size);
75 54 : return size-pos;
76 : }
77 :
78 51 : void CopyTo(std::uint8_t* RESTRICT dst, size_t dstSize)
79 : {
80 51 : memcpy(dst, data+pos, dstSize);
81 51 : pos += dstSize;
82 : }
83 :
84 : private:
85 : std::uint8_t* RESTRICT data;
86 : size_t size;
87 : size_t pos;
88 : };
89 :
90 :
91 : // pass data from PNG file in memory to libpng
92 51 : static void io_read(png_struct* png_ptr, std::uint8_t* RESTRICT data, png_size_t size)
93 : {
94 51 : MemoryStream* stream = (MemoryStream*)png_get_io_ptr(png_ptr);
95 51 : if(stream->RemainingSize() < size)
96 : {
97 0 : png_error(png_ptr, "PNG: not enough input");
98 : return;
99 : }
100 :
101 51 : stream->CopyTo(data, size);
102 : }
103 :
104 :
105 : // write libpng output to PNG file
106 0 : static void io_write(png_struct* png_ptr, std::uint8_t* data, png_size_t length)
107 : {
108 0 : DynArray* da = (DynArray*)png_get_io_ptr(png_ptr);
109 0 : if(da_append(da, data, length) != 0)
110 0 : png_error(png_ptr, "io_write failed");
111 0 : }
112 :
113 :
114 0 : static void io_flush(png_structp)
115 : {
116 0 : }
117 :
118 :
119 :
120 : //-----------------------------------------------------------------------------
121 :
122 13 : Status TexCodecPng::transform(Tex*, size_t /*transforms*/) const
123 : {
124 13 : return INFO::TEX_CODEC_CANNOT_HANDLE;
125 : }
126 :
127 :
128 : // note: it's not worth combining png_encode and png_decode, due to
129 : // libpng read/write interface differences (grr).
130 :
131 : // split out of png_decode to simplify resource cleanup and avoid
132 : // "dtor / setjmp interaction" warning.
133 3 : static Status png_decode_impl(MemoryStream* stream, png_structp png_ptr, png_infop info_ptr, Tex* t)
134 : {
135 3 : png_set_read_fn(png_ptr, stream, io_read);
136 :
137 : // read header and determine format
138 3 : png_read_info(png_ptr, info_ptr);
139 3 : png_uint_32 w, h;
140 3 : int bit_depth, color_type, interlace_type;
141 3 : png_get_IHDR(png_ptr, info_ptr, &w, &h, &bit_depth, &color_type, &interlace_type, 0, 0);
142 :
143 : // (The following is based on GdkPixbuf's PNG image loader)
144 :
145 : // Convert the following images to 8-bit RGB/RGBA:
146 : // * indexed colors
147 : // * grayscale with alpha
148 : // * transparency header
149 : // * bit depth of 16 or less than 8
150 : // * interlaced
151 3 : if (color_type == PNG_COLOR_TYPE_PALETTE && bit_depth <= 8)
152 0 : png_set_expand(png_ptr);
153 3 : else if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
154 0 : png_set_expand(png_ptr);
155 3 : else if (bit_depth < 8)
156 0 : png_set_expand(png_ptr);
157 :
158 3 : if (bit_depth == 16)
159 0 : png_set_strip_16(png_ptr);
160 3 : if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
161 0 : png_set_gray_to_rgb(png_ptr);
162 3 : if (interlace_type != PNG_INTERLACE_NONE)
163 0 : png_set_interlace_handling(png_ptr);
164 :
165 : // Update info after transformations
166 3 : png_read_update_info(png_ptr, info_ptr);
167 :
168 3 : png_get_IHDR(png_ptr, info_ptr, &w, &h, &bit_depth, &color_type, &interlace_type, 0, 0);
169 :
170 : // make sure format is acceptable:
171 : // * non-zero dimensions
172 : // * 8-bit depth
173 : // * RGB, RGBA, or grayscale
174 : // * 1, 3 or 4 channels
175 3 : if (w == 0 || h == 0)
176 0 : WARN_RETURN(ERR::TEX_INVALID_SIZE);
177 3 : if (bit_depth != 8)
178 0 : WARN_RETURN(ERR::TEX_NOT_8BIT_PRECISION);
179 3 : if (!(color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA || color_type == PNG_COLOR_TYPE_GRAY))
180 0 : WARN_RETURN(ERR::TEX_INVALID_COLOR_TYPE);
181 :
182 3 : const int channels = png_get_channels(png_ptr, info_ptr);
183 3 : if (!(channels == 3 || channels == 4 || channels == 1))
184 0 : WARN_RETURN(ERR::TEX_FMT_INVALID);
185 :
186 3 : const size_t pitch = png_get_rowbytes(png_ptr, info_ptr);
187 3 : const std::uint32_t bpp = static_cast<std::uint32_t>(pitch / w * 8);
188 :
189 3 : size_t flags = 0;
190 3 : if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
191 2 : flags |= TEX_ALPHA;
192 3 : if (color_type == PNG_COLOR_TYPE_GRAY)
193 0 : flags |= TEX_GREY;
194 :
195 3 : const size_t img_size = pitch * h;
196 3 : std::shared_ptr<std::uint8_t> data;
197 3 : AllocateAligned(data, img_size, g_PageSize);
198 :
199 6 : std::vector<RowPtr> rows = tex_codec_alloc_rows(data.get(), h, pitch, TEX_TOP_DOWN, 0);
200 3 : png_read_image(png_ptr, (png_bytepp)&rows[0]);
201 3 : png_read_end(png_ptr, info_ptr);
202 :
203 : // success; make sure all data was consumed.
204 3 : ENSURE(stream->RemainingSize() == 0);
205 :
206 : // store image info and validate
207 3 : return t->wrap(w,h,bpp,flags,data,0);
208 : }
209 :
210 :
211 : // split out of png_encode to simplify resource cleanup and avoid
212 : // "dtor / setjmp interaction" warning.
213 0 : static Status png_encode_impl(Tex* t, png_structp png_ptr, png_infop info_ptr, DynArray* da)
214 : {
215 0 : const png_uint_32 w = (png_uint_32)t->m_Width, h = (png_uint_32)t->m_Height;
216 0 : const size_t pitch = w * t->m_Bpp / 8;
217 :
218 0 : int color_type;
219 0 : switch(t->m_Flags & (TEX_GREY|TEX_ALPHA))
220 : {
221 : case TEX_GREY|TEX_ALPHA:
222 : color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
223 : break;
224 0 : case TEX_GREY:
225 0 : color_type = PNG_COLOR_TYPE_GRAY;
226 0 : break;
227 0 : case TEX_ALPHA:
228 0 : color_type = PNG_COLOR_TYPE_RGB_ALPHA;
229 0 : break;
230 0 : default:
231 0 : color_type = PNG_COLOR_TYPE_RGB;
232 0 : break;
233 : }
234 :
235 0 : png_set_write_fn(png_ptr, da, io_write, io_flush);
236 0 : png_set_IHDR(png_ptr, info_ptr, w, h, 8, color_type,
237 : PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
238 :
239 0 : std::uint8_t* data = t->get_data();
240 0 : std::vector<RowPtr> rows = tex_codec_alloc_rows(data, h, pitch, t->m_Flags, TEX_TOP_DOWN);
241 :
242 : // PNG is native RGB.
243 0 : const int png_transforms = (t->m_Flags & TEX_BGR)? PNG_TRANSFORM_BGR : PNG_TRANSFORM_IDENTITY;
244 :
245 0 : png_set_rows(png_ptr, info_ptr, (png_bytepp)&rows[0]);
246 0 : png_write_png(png_ptr, info_ptr, png_transforms, 0);
247 :
248 0 : return INFO::OK;
249 : }
250 :
251 :
252 :
253 4 : bool TexCodecPng::is_hdr(const std::uint8_t* file) const
254 : {
255 : // don't use png_sig_cmp, so we don't pull in libpng for
256 : // this check alone (it might not actually be used).
257 4 : return *reinterpret_cast<const std::uint32_t*>(file) == FOURCC('\x89','P','N','G');
258 : }
259 :
260 :
261 0 : bool TexCodecPng::is_ext(const OsPath& extension) const
262 : {
263 0 : return extension == L".png";
264 : }
265 :
266 :
267 6 : size_t TexCodecPng::hdr_size(const std::uint8_t* /*file*/) const
268 : {
269 6 : return 0; // libpng returns decoded image data; no header
270 : }
271 :
272 0 : static void user_warning_fn(png_structp, png_const_charp warning_msg)
273 : {
274 : // Suppress this warning because it's useless and occurs on a large number of files
275 : // see https://gitea.wildfiregames.com/0ad/0ad/issues/2184
276 0 : if (strcmp(warning_msg, "iCCP: known incorrect sRGB profile") == 0)
277 : return;
278 0 : debug_printf("libpng warning: %s\n", warning_msg);
279 : }
280 :
281 : // limitation: palette images aren't supported
282 3 : Status TexCodecPng::decode(std::uint8_t* RESTRICT data, size_t size, Tex* RESTRICT t) const
283 : {
284 3 : png_infop info_ptr = 0;
285 :
286 : // allocate PNG structures; use default stderr and longjmp error handler, use custom
287 : // warning handler to filter out useless messages
288 3 : png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, user_warning_fn);
289 3 : if(!png_ptr)
290 : return ERR::FAIL;
291 3 : info_ptr = png_create_info_struct(png_ptr);
292 3 : if(!info_ptr)
293 : {
294 0 : png_destroy_read_struct(&png_ptr, &info_ptr, 0);
295 : return ERR::NO_MEM;
296 : }
297 : // setup error handling
298 3 : if(setjmp(png_jmpbuf(png_ptr)))
299 : {
300 : // libpng longjmps here after an error
301 0 : png_destroy_read_struct(&png_ptr, &info_ptr, 0);
302 : return ERR::FAIL;
303 : }
304 :
305 3 : MemoryStream stream(data, size);
306 3 : Status ret = png_decode_impl(&stream, png_ptr, info_ptr, t);
307 :
308 3 : png_destroy_read_struct(&png_ptr, &info_ptr, 0);
309 :
310 : return ret;
311 : }
312 :
313 :
314 : // limitation: palette images aren't supported
315 0 : Status TexCodecPng::encode(Tex* RESTRICT t, DynArray* RESTRICT da) const
316 : {
317 0 : png_infop info_ptr = 0;
318 :
319 : // allocate PNG structures; use default stderr and longjmp error handlers
320 0 : png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
321 0 : if(!png_ptr)
322 0 : WARN_RETURN(ERR::FAIL);
323 0 : info_ptr = png_create_info_struct(png_ptr);
324 0 : if(!info_ptr)
325 : {
326 0 : png_destroy_write_struct(&png_ptr, &info_ptr);
327 0 : WARN_RETURN(ERR::NO_MEM);
328 : }
329 : // setup error handling
330 0 : if(setjmp(png_jmpbuf(png_ptr)))
331 : {
332 : // libpng longjmps here after an error
333 0 : png_destroy_write_struct(&png_ptr, &info_ptr);
334 0 : WARN_RETURN(ERR::FAIL);
335 : }
336 :
337 0 : Status ret = png_encode_impl(t, png_ptr, info_ptr, da);
338 :
339 0 : png_destroy_write_struct(&png_ptr, &info_ptr);
340 :
341 : return ret;
342 : }
|