| 1 | /* |
| 2 | =========================================================================== |
| 3 | Copyright (C) 1999-2005 Id Software, Inc. |
| 4 | |
| 5 | This file is part of Quake III Arena source code. |
| 6 | |
| 7 | Quake III Arena source code is free software; you can redistribute it |
| 8 | and/or modify it under the terms of the GNU General Public License as |
| 9 | published by the Free Software Foundation; either version 2 of the License, |
| 10 | or (at your option) any later version. |
| 11 | |
| 12 | Quake III Arena source code is distributed in the hope that it will be |
| 13 | useful, but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 | GNU General Public License for more details. |
| 16 | |
| 17 | You should have received a copy of the GNU General Public License |
| 18 | along with Quake III Arena source code; if not, write to the Free Software |
| 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
| 20 | =========================================================================== |
| 21 | */ |
| 22 | |
| 23 | #include <setjmp.h> |
| 24 | |
| 25 | #include "tr_common.h" |
| 26 | |
| 27 | /* |
| 28 | * Include file for users of JPEG library. |
| 29 | * You will need to have included system headers that define at least |
| 30 | * the typedefs FILE and size_t before you can include jpeglib.h. |
| 31 | * (stdio.h is sufficient on ANSI-conforming systems.) |
| 32 | * You may also wish to include "jerror.h". |
| 33 | */ |
| 34 | |
| 35 | #ifdef USE_INTERNAL_JPEG |
| 36 | # define JPEG_INTERNALS |
| 37 | #endif |
| 38 | |
| 39 | #include <jpeglib.h> |
| 40 | |
| 41 | #ifndef USE_INTERNAL_JPEG |
| 42 | # if JPEG_LIB_VERSION < 80 && !defined(MEM_SRCDST_SUPPORTED) |
| 43 | # error Need system libjpeg >= 80 or jpeg_mem_ support |
| 44 | # endif |
| 45 | #endif |
| 46 | |
| 47 | /* Catching errors, as done in libjpeg's example.c */ |
| 48 | typedef struct q_jpeg_error_mgr_s |
| 49 | { |
| 50 | struct jpeg_error_mgr pub; /* "public" fields */ |
| 51 | |
| 52 | jmp_buf setjmp_buffer; /* for return to caller */ |
| 53 | } q_jpeg_error_mgr_t; |
| 54 | |
| 55 | static void R_JPGErrorExit(j_common_ptr cinfo) |
| 56 | { |
| 57 | char buffer[JMSG_LENGTH_MAX]; |
| 58 | |
| 59 | /* cinfo->err really points to a q_jpeg_error_mgr_s struct, so coerce pointer */ |
| 60 | q_jpeg_error_mgr_t *jerr = (q_jpeg_error_mgr_t *)cinfo->err; |
| 61 | |
| 62 | (*cinfo->err->format_message) (cinfo, buffer); |
| 63 | |
| 64 | ri.Printf(PRINT_ALL, "Error: %s", buffer); |
| 65 | |
| 66 | /* Return control to the setjmp point */ |
| 67 | longjmp(jerr->setjmp_buffer, 1); |
| 68 | } |
| 69 | |
| 70 | static void R_JPGOutputMessage(j_common_ptr cinfo) |
| 71 | { |
| 72 | char buffer[JMSG_LENGTH_MAX]; |
| 73 | |
| 74 | /* Create the message */ |
| 75 | (*cinfo->err->format_message) (cinfo, buffer); |
| 76 | |
| 77 | /* Send it to stderr, adding a newline */ |
| 78 | ri.Printf(PRINT_ALL, "%s\n", buffer); |
| 79 | } |
| 80 | |
| 81 | void R_LoadJPG(const char *filename, unsigned char **pic, int *width, int *height) |
| 82 | { |
| 83 | /* This struct contains the JPEG decompression parameters and pointers to |
| 84 | * working space (which is allocated as needed by the JPEG library). |
| 85 | */ |
| 86 | struct jpeg_decompress_struct cinfo = {NULL}; |
| 87 | /* We use our private extension JPEG error handler. |
| 88 | * Note that this struct must live as long as the main JPEG parameter |
| 89 | * struct, to avoid dangling-pointer problems. |
| 90 | */ |
| 91 | /* This struct represents a JPEG error handler. It is declared separately |
| 92 | * because applications often want to supply a specialized error handler |
| 93 | * (see the second half of this file for an example). But here we just |
| 94 | * take the easy way out and use the standard error handler, which will |
| 95 | * print a message on stderr and call exit() if compression fails. |
| 96 | * Note that this struct must live as long as the main JPEG parameter |
| 97 | * struct, to avoid dangling-pointer problems. |
| 98 | */ |
| 99 | q_jpeg_error_mgr_t jerr; |
| 100 | /* More stuff */ |
| 101 | JSAMPARRAY buffer; /* Output row buffer */ |
| 102 | unsigned int row_stride; /* physical row width in output buffer */ |
| 103 | unsigned int pixelcount, memcount; |
| 104 | unsigned int sindex, dindex; |
| 105 | byte *out; |
| 106 | int len; |
| 107 | union { |
| 108 | byte *b; |
| 109 | void *v; |
| 110 | } fbuffer; |
| 111 | byte *buf; |
| 112 | |
| 113 | /* In this example we want to open the input file before doing anything else, |
| 114 | * so that the setjmp() error recovery below can assume the file is open. |
| 115 | * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that |
| 116 | * requires it in order to read binary files. |
| 117 | */ |
| 118 | |
| 119 | len = ri.FS_ReadFile ( ( char * ) filename, &fbuffer.v); |
| 120 | if (!fbuffer.b || len < 0) { |
| 121 | return; |
| 122 | } |
| 123 | |
| 124 | /* Step 1: allocate and initialize JPEG decompression object */ |
| 125 | |
| 126 | /* We have to set up the error handler first, in case the initialization |
| 127 | * step fails. (Unlikely, but it could happen if you are out of memory.) |
| 128 | * This routine fills in the contents of struct jerr, and returns jerr's |
| 129 | * address which we place into the link field in cinfo. |
| 130 | */ |
| 131 | cinfo.err = jpeg_std_error(&jerr.pub); |
| 132 | cinfo.err->error_exit = R_JPGErrorExit; |
| 133 | cinfo.err->output_message = R_JPGOutputMessage; |
| 134 | |
| 135 | /* Establish the setjmp return context for R_JPGErrorExit to use. */ |
| 136 | if (setjmp(jerr.setjmp_buffer)) |
| 137 | { |
| 138 | /* If we get here, the JPEG code has signaled an error. |
| 139 | * We need to clean up the JPEG object, close the input file, and return. |
| 140 | */ |
| 141 | jpeg_destroy_decompress(&cinfo); |
| 142 | ri.FS_FreeFile(fbuffer.v); |
| 143 | |
| 144 | /* Append the filename to the error for easier debugging */ |
| 145 | ri.Printf(PRINT_ALL, ", loading file %s\n", filename); |
| 146 | return; |
| 147 | } |
| 148 | |
| 149 | /* Now we can initialize the JPEG decompression object. */ |
| 150 | jpeg_create_decompress(&cinfo); |
| 151 | |
| 152 | /* Step 2: specify data source (eg, a file) */ |
| 153 | |
| 154 | jpeg_mem_src(&cinfo, fbuffer.b, len); |
| 155 | |
| 156 | /* Step 3: read file parameters with jpeg_read_header() */ |
| 157 | |
| 158 | (void) jpeg_read_header(&cinfo, TRUE); |
| 159 | /* We can ignore the return value from jpeg_read_header since |
| 160 | * (a) suspension is not possible with the stdio data source, and |
| 161 | * (b) we passed TRUE to reject a tables-only JPEG file as an error. |
| 162 | * See libjpeg.doc for more info. |
| 163 | */ |
| 164 | |
| 165 | /* Step 4: set parameters for decompression */ |
| 166 | |
| 167 | /* |
| 168 | * Make sure it always converts images to RGB color space. This will |
| 169 | * automatically convert 8-bit greyscale images to RGB as well. |
| 170 | */ |
| 171 | cinfo.out_color_space = JCS_RGB; |
| 172 | |
| 173 | /* Step 5: Start decompressor */ |
| 174 | |
| 175 | (void) jpeg_start_decompress(&cinfo); |
| 176 | /* We can ignore the return value since suspension is not possible |
| 177 | * with the stdio data source. |
| 178 | */ |
| 179 | |
| 180 | /* We may need to do some setup of our own at this point before reading |
| 181 | * the data. After jpeg_start_decompress() we have the correct scaled |
| 182 | * output image dimensions available, as well as the output colormap |
| 183 | * if we asked for color quantization. |
| 184 | * In this example, we need to make an output work buffer of the right size. |
| 185 | */ |
| 186 | /* JSAMPLEs per row in output buffer */ |
| 187 | |
| 188 | pixelcount = cinfo.output_width * cinfo.output_height; |
| 189 | |
| 190 | if(!cinfo.output_width || !cinfo.output_height |
| 191 | || ((pixelcount * 4) / cinfo.output_width) / 4 != cinfo.output_height |
| 192 | || pixelcount > 0x1FFFFFFF || cinfo.output_components != 3 |
| 193 | ) |
| 194 | { |
| 195 | // Free the memory to make sure we don't leak memory |
| 196 | ri.FS_FreeFile (fbuffer.v); |
| 197 | jpeg_destroy_decompress(&cinfo); |
| 198 | |
| 199 | ri.Error(ERR_DROP, "LoadJPG: %s has an invalid image format: %dx%d*4=%d, components: %d", filename, |
| 200 | cinfo.output_width, cinfo.output_height, pixelcount * 4, cinfo.output_components); |
| 201 | } |
| 202 | |
| 203 | memcount = pixelcount * 4; |
| 204 | row_stride = cinfo.output_width * cinfo.output_components; |
| 205 | |
| 206 | out = ri.Malloc(memcount); |
| 207 | |
| 208 | *width = cinfo.output_width; |
| 209 | *height = cinfo.output_height; |
| 210 | |
| 211 | /* Step 6: while (scan lines remain to be read) */ |
| 212 | /* jpeg_read_scanlines(...); */ |
| 213 | |
| 214 | /* Here we use the library's state variable cinfo.output_scanline as the |
| 215 | * loop counter, so that we don't have to keep track ourselves. |
| 216 | */ |
| 217 | while (cinfo.output_scanline < cinfo.output_height) { |
| 218 | /* jpeg_read_scanlines expects an array of pointers to scanlines. |
| 219 | * Here the array is only one element long, but you could ask for |
| 220 | * more than one scanline at a time if that's more convenient. |
| 221 | */ |
| 222 | buf = ((out+(row_stride*cinfo.output_scanline))); |
| 223 | buffer = &buf; |
| 224 | (void) jpeg_read_scanlines(&cinfo, buffer, 1); |
| 225 | } |
| 226 | |
| 227 | buf = out; |
| 228 | |
| 229 | // Expand from RGB to RGBA |
| 230 | sindex = pixelcount * cinfo.output_components; |
| 231 | dindex = memcount; |
| 232 | |
| 233 | do |
| 234 | { |
| 235 | buf[--dindex] = 255; |
| 236 | buf[--dindex] = buf[--sindex]; |
| 237 | buf[--dindex] = buf[--sindex]; |
| 238 | buf[--dindex] = buf[--sindex]; |
| 239 | } while(sindex); |
| 240 | |
| 241 | *pic = out; |
| 242 | |
| 243 | /* Step 7: Finish decompression */ |
| 244 | |
| 245 | jpeg_finish_decompress(&cinfo); |
| 246 | /* We can ignore the return value since suspension is not possible |
| 247 | * with the stdio data source. |
| 248 | */ |
| 249 | |
| 250 | /* Step 8: Release JPEG decompression object */ |
| 251 | |
| 252 | /* This is an important step since it will release a good deal of memory. */ |
| 253 | jpeg_destroy_decompress(&cinfo); |
| 254 | |
| 255 | /* After finish_decompress, we can close the input file. |
| 256 | * Here we postpone it until after no more JPEG errors are possible, |
| 257 | * so as to simplify the setjmp error logic above. (Actually, I don't |
| 258 | * think that jpeg_destroy can do an error exit, but why assume anything...) |
| 259 | */ |
| 260 | ri.FS_FreeFile (fbuffer.v); |
| 261 | |
| 262 | /* At this point you may want to check to see whether any corrupt-data |
| 263 | * warnings occurred (test whether jerr.pub.num_warnings is nonzero). |
| 264 | */ |
| 265 | |
| 266 | /* And we're done! */ |
| 267 | } |
| 268 | |
| 269 | |
| 270 | /* Expanded data destination object for stdio output */ |
| 271 | |
| 272 | typedef struct { |
| 273 | struct jpeg_destination_mgr pub; /* public fields */ |
| 274 | |
| 275 | byte* outfile; /* target stream */ |
| 276 | int size; |
| 277 | } my_destination_mgr; |
| 278 | |
| 279 | typedef my_destination_mgr * my_dest_ptr; |
| 280 | |
| 281 | |
| 282 | /* |
| 283 | * Initialize destination --- called by jpeg_start_compress |
| 284 | * before any data is actually written. |
| 285 | */ |
| 286 | |
| 287 | static void |
| 288 | init_destination (j_compress_ptr cinfo) |
| 289 | { |
| 290 | my_dest_ptr dest = (my_dest_ptr) cinfo->dest; |
| 291 | |
| 292 | dest->pub.next_output_byte = dest->outfile; |
| 293 | dest->pub.free_in_buffer = dest->size; |
| 294 | } |
| 295 | |
| 296 | |
| 297 | /* |
| 298 | * Empty the output buffer --- called whenever buffer fills up. |
| 299 | * |
| 300 | * In typical applications, this should write the entire output buffer |
| 301 | * (ignoring the current state of next_output_byte & free_in_buffer), |
| 302 | * reset the pointer & count to the start of the buffer, and return TRUE |
| 303 | * indicating that the buffer has been dumped. |
| 304 | * |
| 305 | * In applications that need to be able to suspend compression due to output |
| 306 | * overrun, a FALSE return indicates that the buffer cannot be emptied now. |
| 307 | * In this situation, the compressor will return to its caller (possibly with |
| 308 | * an indication that it has not accepted all the supplied scanlines). The |
| 309 | * application should resume compression after it has made more room in the |
| 310 | * output buffer. Note that there are substantial restrictions on the use of |
| 311 | * suspension --- see the documentation. |
| 312 | * |
| 313 | * When suspending, the compressor will back up to a convenient restart point |
| 314 | * (typically the start of the current MCU). next_output_byte & free_in_buffer |
| 315 | * indicate where the restart point will be if the current call returns FALSE. |
| 316 | * Data beyond this point will be regenerated after resumption, so do not |
| 317 | * write it out when emptying the buffer externally. |
| 318 | */ |
| 319 | |
| 320 | static boolean |
| 321 | empty_output_buffer (j_compress_ptr cinfo) |
| 322 | { |
| 323 | my_dest_ptr dest = (my_dest_ptr) cinfo->dest; |
| 324 | |
| 325 | jpeg_destroy_compress(cinfo); |
| 326 | |
| 327 | // Make crash fatal or we would probably leak memory. |
| 328 | ri.Error(ERR_FATAL, "Output buffer for encoded JPEG image has insufficient size of %d bytes", |
| 329 | dest->size); |
| 330 | |
| 331 | return FALSE; |
| 332 | } |
| 333 | |
| 334 | /* |
| 335 | * Terminate destination --- called by jpeg_finish_compress |
| 336 | * after all data has been written. Usually needs to flush buffer. |
| 337 | * |
| 338 | * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding |
| 339 | * application must deal with any cleanup that should happen even |
| 340 | * for error exit. |
| 341 | */ |
| 342 | |
| 343 | static void term_destination(j_compress_ptr cinfo) |
| 344 | { |
| 345 | } |
| 346 | |
| 347 | |
| 348 | /* |
| 349 | * Prepare for output to a stdio stream. |
| 350 | * The caller must have already opened the stream, and is responsible |
| 351 | * for closing it after finishing compression. |
| 352 | */ |
| 353 | |
| 354 | static void |
| 355 | jpegDest (j_compress_ptr cinfo, byte* outfile, int size) |
| 356 | { |
| 357 | my_dest_ptr dest; |
| 358 | |
| 359 | /* The destination object is made permanent so that multiple JPEG images |
| 360 | * can be written to the same file without re-executing jpeg_stdio_dest. |
| 361 | * This makes it dangerous to use this manager and a different destination |
| 362 | * manager serially with the same JPEG object, because their private object |
| 363 | * sizes may be different. Caveat programmer. |
| 364 | */ |
| 365 | if (cinfo->dest == NULL) { /* first time for this JPEG object? */ |
| 366 | cinfo->dest = (struct jpeg_destination_mgr *) |
| 367 | (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, |
| 368 | sizeof(my_destination_mgr)); |
| 369 | } |
| 370 | |
| 371 | dest = (my_dest_ptr) cinfo->dest; |
| 372 | dest->pub.init_destination = init_destination; |
| 373 | dest->pub.empty_output_buffer = empty_output_buffer; |
| 374 | dest->pub.term_destination = term_destination; |
| 375 | dest->outfile = outfile; |
| 376 | dest->size = size; |
| 377 | } |
| 378 | |
| 379 | /* |
| 380 | ================= |
| 381 | SaveJPGToBuffer |
| 382 | |
| 383 | Encodes JPEG from image in image_buffer and writes to buffer. |
| 384 | Expects RGB input data |
| 385 | ================= |
| 386 | */ |
| 387 | size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, |
| 388 | int image_width, int image_height, byte *image_buffer, int padding) |
| 389 | { |
| 390 | struct jpeg_compress_struct cinfo; |
| 391 | q_jpeg_error_mgr_t jerr; |
| 392 | JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ |
| 393 | my_dest_ptr dest; |
| 394 | int row_stride; /* physical row width in image buffer */ |
| 395 | size_t outcount; |
| 396 | |
| 397 | /* Step 1: allocate and initialize JPEG compression object */ |
| 398 | cinfo.err = jpeg_std_error(&jerr.pub); |
| 399 | cinfo.err->error_exit = R_JPGErrorExit; |
| 400 | cinfo.err->output_message = R_JPGOutputMessage; |
| 401 | |
| 402 | /* Establish the setjmp return context for R_JPGErrorExit to use. */ |
| 403 | if (setjmp(jerr.setjmp_buffer)) |
| 404 | { |
| 405 | /* If we get here, the JPEG code has signaled an error. |
| 406 | * We need to clean up the JPEG object and return. |
| 407 | */ |
| 408 | jpeg_destroy_compress(&cinfo); |
| 409 | |
| 410 | ri.Printf(PRINT_ALL, "\n"); |
| 411 | return 0; |
| 412 | } |
| 413 | |
| 414 | /* Now we can initialize the JPEG compression object. */ |
| 415 | jpeg_create_compress(&cinfo); |
| 416 | |
| 417 | /* Step 2: specify data destination (eg, a file) */ |
| 418 | /* Note: steps 2 and 3 can be done in either order. */ |
| 419 | jpegDest(&cinfo, buffer, bufSize); |
| 420 | |
| 421 | /* Step 3: set parameters for compression */ |
| 422 | cinfo.image_width = image_width; /* image width and height, in pixels */ |
| 423 | cinfo.image_height = image_height; |
| 424 | cinfo.input_components = 3; /* # of color components per pixel */ |
| 425 | cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ |
| 426 | |
| 427 | jpeg_set_defaults(&cinfo); |
| 428 | jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */); |
| 429 | /* If quality is set high, disable chroma subsampling */ |
| 430 | if (quality >= 85) { |
| 431 | cinfo.comp_info[0].h_samp_factor = 1; |
| 432 | cinfo.comp_info[0].v_samp_factor = 1; |
| 433 | } |
| 434 | |
| 435 | /* Step 4: Start compressor */ |
| 436 | jpeg_start_compress(&cinfo, TRUE); |
| 437 | |
| 438 | /* Step 5: while (scan lines remain to be written) */ |
| 439 | /* jpeg_write_scanlines(...); */ |
| 440 | row_stride = image_width * cinfo.input_components + padding; /* JSAMPLEs per row in image_buffer */ |
| 441 | |
| 442 | while (cinfo.next_scanline < cinfo.image_height) { |
| 443 | /* jpeg_write_scanlines expects an array of pointers to scanlines. |
| 444 | * Here the array is only one element long, but you could pass |
| 445 | * more than one scanline at a time if that's more convenient. |
| 446 | */ |
| 447 | row_pointer[0] = &image_buffer[((cinfo.image_height-1)*row_stride)-cinfo.next_scanline * row_stride]; |
| 448 | (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); |
| 449 | } |
| 450 | |
| 451 | /* Step 6: Finish compression */ |
| 452 | jpeg_finish_compress(&cinfo); |
| 453 | |
| 454 | dest = (my_dest_ptr) cinfo.dest; |
| 455 | outcount = dest->size - dest->pub.free_in_buffer; |
| 456 | |
| 457 | /* Step 7: release JPEG compression object */ |
| 458 | jpeg_destroy_compress(&cinfo); |
| 459 | |
| 460 | /* And we're done! */ |
| 461 | return outcount; |
| 462 | } |
| 463 | |
| 464 | void RE_SaveJPG(char * filename, int quality, int image_width, int image_height, byte *image_buffer, int padding) |
| 465 | { |
| 466 | byte *out; |
| 467 | size_t bufSize; |
| 468 | |
| 469 | bufSize = image_width * image_height * 3; |
| 470 | out = ri.Hunk_AllocateTempMemory(bufSize); |
| 471 | |
| 472 | bufSize = RE_SaveJPGToBuffer(out, bufSize, quality, image_width, image_height, image_buffer, padding); |
| 473 | ri.FS_WriteFile(filename, out, bufSize); |
| 474 | |
| 475 | ri.Hunk_FreeTempMemory(out); |
| 476 | } |