1 // Copyright 2012 Google Inc. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the COPYING file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 // -----------------------------------------------------------------------------
9 //
10 // PNG decode.
11 
12 #include "./pngdec.h"
13 
14 #ifdef HAVE_CONFIG_H
15 #include "webp/config.h"
16 #endif
17 
18 #include <stdio.h>
19 
20 #ifdef WEBP_HAVE_PNG
21 #ifndef PNG_USER_MEM_SUPPORTED
22 #define PNG_USER_MEM_SUPPORTED  // for png_create_read_struct_2
23 #endif
24 #include <png.h>
25 #include <setjmp.h>   // note: this must be included *after* png.h
26 #include <stdlib.h>
27 #include <string.h>
28 
29 #include "webp/encode.h"
30 #include "./imageio_util.h"
31 #include "./metadata.h"
32 
33 #define LOCAL_PNG_VERSION ((PNG_LIBPNG_VER_MAJOR << 8) | PNG_LIBPNG_VER_MINOR)
34 #define LOCAL_PNG_PREREQ(maj, min) \
35    (LOCAL_PNG_VERSION >= (((maj) << 8) | (min)))
36 
error_function(png_structp png,png_const_charp error)37 static void PNGAPI error_function(png_structp png, png_const_charp error) {
38   if (error != NULL) fprintf(stderr, "libpng error: %s\n", error);
39   longjmp(png_jmpbuf(png), 1);
40 }
41 
42 #if LOCAL_PNG_PREREQ(1,4)
43 typedef png_alloc_size_t LocalPngAllocSize;
44 #else
45 typedef png_size_t LocalPngAllocSize;
46 #endif
47 
MallocFunc(png_structp png_ptr,LocalPngAllocSize size)48 static png_voidp MallocFunc(png_structp png_ptr, LocalPngAllocSize size) {
49   (void)png_ptr;
50   if (size != (size_t)size) return NULL;
51   if (!ImgIoUtilCheckSizeArgumentsOverflow(size, 1)) return NULL;
52   return (png_voidp)malloc((size_t)size);
53 }
54 
FreeFunc(png_structp png_ptr,png_voidp ptr)55 static void FreeFunc(png_structp png_ptr, png_voidp ptr) {
56   (void)png_ptr;
57   free(ptr);
58 }
59 
60 // Converts the NULL terminated 'hexstring' which contains 2-byte character
61 // representations of hex values to raw data.
62 // 'hexstring' may contain values consisting of [A-F][a-f][0-9] in pairs,
63 // e.g., 7af2..., separated by any number of newlines.
64 // 'expected_length' is the anticipated processed size.
65 // On success the raw buffer is returned with its length equivalent to
66 // 'expected_length'. NULL is returned if the processed length is less than
67 // 'expected_length' or any character aside from those above is encountered.
68 // The returned buffer must be freed by the caller.
HexStringToBytes(const char * hexstring,size_t expected_length)69 static uint8_t* HexStringToBytes(const char* hexstring,
70                                  size_t expected_length) {
71   const char* src = hexstring;
72   size_t actual_length = 0;
73   uint8_t* const raw_data = (uint8_t*)malloc(expected_length);
74   uint8_t* dst;
75 
76   if (raw_data == NULL) return NULL;
77 
78   for (dst = raw_data; actual_length < expected_length && *src != '\0'; ++src) {
79     char* end;
80     char val[3];
81     if (*src == '\n') continue;
82     val[0] = *src++;
83     val[1] = *src;
84     val[2] = '\0';
85     *dst++ = (uint8_t)strtol(val, &end, 16);
86     if (end != val + 2) break;
87     ++actual_length;
88   }
89 
90   if (actual_length != expected_length) {
91     free(raw_data);
92     return NULL;
93   }
94   return raw_data;
95 }
96 
ProcessRawProfile(const char * profile,size_t profile_len,MetadataPayload * const payload)97 static int ProcessRawProfile(const char* profile, size_t profile_len,
98                              MetadataPayload* const payload) {
99   const char* src = profile;
100   char* end;
101   int expected_length;
102 
103   if (profile == NULL || profile_len == 0) return 0;
104 
105   // ImageMagick formats 'raw profiles' as
106   // '\n<name>\n<length>(%8lu)\n<hex payload>\n'.
107   if (*src != '\n') {
108     fprintf(stderr, "Malformed raw profile, expected '\\n' got '\\x%.2X'\n",
109             *src);
110     return 0;
111   }
112   ++src;
113   // skip the profile name and extract the length.
114   while (*src != '\0' && *src++ != '\n') {}
115   expected_length = (int)strtol(src, &end, 10);
116   if (*end != '\n') {
117     fprintf(stderr, "Malformed raw profile, expected '\\n' got '\\x%.2X'\n",
118             *end);
119     return 0;
120   }
121   ++end;
122 
123   // 'end' now points to the profile payload.
124   payload->bytes = HexStringToBytes(end, expected_length);
125   if (payload->bytes == NULL) return 0;
126   payload->size = expected_length;
127   return 1;
128 }
129 
130 static const struct {
131   const char* name;
132   int (*process)(const char* profile, size_t profile_len,
133                  MetadataPayload* const payload);
134   size_t storage_offset;
135 } kPNGMetadataMap[] = {
136   // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PNG.html#TextualData
137   // See also: ExifTool on CPAN.
138   { "Raw profile type exif", ProcessRawProfile, METADATA_OFFSET(exif) },
139   { "Raw profile type xmp",  ProcessRawProfile, METADATA_OFFSET(xmp) },
140   // Exiftool puts exif data in APP1 chunk, too.
141   { "Raw profile type APP1", ProcessRawProfile, METADATA_OFFSET(exif) },
142   // XMP Specification Part 3, Section 3 #PNG
143   { "XML:com.adobe.xmp",     MetadataCopy,      METADATA_OFFSET(xmp) },
144   { NULL, NULL, 0 },
145 };
146 
147 // Looks for metadata at both the beginning and end of the PNG file, giving
148 // preference to the head.
149 // Returns true on success. The caller must use MetadataFree() on 'metadata' in
150 // all cases.
ExtractMetadataFromPNG(png_structp png,png_infop const head_info,png_infop const end_info,Metadata * const metadata)151 static int ExtractMetadataFromPNG(png_structp png,
152                                   png_infop const head_info,
153                                   png_infop const end_info,
154                                   Metadata* const metadata) {
155   int p;
156 
157   for (p = 0; p < 2; ++p)  {
158     png_infop const info = (p == 0) ? head_info : end_info;
159     png_textp text = NULL;
160     const png_uint_32 num = png_get_text(png, info, &text, NULL);
161     png_uint_32 i;
162     // Look for EXIF / XMP metadata.
163     for (i = 0; i < num; ++i, ++text) {
164       int j;
165       for (j = 0; kPNGMetadataMap[j].name != NULL; ++j) {
166         if (!strcmp(text->key, kPNGMetadataMap[j].name)) {
167           MetadataPayload* const payload =
168               (MetadataPayload*)((uint8_t*)metadata +
169                                  kPNGMetadataMap[j].storage_offset);
170           png_size_t text_length;
171           switch (text->compression) {
172 #ifdef PNG_iTXt_SUPPORTED
173             case PNG_ITXT_COMPRESSION_NONE:
174             case PNG_ITXT_COMPRESSION_zTXt:
175               text_length = text->itxt_length;
176               break;
177 #endif
178             case PNG_TEXT_COMPRESSION_NONE:
179             case PNG_TEXT_COMPRESSION_zTXt:
180             default:
181               text_length = text->text_length;
182               break;
183           }
184           if (payload->bytes != NULL) {
185             fprintf(stderr, "Ignoring additional '%s'\n", text->key);
186           } else if (!kPNGMetadataMap[j].process(text->text, text_length,
187                                                  payload)) {
188             fprintf(stderr, "Failed to process: '%s'\n", text->key);
189             return 0;
190           }
191           break;
192         }
193       }
194     }
195     // Look for an ICC profile.
196     {
197       png_charp name;
198       int comp_type;
199 #if LOCAL_PNG_PREREQ(1,5)
200       png_bytep profile;
201 #else
202       png_charp profile;
203 #endif
204       png_uint_32 len;
205 
206       if (png_get_iCCP(png, info,
207                        &name, &comp_type, &profile, &len) == PNG_INFO_iCCP) {
208         if (!MetadataCopy((const char*)profile, len, &metadata->iccp)) return 0;
209       }
210     }
211   }
212   return 1;
213 }
214 
215 typedef struct {
216   const uint8_t* data;
217   size_t data_size;
218   png_size_t offset;
219 } PNGReadContext;
220 
ReadFunc(png_structp png_ptr,png_bytep data,png_size_t length)221 static void ReadFunc(png_structp png_ptr, png_bytep data, png_size_t length) {
222   PNGReadContext* const ctx = (PNGReadContext*)png_get_io_ptr(png_ptr);
223   if (ctx->data_size - ctx->offset < length) {
224     png_error(png_ptr, "ReadFunc: invalid read length (overflow)!");
225   }
226   memcpy(data, ctx->data + ctx->offset, length);
227   ctx->offset += length;
228 }
229 
ReadPNG(const uint8_t * const data,size_t data_size,struct WebPPicture * const pic,int keep_alpha,struct Metadata * const metadata)230 int ReadPNG(const uint8_t* const data, size_t data_size,
231             struct WebPPicture* const pic,
232             int keep_alpha, struct Metadata* const metadata) {
233   volatile png_structp png = NULL;
234   volatile png_infop info = NULL;
235   volatile png_infop end_info = NULL;
236   PNGReadContext context = { NULL, 0, 0 };
237   int color_type, bit_depth, interlaced;
238   int has_alpha;
239   int num_passes;
240   int p;
241   volatile int ok = 0;
242   png_uint_32 width, height, y;
243   int64_t stride;
244   uint8_t* volatile rgb = NULL;
245 
246   if (data == NULL || data_size == 0 || pic == NULL) return 0;
247 
248   context.data = data;
249   context.data_size = data_size;
250 
251   png = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL,
252                                  NULL, MallocFunc, FreeFunc);
253   if (png == NULL) goto End;
254 
255   png_set_error_fn(png, 0, error_function, NULL);
256   if (setjmp(png_jmpbuf(png))) {
257  Error:
258     MetadataFree(metadata);
259     goto End;
260   }
261 
262   // If it looks like the bitstream is going to need more memory than libpng's
263   // internal limit (default: 8M), try to (reasonably) raise it.
264   if (data_size > png_get_chunk_malloc_max(png) && data_size < (1u << 24)) {
265     png_set_chunk_malloc_max(png, data_size);
266   }
267 
268   info = png_create_info_struct(png);
269   if (info == NULL) goto Error;
270   end_info = png_create_info_struct(png);
271   if (end_info == NULL) goto Error;
272 
273   png_set_read_fn(png, &context, ReadFunc);
274   png_read_info(png, info);
275   if (!png_get_IHDR(png, info,
276                     &width, &height, &bit_depth, &color_type, &interlaced,
277                     NULL, NULL)) goto Error;
278 
279   png_set_strip_16(png);
280   png_set_packing(png);
281   if (color_type == PNG_COLOR_TYPE_PALETTE) {
282     png_set_palette_to_rgb(png);
283   }
284   if (color_type == PNG_COLOR_TYPE_GRAY ||
285       color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
286     if (bit_depth < 8) {
287       png_set_expand_gray_1_2_4_to_8(png);
288     }
289     png_set_gray_to_rgb(png);
290   }
291   if (png_get_valid(png, info, PNG_INFO_tRNS)) {
292     png_set_tRNS_to_alpha(png);
293     has_alpha = 1;
294   } else {
295     has_alpha = !!(color_type & PNG_COLOR_MASK_ALPHA);
296   }
297 
298   // Apply gamma correction if needed.
299   {
300     double image_gamma = 1 / 2.2, screen_gamma = 2.2;
301     int srgb_intent;
302     if (png_get_sRGB(png, info, &srgb_intent) ||
303         png_get_gAMA(png, info, &image_gamma)) {
304       png_set_gamma(png, screen_gamma, image_gamma);
305     }
306   }
307 
308   if (!keep_alpha) {
309     png_set_strip_alpha(png);
310     has_alpha = 0;
311   }
312 
313   num_passes = png_set_interlace_handling(png);
314   png_read_update_info(png, info);
315 
316   stride = (int64_t)(has_alpha ? 4 : 3) * width * sizeof(*rgb);
317   if (stride != (int)stride ||
318       !ImgIoUtilCheckSizeArgumentsOverflow(stride, height)) {
319     goto Error;
320   }
321 
322   rgb = (uint8_t*)malloc((size_t)stride * height);
323   if (rgb == NULL) goto Error;
324   for (p = 0; p < num_passes; ++p) {
325     png_bytep row = rgb;
326     for (y = 0; y < height; ++y) {
327       png_read_rows(png, &row, NULL, 1);
328       row += stride;
329     }
330   }
331   png_read_end(png, end_info);
332 
333   if (metadata != NULL &&
334       !ExtractMetadataFromPNG(png, info, end_info, metadata)) {
335     fprintf(stderr, "Error extracting PNG metadata!\n");
336     goto Error;
337   }
338 
339   pic->width = (int)width;
340   pic->height = (int)height;
341   ok = has_alpha ? WebPPictureImportRGBA(pic, rgb, (int)stride)
342                  : WebPPictureImportRGB(pic, rgb, (int)stride);
343 
344   if (!ok) {
345     goto Error;
346   }
347 
348  End:
349   if (png != NULL) {
350     png_destroy_read_struct((png_structpp)&png,
351                             (png_infopp)&info, (png_infopp)&end_info);
352   }
353   free(rgb);
354   return ok;
355 }
356 #else  // !WEBP_HAVE_PNG
ReadPNG(const uint8_t * const data,size_t data_size,struct WebPPicture * const pic,int keep_alpha,struct Metadata * const metadata)357 int ReadPNG(const uint8_t* const data, size_t data_size,
358             struct WebPPicture* const pic,
359             int keep_alpha, struct Metadata* const metadata) {
360   (void)data;
361   (void)data_size;
362   (void)pic;
363   (void)keep_alpha;
364   (void)metadata;
365   fprintf(stderr, "PNG support not compiled. Please install the libpng "
366           "development package before building.\n");
367   return 0;
368 }
369 #endif  // WEBP_HAVE_PNG
370 
371 // -----------------------------------------------------------------------------
372