1 /*
2     SDL_image:  An example image loading library for use with SDL
3     Copyright (C) 1997-2009 Sam Lantinga
4 
5     This library is free software; you can redistribute it and/or
6     modify it under the terms of the GNU Lesser General Public
7     License as published by the Free Software Foundation; either
8     version 2.1 of the License, or (at your option) any later version.
9 
10     This library is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13     Lesser General Public License for more details.
14 
15     You should have received a copy of the GNU Lesser General Public
16     License along with this library; if not, write to the Free Software
17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18 
19     Sam Lantinga
20     slouken@libsdl.org
21 */
22 
23 #if !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND)
24 
25 /* This is a PNG image file loading framework */
26 
27 #include <stdlib.h>
28 #include <stdio.h>
29 
30 #include "SDL_image.h"
31 
32 #ifdef LOAD_PNG
33 
34 /*=============================================================================
35         File: SDL_png.c
36      Purpose: A PNG loader and saver for the SDL library
37     Revision:
38   Created by: Philippe Lavoie          (2 November 1998)
39               lavoie@zeus.genie.uottawa.ca
40  Modified by:
41 
42  Copyright notice:
43           Copyright (C) 1998 Philippe Lavoie
44 
45           This library is free software; you can redistribute it and/or
46           modify it under the terms of the GNU Library General Public
47           License as published by the Free Software Foundation; either
48           version 2 of the License, or (at your option) any later version.
49 
50           This library is distributed in the hope that it will be useful,
51           but WITHOUT ANY WARRANTY; without even the implied warranty of
52           MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
53           Library General Public License for more details.
54 
55           You should have received a copy of the GNU Library General Public
56           License along with this library; if not, write to the Free
57           Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
58 
59     Comments: The load and save routine are basically the ones you can find
60              in the example.c file from the libpng distribution.
61 
62   Changes:
63     5/17/99 - Modified to use the new SDL data sources - Sam Lantinga
64 
65 =============================================================================*/
66 
67 #include "SDL_endian.h"
68 
69 #ifdef macintosh
70 #define MACOS
71 #endif
72 #include <png.h>
73 
74 
75 static struct {
76  int loaded;
77  void *handle;
78  png_infop (*png_create_info_struct) (png_structp png_ptr);
79  png_structp (*png_create_read_struct) (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn);
80  void (*png_destroy_read_struct) (png_structpp png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr);
81  png_uint_32 (*png_get_IHDR) (png_structp png_ptr, png_infop info_ptr, png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type, int *interlace_method, int *compression_method, int *filter_method);
82  png_voidp (*png_get_io_ptr) (png_structp png_ptr);
83  png_uint_32 (*png_get_tRNS) (png_structp png_ptr, png_infop info_ptr, png_bytep *trans, int *num_trans, png_color_16p *trans_values);
84  png_uint_32 (*png_get_valid) (png_structp png_ptr, png_infop info_ptr, png_uint_32 flag);
85  void (*png_read_image) (png_structp png_ptr, png_bytepp image);
86  void (*png_read_info) (png_structp png_ptr, png_infop info_ptr);
87  void (*png_read_update_info) (png_structp png_ptr, png_infop info_ptr);
88  void (*png_set_expand) (png_structp png_ptr);
89  void (*png_set_gray_to_rgb) (png_structp png_ptr);
90  void (*png_set_packing) (png_structp png_ptr);
91  void (*png_set_read_fn) (png_structp png_ptr, png_voidp io_ptr, png_rw_ptr read_data_fn);
92  void (*png_set_strip_16) (png_structp png_ptr);
93  int (*png_sig_cmp) (png_bytep sig, png_size_t start, png_size_t num_to_check);
94 } lib;
95 
96 #ifdef LOAD_PNG_DYNAMIC
IMG_InitPNG()97 int IMG_InitPNG()
98 {
99  if ( lib.loaded == 0 ) {
100    lib.handle = SDL_LoadObject(LOAD_PNG_DYNAMIC);
101    if ( lib.handle == NULL ) {
102      return -1;
103    }
104    lib.png_create_info_struct =
105      (png_infop (*) (png_structp))
106      SDL_LoadFunction(lib.handle, "png_create_info_struct");
107    if ( lib.png_create_info_struct == NULL ) {
108      SDL_UnloadObject(lib.handle);
109      return -1;
110    }
111    lib.png_create_read_struct =
112      (png_structp (*) (png_const_charp, png_voidp, png_error_ptr, png_error_ptr))
113      SDL_LoadFunction(lib.handle, "png_create_read_struct");
114    if ( lib.png_create_read_struct == NULL ) {
115      SDL_UnloadObject(lib.handle);
116      return -1;
117    }
118    lib.png_destroy_read_struct =
119      (void (*) (png_structpp, png_infopp, png_infopp))
120      SDL_LoadFunction(lib.handle, "png_destroy_read_struct");
121    if ( lib.png_destroy_read_struct == NULL ) {
122      SDL_UnloadObject(lib.handle);
123      return -1;
124    }
125    lib.png_get_IHDR =
126      (png_uint_32 (*) (png_structp, png_infop, png_uint_32 *, png_uint_32 *, int *, int *, int *, int *, int *))
127      SDL_LoadFunction(lib.handle, "png_get_IHDR");
128    if ( lib.png_get_IHDR == NULL ) {
129      SDL_UnloadObject(lib.handle);
130      return -1;
131    }
132    lib.png_get_io_ptr =
133      (png_voidp (*) (png_structp))
134      SDL_LoadFunction(lib.handle, "png_get_io_ptr");
135    if ( lib.png_get_io_ptr == NULL ) {
136      SDL_UnloadObject(lib.handle);
137      return -1;
138    }
139    lib.png_get_tRNS =
140      (png_uint_32 (*) (png_structp, png_infop, png_bytep *, int *, png_color_16p *))
141      SDL_LoadFunction(lib.handle, "png_get_tRNS");
142    if ( lib.png_get_tRNS == NULL ) {
143      SDL_UnloadObject(lib.handle);
144      return -1;
145    }
146    lib.png_get_valid =
147      (png_uint_32 (*) (png_structp, png_infop, png_uint_32))
148      SDL_LoadFunction(lib.handle, "png_get_valid");
149    if ( lib.png_get_valid == NULL ) {
150      SDL_UnloadObject(lib.handle);
151      return -1;
152    }
153    lib.png_read_image =
154      (void (*) (png_structp, png_bytepp))
155      SDL_LoadFunction(lib.handle, "png_read_image");
156    if ( lib.png_read_image == NULL ) {
157      SDL_UnloadObject(lib.handle);
158      return -1;
159    }
160    lib.png_read_info =
161      (void (*) (png_structp, png_infop))
162      SDL_LoadFunction(lib.handle, "png_read_info");
163    if ( lib.png_read_info == NULL ) {
164      SDL_UnloadObject(lib.handle);
165      return -1;
166    }
167    lib.png_read_update_info =
168      (void (*) (png_structp, png_infop))
169      SDL_LoadFunction(lib.handle, "png_read_update_info");
170    if ( lib.png_read_update_info == NULL ) {
171      SDL_UnloadObject(lib.handle);
172      return -1;
173    }
174    lib.png_set_expand =
175      (void (*) (png_structp))
176      SDL_LoadFunction(lib.handle, "png_set_expand");
177    if ( lib.png_set_expand == NULL ) {
178      SDL_UnloadObject(lib.handle);
179      return -1;
180    }
181    lib.png_set_gray_to_rgb =
182      (void (*) (png_structp))
183      SDL_LoadFunction(lib.handle, "png_set_gray_to_rgb");
184    if ( lib.png_set_gray_to_rgb == NULL ) {
185      SDL_UnloadObject(lib.handle);
186      return -1;
187    }
188    lib.png_set_packing =
189      (void (*) (png_structp))
190      SDL_LoadFunction(lib.handle, "png_set_packing");
191    if ( lib.png_set_packing == NULL ) {
192      SDL_UnloadObject(lib.handle);
193      return -1;
194    }
195    lib.png_set_read_fn =
196      (void (*) (png_structp, png_voidp, png_rw_ptr))
197      SDL_LoadFunction(lib.handle, "png_set_read_fn");
198    if ( lib.png_set_read_fn == NULL ) {
199      SDL_UnloadObject(lib.handle);
200      return -1;
201    }
202    lib.png_set_strip_16 =
203      (void (*) (png_structp))
204      SDL_LoadFunction(lib.handle, "png_set_strip_16");
205    if ( lib.png_set_strip_16 == NULL ) {
206      SDL_UnloadObject(lib.handle);
207      return -1;
208    }
209    lib.png_sig_cmp =
210      (int (*) (png_bytep, png_size_t, png_size_t))
211      SDL_LoadFunction(lib.handle, "png_sig_cmp");
212    if ( lib.png_sig_cmp == NULL ) {
213      SDL_UnloadObject(lib.handle);
214      return -1;
215    }
216  }
217  ++lib.loaded;
218 
219  return 0;
220 }
IMG_QuitPNG()221 void IMG_QuitPNG()
222 {
223  if ( lib.loaded == 0 ) {
224    return;
225  }
226  if ( lib.loaded == 1 ) {
227    SDL_UnloadObject(lib.handle);
228  }
229  --lib.loaded;
230 }
231 #else
IMG_InitPNG()232 int IMG_InitPNG()
233 {
234  if ( lib.loaded == 0 ) {
235    lib.png_create_info_struct = png_create_info_struct;
236    lib.png_create_read_struct = png_create_read_struct;
237    lib.png_destroy_read_struct = png_destroy_read_struct;
238    lib.png_get_IHDR = png_get_IHDR;
239    lib.png_get_io_ptr = png_get_io_ptr;
240    lib.png_get_tRNS = png_get_tRNS;
241    lib.png_get_valid = png_get_valid;
242    lib.png_read_image = png_read_image;
243    lib.png_read_info = png_read_info;
244    lib.png_read_update_info = png_read_update_info;
245    lib.png_set_expand = png_set_expand;
246    lib.png_set_gray_to_rgb = png_set_gray_to_rgb;
247    lib.png_set_packing = png_set_packing;
248    lib.png_set_read_fn = png_set_read_fn;
249    lib.png_set_strip_16 = png_set_strip_16;
250    lib.png_sig_cmp = png_sig_cmp;
251  }
252  ++lib.loaded;
253 
254  return 0;
255 }
IMG_QuitPNG()256 void IMG_QuitPNG()
257 {
258  if ( lib.loaded == 0 ) {
259    return;
260  }
261  if ( lib.loaded == 1 ) {
262  }
263  --lib.loaded;
264 }
265 #endif /* LOAD_PNG_DYNAMIC */
266 
267 /* See if an image is contained in a data source */
IMG_isPNG(SDL_RWops * src)268 int IMG_isPNG(SDL_RWops *src)
269 {
270  int start;
271  int is_PNG;
272  Uint8 magic[4];
273 
274  if ( !src )
275    return 0;
276  start = SDL_RWtell(src);
277  is_PNG = 0;
278  if ( SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic) ) {
279                 if ( magic[0] == 0x89 &&
280                      magic[1] == 'P' &&
281                      magic[2] == 'N' &&
282                      magic[3] == 'G' ) {
283      is_PNG = 1;
284    }
285  }
286  SDL_RWseek(src, start, RW_SEEK_SET);
287  return(is_PNG);
288 }
289 
290 /* Load a PNG type image from an SDL datasource */
png_read_data(png_structp ctx,png_bytep area,png_size_t size)291 static void png_read_data(png_structp ctx, png_bytep area, png_size_t size)
292 {
293  SDL_RWops *src;
294 
295  src = (SDL_RWops *)lib.png_get_io_ptr(ctx);
296  SDL_RWread(src, area, size, 1);
297 }
IMG_LoadPNG_RW(SDL_RWops * src)298 SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src)
299 {
300  int start;
301  const char *error;
302  SDL_Surface *volatile surface;
303  png_structp png_ptr;
304  png_infop info_ptr;
305  png_uint_32 width, height;
306  int bit_depth, color_type, interlace_type;
307  Uint32 Rmask;
308  Uint32 Gmask;
309  Uint32 Bmask;
310  Uint32 Amask;
311  SDL_Palette *palette;
312  png_bytep *volatile row_pointers;
313  int row, i;
314  volatile int ckey = -1;
315  png_color_16 *transv;
316 
317  if ( !src ) {
318    /* The error message has been set in SDL_RWFromFile */
319    return NULL;
320  }
321  start = SDL_RWtell(src);
322 
323  if ( !IMG_Init(IMG_INIT_PNG) ) {
324    return NULL;
325  }
326 
327  /* Initialize the data we will clean up when we're done */
328  error = NULL;
329  png_ptr = NULL; info_ptr = NULL; row_pointers = NULL; surface = NULL;
330 
331  /* Create the PNG loading context structure */
332  png_ptr = lib.png_create_read_struct(PNG_LIBPNG_VER_STRING,
333            NULL,NULL,NULL);
334  if (png_ptr == NULL){
335    error = "Couldn't allocate memory for PNG file or incompatible PNG dll";
336    goto done;
337  }
338 
339   /* Allocate/initialize the memory for image information.  REQUIRED. */
340  info_ptr = lib.png_create_info_struct(png_ptr);
341  if (info_ptr == NULL) {
342    error = "Couldn't create image information for PNG file";
343    goto done;
344  }
345 
346  /* Set error handling if you are using setjmp/longjmp method (this is
347   * the normal method of doing things with libpng).  REQUIRED unless you
348   * set up your own error handlers in png_create_read_struct() earlier.
349   */
350  if ( setjmp(png_ptr->jmpbuf) ) {
351    error = "Error reading the PNG file.";
352    goto done;
353  }
354 
355  /* Set up the input control */
356  lib.png_set_read_fn(png_ptr, src, png_read_data);
357 
358  /* Read PNG header info */
359  lib.png_read_info(png_ptr, info_ptr);
360  lib.png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
361      &color_type, &interlace_type, NULL, NULL);
362 
363  /* tell libpng to strip 16 bit/color files down to 8 bits/color */
364  lib.png_set_strip_16(png_ptr) ;
365 
366  /* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
367   * byte into separate bytes (useful for paletted and grayscale images).
368   */
369  lib.png_set_packing(png_ptr);
370 
371  /* scale greyscale values to the range 0..255 */
372  if(color_type == PNG_COLOR_TYPE_GRAY)
373    lib.png_set_expand(png_ptr);
374 
375  /* For images with a single "transparent colour", set colour key;
376     if more than one index has transparency, or if partially transparent
377     entries exist, use full alpha channel */
378  if (lib.png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
379          int num_trans;
380    Uint8 *trans;
381    lib.png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
382           &transv);
383    if(color_type == PNG_COLOR_TYPE_PALETTE) {
384        /* Check if all tRNS entries are opaque except one */
385        int i, t = -1;
386        for(i = 0; i < num_trans; i++)
387      if(trans[i] == 0) {
388          if(t >= 0)
389        break;
390          t = i;
391      } else if(trans[i] != 255)
392          break;
393        if(i == num_trans) {
394      /* exactly one transparent index */
395      ckey = t;
396        } else {
397      /* more than one transparent index, or translucency */
398      lib.png_set_expand(png_ptr);
399        }
400    } else
401        ckey = 0; /* actual value will be set later */
402  }
403 
404  if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA )
405    lib.png_set_gray_to_rgb(png_ptr);
406 
407  lib.png_read_update_info(png_ptr, info_ptr);
408 
409  lib.png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
410      &color_type, &interlace_type, NULL, NULL);
411 
412  /* Allocate the SDL surface to hold the image */
413  Rmask = Gmask = Bmask = Amask = 0 ;
414  if ( color_type != PNG_COLOR_TYPE_PALETTE ) {
415    if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) {
416      Rmask = 0x000000FF;
417      Gmask = 0x0000FF00;
418      Bmask = 0x00FF0000;
419      Amask = (info_ptr->channels == 4) ? 0xFF000000 : 0;
420    } else {
421            int s = (info_ptr->channels == 4) ? 0 : 8;
422      Rmask = 0xFF000000 >> s;
423      Gmask = 0x00FF0000 >> s;
424      Bmask = 0x0000FF00 >> s;
425      Amask = 0x000000FF >> s;
426    }
427  }
428  surface = SDL_AllocSurface(SDL_SWSURFACE, width, height,
429      bit_depth*info_ptr->channels, Rmask,Gmask,Bmask,Amask);
430  if ( surface == NULL ) {
431    error = "Out of memory";
432    goto done;
433  }
434 
435  if(ckey != -1) {
436          if(color_type != PNG_COLOR_TYPE_PALETTE)
437      /* FIXME: Should these be truncated or shifted down? */
438            ckey = SDL_MapRGB(surface->format,
439                       (Uint8)transv->red,
440                       (Uint8)transv->green,
441                       (Uint8)transv->blue);
442          SDL_SetColorKey(surface, SDL_SRCCOLORKEY, ckey);
443  }
444 
445  /* Create the array of pointers to image data */
446  row_pointers = (png_bytep*) malloc(sizeof(png_bytep)*height);
447  if ( (row_pointers == NULL) ) {
448    error = "Out of memory";
449    goto done;
450  }
451  for (row = 0; row < (int)height; row++) {
452    row_pointers[row] = (png_bytep)
453        (Uint8 *)surface->pixels + row*surface->pitch;
454  }
455 
456  /* Read the entire image in one go */
457  lib.png_read_image(png_ptr, row_pointers);
458 
459  /* and we're done!  (png_read_end() can be omitted if no processing of
460   * post-IDAT text/time/etc. is desired)
461   * In some cases it can't read PNG's created by some popular programs (ACDSEE),
462   * we do not want to process comments, so we omit png_read_end
463 
464  lib.png_read_end(png_ptr, info_ptr);
465  */
466 
467  /* Load the palette, if any */
468  palette = surface->format->palette;
469  if ( palette ) {
470      if(color_type == PNG_COLOR_TYPE_GRAY) {
471    palette->ncolors = 256;
472    for(i = 0; i < 256; i++) {
473        palette->colors[i].r = i;
474        palette->colors[i].g = i;
475        palette->colors[i].b = i;
476    }
477      } else if (info_ptr->num_palette > 0 ) {
478    palette->ncolors = info_ptr->num_palette;
479    for( i=0; i<info_ptr->num_palette; ++i ) {
480        palette->colors[i].b = info_ptr->palette[i].blue;
481        palette->colors[i].g = info_ptr->palette[i].green;
482        palette->colors[i].r = info_ptr->palette[i].red;
483    }
484      }
485  }
486 
487 done:  /* Clean up and return */
488  if ( png_ptr ) {
489    lib.png_destroy_read_struct(&png_ptr,
490                            info_ptr ? &info_ptr : (png_infopp)0,
491                (png_infopp)0);
492  }
493  if ( row_pointers ) {
494    free(row_pointers);
495  }
496  if ( error ) {
497    SDL_RWseek(src, start, RW_SEEK_SET);
498    if ( surface ) {
499      SDL_FreeSurface(surface);
500      surface = NULL;
501    }
502    IMG_SetError(error);
503  }
504  return(surface);
505 }
506 
507 #else
508 
IMG_InitPNG()509 int IMG_InitPNG()
510 {
511  IMG_SetError("PNG images are not supported");
512  return(-1);
513 }
514 
IMG_QuitPNG()515 void IMG_QuitPNG()
516 {
517 }
518 
519 /* See if an image is contained in a data source */
IMG_isPNG(SDL_RWops * src)520 int IMG_isPNG(SDL_RWops *src)
521 {
522  return(0);
523 }
524 
525 /* Load a PNG type image from an SDL datasource */
IMG_LoadPNG_RW(SDL_RWops * src)526 SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src)
527 {
528  return(NULL);
529 }
530 
531 #endif /* LOAD_PNG */
532 
533 #endif /* !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) */
534