IMG_jpg.c
author Sam Lantinga <slouken@libsdl.org>
Sat, 26 Sep 2009 09:09:53 +0000
changeset 205 0aa18e250940
parent 204 dcb38b0e78a6
child 230 3766fc378624
permissions -rw-r--r--
Mason Wheeler - 2009-06-10 06:29:45 PDT
* Added IMG_Init()/IMG_Quit() to prevent constantly loading and unloading DLLs
     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 /* 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 	return 0;
   158 }
   159 void IMG_QuitJPG()
   160 {
   161 	if ( lib.loaded == 0 ) {
   162 		return;
   163 	}
   164 	if ( lib.loaded == 1 ) {
   165 	}
   166 	--lib.loaded;
   167 }
   168 #endif /* LOAD_JPG_DYNAMIC */
   169 
   170 /* See if an image is contained in a data source */
   171 int IMG_isJPG(SDL_RWops *src)
   172 {
   173 	int start;
   174 	int is_JPG;
   175 	int in_scan;
   176 	Uint8 magic[4];
   177 
   178 	/* This detection code is by Steaphan Greene <stea@cs.binghamton.edu> */
   179 	/* Blame me, not Sam, if this doesn't work right. */
   180 	/* And don't forget to report the problem to the the sdl list too! */
   181 
   182 	if ( !src )
   183 		return 0;
   184 	start = SDL_RWtell(src);
   185 	is_JPG = 0;
   186 	in_scan = 0;
   187 	if ( SDL_RWread(src, magic, 2, 1) ) {
   188 		if ( (magic[0] == 0xFF) && (magic[1] == 0xD8) ) {
   189 			is_JPG = 1;
   190 			while (is_JPG == 1) {
   191 				if(SDL_RWread(src, magic, 1, 2) != 2) {
   192 					is_JPG = 0;
   193 				} else if( (magic[0] != 0xFF) && (in_scan == 0) ) {
   194 					is_JPG = 0;
   195 				} else if( (magic[0] != 0xFF) || (magic[1] == 0xFF) ) {
   196 					/* Extra padding in JPEG (legal) */
   197 					/* or this is data and we are scanning */
   198 					SDL_RWseek(src, -1, SEEK_CUR);
   199 				} else if(magic[1] == 0xD9) {
   200 					/* Got to end of good JPEG */
   201 					break;
   202 				} else if( (in_scan == 1) && (magic[1] == 0x00) ) {
   203 					/* This is an encoded 0xFF within the data */
   204 				} else if( (magic[1] >= 0xD0) && (magic[1] < 0xD9) ) {
   205 					/* These have nothing else */
   206 				} else if(SDL_RWread(src, magic+2, 1, 2) != 2) {
   207 					is_JPG = 0;
   208 				} else {
   209 					/* Yes, it's big-endian */
   210 					Uint32 start;
   211 					Uint32 size;
   212 					Uint32 end;
   213 					start = SDL_RWtell(src);
   214 					size = (magic[2] << 8) + magic[3];
   215 					end = SDL_RWseek(src, size-2, SEEK_CUR);
   216 					if ( end != start + size - 2 ) is_JPG = 0;
   217 					if ( magic[1] == 0xDA ) {
   218 						/* Now comes the actual JPEG meat */
   219 #ifdef	FAST_IS_JPEG
   220 						/* Ok, I'm convinced.  It is a JPEG. */
   221 						break;
   222 #else
   223 						/* I'm not convinced.  Prove it! */
   224 						in_scan = 1;
   225 #endif
   226 					}
   227 				}
   228 			}
   229 		}
   230 	}
   231 	SDL_RWseek(src, start, SEEK_SET);
   232 	return(is_JPG);
   233 }
   234 
   235 #define INPUT_BUFFER_SIZE	4096
   236 typedef struct {
   237 	struct jpeg_source_mgr pub;
   238 
   239 	SDL_RWops *ctx;
   240 	Uint8 buffer[INPUT_BUFFER_SIZE];
   241 } my_source_mgr;
   242 
   243 /*
   244  * Initialize source --- called by jpeg_read_header
   245  * before any data is actually read.
   246  */
   247 static void init_source (j_decompress_ptr cinfo)
   248 {
   249 	/* We don't actually need to do anything */
   250 	return;
   251 }
   252 
   253 /*
   254  * Fill the input buffer --- called whenever buffer is emptied.
   255  */
   256 static int fill_input_buffer (j_decompress_ptr cinfo)
   257 {
   258 	my_source_mgr * src = (my_source_mgr *) cinfo->src;
   259 	int nbytes;
   260 
   261 	nbytes = SDL_RWread(src->ctx, src->buffer, 1, INPUT_BUFFER_SIZE);
   262 	if (nbytes <= 0) {
   263 		/* Insert a fake EOI marker */
   264 		src->buffer[0] = (Uint8) 0xFF;
   265 		src->buffer[1] = (Uint8) JPEG_EOI;
   266 		nbytes = 2;
   267 	}
   268 	src->pub.next_input_byte = src->buffer;
   269 	src->pub.bytes_in_buffer = nbytes;
   270 
   271 	return TRUE;
   272 }
   273 
   274 
   275 /*
   276  * Skip data --- used to skip over a potentially large amount of
   277  * uninteresting data (such as an APPn marker).
   278  *
   279  * Writers of suspendable-input applications must note that skip_input_data
   280  * is not granted the right to give a suspension return.  If the skip extends
   281  * beyond the data currently in the buffer, the buffer can be marked empty so
   282  * that the next read will cause a fill_input_buffer call that can suspend.
   283  * Arranging for additional bytes to be discarded before reloading the input
   284  * buffer is the application writer's problem.
   285  */
   286 static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
   287 {
   288 	my_source_mgr * src = (my_source_mgr *) cinfo->src;
   289 
   290 	/* Just a dumb implementation for now.	Could use fseek() except
   291 	 * it doesn't work on pipes.  Not clear that being smart is worth
   292 	 * any trouble anyway --- large skips are infrequent.
   293 	 */
   294 	if (num_bytes > 0) {
   295 		while (num_bytes > (long) src->pub.bytes_in_buffer) {
   296 			num_bytes -= (long) src->pub.bytes_in_buffer;
   297 			(void) src->pub.fill_input_buffer(cinfo);
   298 			/* note we assume that fill_input_buffer will never
   299 			 * return FALSE, so suspension need not be handled.
   300 			 */
   301 		}
   302 		src->pub.next_input_byte += (size_t) num_bytes;
   303 		src->pub.bytes_in_buffer -= (size_t) num_bytes;
   304 	}
   305 }
   306 
   307 /*
   308  * Terminate source --- called by jpeg_finish_decompress
   309  * after all data has been read.
   310  */
   311 static void term_source (j_decompress_ptr cinfo)
   312 {
   313 	/* We don't actually need to do anything */
   314 	return;
   315 }
   316 
   317 /*
   318  * Prepare for input from a stdio stream.
   319  * The caller must have already opened the stream, and is responsible
   320  * for closing it after finishing decompression.
   321  */
   322 static void jpeg_SDL_RW_src (j_decompress_ptr cinfo, SDL_RWops *ctx)
   323 {
   324   my_source_mgr *src;
   325 
   326   /* The source object and input buffer are made permanent so that a series
   327    * of JPEG images can be read from the same file by calling jpeg_stdio_src
   328    * only before the first one.  (If we discarded the buffer at the end of
   329    * one image, we'd likely lose the start of the next one.)
   330    * This makes it unsafe to use this manager and a different source
   331    * manager serially with the same JPEG object.  Caveat programmer.
   332    */
   333   if (cinfo->src == NULL) {	/* first time for this JPEG object? */
   334     cinfo->src = (struct jpeg_source_mgr *)
   335       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
   336 				  sizeof(my_source_mgr));
   337     src = (my_source_mgr *) cinfo->src;
   338   }
   339 
   340   src = (my_source_mgr *) cinfo->src;
   341   src->pub.init_source = init_source;
   342   src->pub.fill_input_buffer = fill_input_buffer;
   343   src->pub.skip_input_data = skip_input_data;
   344   src->pub.resync_to_restart = lib.jpeg_resync_to_restart; /* use default method */
   345   src->pub.term_source = term_source;
   346   src->ctx = ctx;
   347   src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
   348   src->pub.next_input_byte = NULL; /* until buffer loaded */
   349 }
   350 
   351 struct my_error_mgr {
   352 	struct jpeg_error_mgr errmgr;
   353 	jmp_buf escape;
   354 };
   355 
   356 static void my_error_exit(j_common_ptr cinfo)
   357 {
   358 	struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
   359 	longjmp(err->escape, 1);
   360 }
   361 
   362 static void output_no_message(j_common_ptr cinfo)
   363 {
   364 	/* do nothing */
   365 }
   366 
   367 /* Load a JPEG type image from an SDL datasource */
   368 SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src)
   369 {
   370 	int start;
   371 	struct jpeg_decompress_struct cinfo;
   372 	JSAMPROW rowptr[1];
   373 	SDL_Surface *volatile surface = NULL;
   374 	struct my_error_mgr jerr;
   375 
   376 	if ( !src ) {
   377 		/* The error message has been set in SDL_RWFromFile */
   378 		return NULL;
   379 	}
   380 	start = SDL_RWtell(src);
   381 
   382 	if ( IMG_InitJPG() < 0 ) {
   383 		return NULL;
   384 	}
   385 
   386 	/* Create a decompression structure and load the JPEG header */
   387 	cinfo.err = lib.jpeg_std_error(&jerr.errmgr);
   388 	jerr.errmgr.error_exit = my_error_exit;
   389 	jerr.errmgr.output_message = output_no_message;
   390 	if(setjmp(jerr.escape)) {
   391 		/* If we get here, libjpeg found an error */
   392 		lib.jpeg_destroy_decompress(&cinfo);
   393 		if ( surface != NULL ) {
   394 			SDL_FreeSurface(surface);
   395 		}
   396 		SDL_RWseek(src, start, SEEK_SET);
   397 		IMG_QuitJPG();
   398 		IMG_SetError("JPEG loading error");
   399 		return NULL;
   400 	}
   401 
   402 	lib.jpeg_create_decompress(&cinfo);
   403 	jpeg_SDL_RW_src(&cinfo, src);
   404 	lib.jpeg_read_header(&cinfo, TRUE);
   405 
   406 	if(cinfo.num_components == 4) {
   407 		/* Set 32-bit Raw output */
   408 		cinfo.out_color_space = JCS_CMYK;
   409 		cinfo.quantize_colors = FALSE;
   410 		lib.jpeg_calc_output_dimensions(&cinfo);
   411 
   412 		/* Allocate an output surface to hold the image */
   413 		surface = SDL_AllocSurface(SDL_SWSURFACE,
   414 		        cinfo.output_width, cinfo.output_height, 32,
   415 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
   416 		                   0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
   417 #else
   418 		                   0x0000FF00, 0x00FF0000, 0xFF000000, 0x000000FF);
   419 #endif
   420 	} else {
   421 		/* Set 24-bit RGB output */
   422 		cinfo.out_color_space = JCS_RGB;
   423 		cinfo.quantize_colors = FALSE;
   424 #ifdef FAST_JPEG
   425 		cinfo.scale_num   = 1;
   426 		cinfo.scale_denom = 1;
   427 		cinfo.dct_method = JDCT_FASTEST;
   428 		cinfo.do_fancy_upsampling = FALSE;
   429 #endif
   430 		lib.jpeg_calc_output_dimensions(&cinfo);
   431 
   432 		/* Allocate an output surface to hold the image */
   433 		surface = SDL_AllocSurface(SDL_SWSURFACE,
   434 		        cinfo.output_width, cinfo.output_height, 24,
   435 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
   436 		                   0x0000FF, 0x00FF00, 0xFF0000,
   437 #else
   438 		                   0xFF0000, 0x00FF00, 0x0000FF,
   439 #endif
   440 		                   0);
   441 	}
   442 
   443 	if ( surface == NULL ) {
   444 		lib.jpeg_destroy_decompress(&cinfo);
   445 		SDL_RWseek(src, start, SEEK_SET);
   446 		IMG_QuitJPG();
   447 		IMG_SetError("Out of memory");
   448 		return NULL;
   449 	}
   450 
   451 	/* Decompress the image */
   452 	lib.jpeg_start_decompress(&cinfo);
   453 	while ( cinfo.output_scanline < cinfo.output_height ) {
   454 		rowptr[0] = (JSAMPROW)(Uint8 *)surface->pixels +
   455 		                    cinfo.output_scanline * surface->pitch;
   456 		lib.jpeg_read_scanlines(&cinfo, rowptr, (JDIMENSION) 1);
   457 	}
   458 	lib.jpeg_finish_decompress(&cinfo);
   459 	lib.jpeg_destroy_decompress(&cinfo);
   460 
   461 	IMG_QuitJPG();
   462 
   463 	return(surface);
   464 }
   465 
   466 #else
   467 
   468 int IMG_InitJPG()
   469 {
   470 	IMG_SetError("JPEG images are not supported");
   471 	return(-1);
   472 }
   473 
   474 void IMG_QuitJPG()
   475 {
   476 }
   477 
   478 /* See if an image is contained in a data source */
   479 int IMG_isJPG(SDL_RWops *src)
   480 {
   481 	return(0);
   482 }
   483 
   484 /* Load a JPEG type image from an SDL datasource */
   485 SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src)
   486 {
   487 	return(NULL);
   488 }
   489 
   490 #endif /* LOAD_JPG */