IMG_jpg.c
author Sam Lantinga <slouken@libsdl.org>
Fri, 12 May 2006 05:08:03 +0000
changeset 143 e01fee7bdf3b
parent 123 1f7908a9cabb
child 146 aaa5876f41ab
permissions -rw-r--r--
Added support for dynamically loading libjpeg, libpng, and libtiff.
     1 /*
     2     SDL_image:  An example image loading library for use with SDL
     3     Copyright (C) 1997-2006 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 /* This is a JPEG image file loading framework */
    24 
    25 #include <stdio.h>
    26 #include <string.h>
    27 #include <setjmp.h>
    28 
    29 #include "SDL_image.h"
    30 
    31 #ifdef LOAD_JPG
    32 
    33 #include <jpeglib.h>
    34 
    35 /* Define this for fast loading and not as good image quality */
    36 /*#define FAST_JPEG*/
    37 
    38 /* Define this for quicker (but less perfect) JPEG identification */
    39 #define FAST_IS_JPEG
    40 
    41 static struct {
    42 	int loaded;
    43 	void *handle;
    44 	void (*jpeg_calc_output_dimensions) (j_decompress_ptr cinfo);
    45 	void (*jpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize);
    46 	void (*jpeg_destroy_decompress) (j_decompress_ptr cinfo);
    47 	boolean (*jpeg_finish_decompress) (j_decompress_ptr cinfo);
    48 	int (*jpeg_read_header) (j_decompress_ptr cinfo, boolean require_image);
    49 	JDIMENSION (*jpeg_read_scanlines) (j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines);
    50 	boolean (*jpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired);
    51 	boolean (*jpeg_start_decompress) (j_decompress_ptr cinfo);
    52 	struct jpeg_error_mgr * (*jpeg_std_error) (struct jpeg_error_mgr * err);
    53 } lib;
    54 
    55 #ifdef LOAD_JPG_DYNAMIC
    56 int IMG_InitJPG()
    57 {
    58 	if ( lib.loaded == 0 ) {
    59 		lib.handle = SDL_LoadObject(LOAD_JPG_DYNAMIC);
    60 		if ( lib.handle == NULL ) {
    61 			return -1;
    62 		}
    63 		lib.jpeg_calc_output_dimensions =
    64 			(void (*) (j_decompress_ptr))
    65 			SDL_LoadFunction(lib.handle, "jpeg_calc_output_dimensions");
    66 		if ( lib.jpeg_calc_output_dimensions == NULL ) {
    67 			SDL_UnloadObject(lib.handle);
    68 			return -1;
    69 		}
    70 		lib.jpeg_CreateDecompress = 
    71 			(void (*) (j_decompress_ptr, int, size_t))
    72 			SDL_LoadFunction(lib.handle, "jpeg_CreateDecompress");
    73 		if ( lib.jpeg_CreateDecompress == NULL ) {
    74 			SDL_UnloadObject(lib.handle);
    75 			return -1;
    76 		}
    77 		lib.jpeg_destroy_decompress = 
    78 			(void (*) (j_decompress_ptr))
    79 			SDL_LoadFunction(lib.handle, "jpeg_destroy_decompress");
    80 		if ( lib.jpeg_destroy_decompress == NULL ) {
    81 			SDL_UnloadObject(lib.handle);
    82 			return -1;
    83 		}
    84 		lib.jpeg_finish_decompress = 
    85 			(boolean (*) (j_decompress_ptr))
    86 			SDL_LoadFunction(lib.handle, "jpeg_finish_decompress");
    87 		if ( lib.jpeg_finish_decompress == NULL ) {
    88 			SDL_UnloadObject(lib.handle);
    89 			return -1;
    90 		}
    91 		lib.jpeg_read_header = 
    92 			(int (*) (j_decompress_ptr, boolean))
    93 			SDL_LoadFunction(lib.handle, "jpeg_read_header");
    94 		if ( lib.jpeg_read_header == NULL ) {
    95 			SDL_UnloadObject(lib.handle);
    96 			return -1;
    97 		}
    98 		lib.jpeg_read_scanlines = 
    99 			(JDIMENSION (*) (j_decompress_ptr, JSAMPARRAY, JDIMENSION))
   100 			SDL_LoadFunction(lib.handle, "jpeg_read_scanlines");
   101 		if ( lib.jpeg_read_scanlines == NULL ) {
   102 			SDL_UnloadObject(lib.handle);
   103 			return -1;
   104 		}
   105 		lib.jpeg_resync_to_restart = 
   106 			(boolean (*) (j_decompress_ptr, int))
   107 			SDL_LoadFunction(lib.handle, "jpeg_resync_to_restart");
   108 		if ( lib.jpeg_resync_to_restart == NULL ) {
   109 			SDL_UnloadObject(lib.handle);
   110 			return -1;
   111 		}
   112 		lib.jpeg_start_decompress = 
   113 			(boolean (*) (j_decompress_ptr))
   114 			SDL_LoadFunction(lib.handle, "jpeg_start_decompress");
   115 		if ( lib.jpeg_start_decompress == NULL ) {
   116 			SDL_UnloadObject(lib.handle);
   117 			return -1;
   118 		}
   119 		lib.jpeg_std_error = 
   120 			(struct jpeg_error_mgr * (*) (struct jpeg_error_mgr *))
   121 			SDL_LoadFunction(lib.handle, "jpeg_std_error");
   122 		if ( lib.jpeg_std_error == NULL ) {
   123 			SDL_UnloadObject(lib.handle);
   124 			return -1;
   125 		}
   126 	}
   127 	++lib.loaded;
   128 
   129 	return 0;
   130 }
   131 void IMG_QuitJPG()
   132 {
   133 	if ( lib.loaded == 0 ) {
   134 		return;
   135 	}
   136 	if ( lib.loaded == 1 ) {
   137 		SDL_UnloadObject(lib.handle);
   138 	}
   139 	--lib.loaded;
   140 }
   141 #else
   142 int IMG_InitJPG()
   143 {
   144 	if ( lib.loaded == 0 ) {
   145 		lib.jpeg_calc_output_dimensions = jpeg_calc_output_dimensions;
   146 		lib.jpeg_CreateDecompress = jpeg_CreateDecompress;
   147 		lib.jpeg_destroy_decompress = jpeg_destroy_decompress;
   148 		lib.jpeg_finish_decompress = jpeg_finish_decompress;
   149 		lib.jpeg_read_header = jpeg_read_header;
   150 		lib.jpeg_read_scanlines = jpeg_read_scanlines;
   151 		lib.jpeg_resync_to_restart = jpeg_resync_to_restart;
   152 		lib.jpeg_start_decompress = jpeg_start_decompress;
   153 		lib.jpeg_std_error = jpeg_std_error;
   154 	}
   155 	++lib.loaded;
   156 }
   157 void IMG_QuitJPG()
   158 {
   159 	if ( lib.loaded == 0 ) {
   160 		return;
   161 	}
   162 	if ( lib.loaded == 1 ) {
   163 	}
   164 	--lib.loaded;
   165 }
   166 #endif /* LOAD_JPG_DYNAMIC */
   167 
   168 /* See if an image is contained in a data source */
   169 int IMG_isJPG(SDL_RWops *src)
   170 {
   171 	int start;
   172 	int is_JPG;
   173 	int in_scan;
   174 	Uint8 magic[4];
   175 
   176 	/* This detection code is by Steaphan Greene <stea@cs.binghamton.edu> */
   177 	/* Blame me, not Sam, if this doesn't work right. */
   178 	/* And don't forget to report the problem to the the sdl list too! */
   179 
   180 	start = SDL_RWtell(src);
   181 	is_JPG = 0;
   182 	in_scan = 0;
   183 	if ( SDL_RWread(src, magic, 2, 1) ) {
   184 		if ( (magic[0] == 0xFF) && (magic[1] == 0xD8) ) {
   185 			is_JPG = 1;
   186 			while (is_JPG == 1) {
   187 				if(SDL_RWread(src, magic, 1, 2) != 2) {
   188 					is_JPG = 0;
   189 				} else if( (magic[0] != 0xFF) && (in_scan == 0) ) {
   190 					is_JPG = 0;
   191 				} else if( (magic[0] != 0xFF) || (magic[1] == 0xFF) ) {
   192 					/* Extra padding in JPEG (legal) */
   193 					/* or this is data and we are scanning */
   194 					SDL_RWseek(src, -1, SEEK_CUR);
   195 				} else if(magic[1] == 0xD9) {
   196 					/* Got to end of good JPEG */
   197 					break;
   198 				} else if( (in_scan == 1) && (magic[1] == 0x00) ) {
   199 					/* This is an encoded 0xFF within the data */
   200 				} else if( (magic[1] >= 0xD0) && (magic[1] < 0xD9) ) {
   201 					/* These have nothing else */
   202 				} else if(SDL_RWread(src, magic+2, 1, 2) != 2) {
   203 					is_JPG = 0;
   204 				} else {
   205 					/* Yes, it's big-endian */
   206 					Uint32 start;
   207 					Uint32 size;
   208 					Uint32 end;
   209 					start = SDL_RWtell(src);
   210 					size = (magic[2] << 8) + magic[3];
   211 					end = SDL_RWseek(src, size-2, SEEK_CUR);
   212 					if ( end != start + size - 2 ) is_JPG = 0;
   213 					if ( magic[1] == 0xDA ) {
   214 						/* Now comes the actual JPEG meat */
   215 #ifdef	FAST_IS_JPEG
   216 						/* Ok, I'm convinced.  It is a JPEG. */
   217 						break;
   218 #else
   219 						/* I'm not convinced.  Prove it! */
   220 						in_scan = 1;
   221 #endif
   222 					}
   223 				}
   224 			}
   225 		}
   226 	}
   227 	SDL_RWseek(src, start, SEEK_SET);
   228 	return(is_JPG);
   229 }
   230 
   231 #define INPUT_BUFFER_SIZE	4096
   232 typedef struct {
   233 	struct jpeg_source_mgr pub;
   234 
   235 	SDL_RWops *ctx;
   236 	Uint8 buffer[INPUT_BUFFER_SIZE];
   237 } my_source_mgr;
   238 
   239 /*
   240  * Initialize source --- called by jpeg_read_header
   241  * before any data is actually read.
   242  */
   243 static void init_source (j_decompress_ptr cinfo)
   244 {
   245 	/* We don't actually need to do anything */
   246 	return;
   247 }
   248 
   249 /*
   250  * Fill the input buffer --- called whenever buffer is emptied.
   251  */
   252 static int fill_input_buffer (j_decompress_ptr cinfo)
   253 {
   254 	my_source_mgr * src = (my_source_mgr *) cinfo->src;
   255 	int nbytes;
   256 
   257 	nbytes = SDL_RWread(src->ctx, src->buffer, 1, INPUT_BUFFER_SIZE);
   258 	if (nbytes <= 0) {
   259 		/* Insert a fake EOI marker */
   260 		src->buffer[0] = (Uint8) 0xFF;
   261 		src->buffer[1] = (Uint8) JPEG_EOI;
   262 		nbytes = 2;
   263 	}
   264 	src->pub.next_input_byte = src->buffer;
   265 	src->pub.bytes_in_buffer = nbytes;
   266 
   267 	return TRUE;
   268 }
   269 
   270 
   271 /*
   272  * Skip data --- used to skip over a potentially large amount of
   273  * uninteresting data (such as an APPn marker).
   274  *
   275  * Writers of suspendable-input applications must note that skip_input_data
   276  * is not granted the right to give a suspension return.  If the skip extends
   277  * beyond the data currently in the buffer, the buffer can be marked empty so
   278  * that the next read will cause a fill_input_buffer call that can suspend.
   279  * Arranging for additional bytes to be discarded before reloading the input
   280  * buffer is the application writer's problem.
   281  */
   282 static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
   283 {
   284 	my_source_mgr * src = (my_source_mgr *) cinfo->src;
   285 
   286 	/* Just a dumb implementation for now.	Could use fseek() except
   287 	 * it doesn't work on pipes.  Not clear that being smart is worth
   288 	 * any trouble anyway --- large skips are infrequent.
   289 	 */
   290 	if (num_bytes > 0) {
   291 		while (num_bytes > (long) src->pub.bytes_in_buffer) {
   292 			num_bytes -= (long) src->pub.bytes_in_buffer;
   293 			(void) src->pub.fill_input_buffer(cinfo);
   294 			/* note we assume that fill_input_buffer will never
   295 			 * return FALSE, so suspension need not be handled.
   296 			 */
   297 		}
   298 		src->pub.next_input_byte += (size_t) num_bytes;
   299 		src->pub.bytes_in_buffer -= (size_t) num_bytes;
   300 	}
   301 }
   302 
   303 /*
   304  * Terminate source --- called by jpeg_finish_decompress
   305  * after all data has been read.
   306  */
   307 static void term_source (j_decompress_ptr cinfo)
   308 {
   309 	/* We don't actually need to do anything */
   310 	return;
   311 }
   312 
   313 /*
   314  * Prepare for input from a stdio stream.
   315  * The caller must have already opened the stream, and is responsible
   316  * for closing it after finishing decompression.
   317  */
   318 static void jpeg_SDL_RW_src (j_decompress_ptr cinfo, SDL_RWops *ctx)
   319 {
   320   my_source_mgr *src;
   321 
   322   /* The source object and input buffer are made permanent so that a series
   323    * of JPEG images can be read from the same file by calling jpeg_stdio_src
   324    * only before the first one.  (If we discarded the buffer at the end of
   325    * one image, we'd likely lose the start of the next one.)
   326    * This makes it unsafe to use this manager and a different source
   327    * manager serially with the same JPEG object.  Caveat programmer.
   328    */
   329   if (cinfo->src == NULL) {	/* first time for this JPEG object? */
   330     cinfo->src = (struct jpeg_source_mgr *)
   331       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
   332 				  sizeof(my_source_mgr));
   333     src = (my_source_mgr *) cinfo->src;
   334   }
   335 
   336   src = (my_source_mgr *) cinfo->src;
   337   src->pub.init_source = init_source;
   338   src->pub.fill_input_buffer = fill_input_buffer;
   339   src->pub.skip_input_data = skip_input_data;
   340   src->pub.resync_to_restart = lib.jpeg_resync_to_restart; /* use default method */
   341   src->pub.term_source = term_source;
   342   src->ctx = ctx;
   343   src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
   344   src->pub.next_input_byte = NULL; /* until buffer loaded */
   345 }
   346 
   347 struct my_error_mgr {
   348 	struct jpeg_error_mgr errmgr;
   349 	jmp_buf escape;
   350 };
   351 
   352 static void my_error_exit(j_common_ptr cinfo)
   353 {
   354 	struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
   355 	longjmp(err->escape, 1);
   356 }
   357 
   358 static void output_no_message(j_common_ptr cinfo)
   359 {
   360 	/* do nothing */
   361 }
   362 
   363 /* Load a JPEG type image from an SDL datasource */
   364 SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src)
   365 {
   366 	int start;
   367 	struct jpeg_decompress_struct cinfo;
   368 	JSAMPROW rowptr[1];
   369 	SDL_Surface *volatile surface = NULL;
   370 	struct my_error_mgr jerr;
   371 
   372 	if ( !src ) {
   373 		/* The error message has been set in SDL_RWFromFile */
   374 		return NULL;
   375 	}
   376 	start = SDL_RWtell(src);
   377 
   378 	if ( IMG_InitJPG() < 0 ) {
   379 		return NULL;
   380 	}
   381 
   382 	/* Create a decompression structure and load the JPEG header */
   383 	cinfo.err = lib.jpeg_std_error(&jerr.errmgr);
   384 	jerr.errmgr.error_exit = my_error_exit;
   385 	jerr.errmgr.output_message = output_no_message;
   386 	if(setjmp(jerr.escape)) {
   387 		/* If we get here, libjpeg found an error */
   388 		lib.jpeg_destroy_decompress(&cinfo);
   389 		if ( surface != NULL ) {
   390 			SDL_FreeSurface(surface);
   391 		}
   392 		SDL_RWseek(src, start, SEEK_SET);
   393 		IMG_QuitJPG();
   394 		IMG_SetError("JPEG loading error");
   395 		return NULL;
   396 	}
   397 
   398 	lib.jpeg_create_decompress(&cinfo);
   399 	jpeg_SDL_RW_src(&cinfo, src);
   400 	lib.jpeg_read_header(&cinfo, TRUE);
   401 
   402 	if(cinfo.num_components == 4) {
   403 		/* Set 32-bit Raw output */
   404 		cinfo.out_color_space = JCS_CMYK;
   405 		cinfo.quantize_colors = FALSE;
   406 		lib.jpeg_calc_output_dimensions(&cinfo);
   407 
   408 		/* Allocate an output surface to hold the image */
   409 		surface = SDL_AllocSurface(SDL_SWSURFACE,
   410 		        cinfo.output_width, cinfo.output_height, 32,
   411 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
   412 		                   0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
   413 #else
   414 		                   0x0000FF00, 0x00FF0000, 0xFF000000, 0x000000FF);
   415 #endif
   416 	} else {
   417 		/* Set 24-bit RGB output */
   418 		cinfo.out_color_space = JCS_RGB;
   419 		cinfo.quantize_colors = FALSE;
   420 #ifdef FAST_JPEG
   421 		cinfo.scale_num   = 1;
   422 		cinfo.scale_denom = 1;
   423 		cinfo.dct_method = JDCT_FASTEST;
   424 		cinfo.do_fancy_upsampling = FALSE;
   425 #endif
   426 		lib.jpeg_calc_output_dimensions(&cinfo);
   427 
   428 		/* Allocate an output surface to hold the image */
   429 		surface = SDL_AllocSurface(SDL_SWSURFACE,
   430 		        cinfo.output_width, cinfo.output_height, 24,
   431 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
   432 		                   0x0000FF, 0x00FF00, 0xFF0000,
   433 #else
   434 		                   0xFF0000, 0x00FF00, 0x0000FF,
   435 #endif
   436 		                   0);
   437 	}
   438 
   439 	if ( surface == NULL ) {
   440 		lib.jpeg_destroy_decompress(&cinfo);
   441 		SDL_RWseek(src, start, SEEK_SET);
   442 		IMG_QuitJPG();
   443 		IMG_SetError("Out of memory");
   444 		return NULL;
   445 	}
   446 
   447 	/* Decompress the image */
   448 	lib.jpeg_start_decompress(&cinfo);
   449 	while ( cinfo.output_scanline < cinfo.output_height ) {
   450 		rowptr[0] = (JSAMPROW)(Uint8 *)surface->pixels +
   451 		                    cinfo.output_scanline * surface->pitch;
   452 		lib.jpeg_read_scanlines(&cinfo, rowptr, (JDIMENSION) 1);
   453 	}
   454 	lib.jpeg_finish_decompress(&cinfo);
   455 	lib.jpeg_destroy_decompress(&cinfo);
   456 
   457 	IMG_QuitJPG();
   458 
   459 	return(surface);
   460 }
   461 
   462 #else
   463 
   464 /* See if an image is contained in a data source */
   465 int IMG_isJPG(SDL_RWops *src)
   466 {
   467 	return(0);
   468 }
   469 
   470 /* Load a JPEG type image from an SDL datasource */
   471 SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src)
   472 {
   473 	return(NULL);
   474 }
   475 
   476 #endif /* LOAD_JPG */