2 Copyright (C) 2002 Mathieu Olivier
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to:
18 Free Software Foundation, Inc.
19 59 Temple Place - Suite 330
20 Boston, MA 02111-1307, USA
29 cvar_t sv_writepicture_quality = {CVAR_SAVE, "sv_writepicture_quality", "10", "WritePicture quality offset (higher means better quality, but slower)"};
32 =================================================================
34 Minimal set of definitions from the JPEG lib
36 WARNING: for a matter of simplicity, several pointer types are
37 casted to "void*", and most enumerated values are not included
39 =================================================================
42 // jboolean is unsigned char instead of int on Win32
44 typedef unsigned char jboolean;
49 #define JPEG_LIB_VERSION 62 // Version 6b
51 typedef void *j_common_ptr;
52 typedef struct jpeg_compress_struct *j_compress_ptr;
53 typedef struct jpeg_decompress_struct *j_decompress_ptr;
63 typedef enum {JPEG_DUMMY1} J_DCT_METHOD;
64 typedef enum {JPEG_DUMMY2} J_DITHER_MODE;
65 typedef unsigned int JDIMENSION;
67 #define JPOOL_PERMANENT 0 // lasts until master record is destroyed
68 #define JPOOL_IMAGE 1 // lasts until done with image/datastream
70 #define JPEG_EOI 0xD9 // EOI marker code
72 #define JMSG_STR_PARM_MAX 80
75 #define NUM_QUANT_TBLS 4
76 #define NUM_HUFF_TBLS 4
77 #define NUM_ARITH_TBLS 16
78 #define MAX_COMPS_IN_SCAN 4
79 #define C_MAX_BLOCKS_IN_MCU 10
80 #define D_MAX_BLOCKS_IN_MCU 10
82 struct jpeg_memory_mgr
84 void* (*alloc_small) (j_common_ptr cinfo, int pool_id, size_t sizeofobject);
85 void (*alloc_large) ();
86 void (*alloc_sarray) ();
87 void (*alloc_barray) ();
88 void (*request_virt_sarray) ();
89 void (*request_virt_barray) ();
90 void (*realize_virt_arrays) ();
91 void (*access_virt_sarray) ();
92 void (*access_virt_barray) ();
94 void (*self_destruct) ();
96 long max_memory_to_use;
100 struct jpeg_error_mgr
102 void (*error_exit) (j_common_ptr cinfo);
103 void (*emit_message) (j_common_ptr cinfo, int msg_level);
104 void (*output_message) (j_common_ptr cinfo);
105 void (*format_message) (j_common_ptr cinfo, char * buffer);
106 void (*reset_error_mgr) (j_common_ptr cinfo);
110 char s[JMSG_STR_PARM_MAX];
114 const char * const * jpeg_message_table;
115 int last_jpeg_message;
116 const char * const * addon_message_table;
117 int first_addon_message;
118 int last_addon_message;
121 struct jpeg_source_mgr
123 const unsigned char *next_input_byte;
124 size_t bytes_in_buffer;
126 void (*init_source) (j_decompress_ptr cinfo);
127 jboolean (*fill_input_buffer) (j_decompress_ptr cinfo);
128 void (*skip_input_data) (j_decompress_ptr cinfo, long num_bytes);
129 jboolean (*resync_to_restart) (j_decompress_ptr cinfo, int desired);
130 void (*term_source) (j_decompress_ptr cinfo);
134 /* These values are fixed over the whole image. */
135 /* For compression, they must be supplied by parameter setup; */
136 /* for decompression, they are read from the SOF marker. */
137 int component_id; /* identifier for this component (0..255) */
138 int component_index; /* its index in SOF or cinfo->comp_info[] */
139 int h_samp_factor; /* horizontal sampling factor (1..4) */
140 int v_samp_factor; /* vertical sampling factor (1..4) */
141 int quant_tbl_no; /* quantization table selector (0..3) */
142 /* These values may vary between scans. */
143 /* For compression, they must be supplied by parameter setup; */
144 /* for decompression, they are read from the SOS marker. */
145 /* The decompressor output side may not use these variables. */
146 int dc_tbl_no; /* DC entropy table selector (0..3) */
147 int ac_tbl_no; /* AC entropy table selector (0..3) */
149 /* Remaining fields should be treated as private by applications. */
151 /* These values are computed during compression or decompression startup: */
152 /* Component's size in DCT blocks.
153 * Any dummy blocks added to complete an MCU are not counted; therefore
154 * these values do not depend on whether a scan is interleaved or not.
156 JDIMENSION width_in_blocks;
157 JDIMENSION height_in_blocks;
158 /* Size of a DCT block in samples. Always DCTSIZE for compression.
159 * For decompression this is the size of the output from one DCT block,
160 * reflecting any scaling we choose to apply during the IDCT step.
161 * Values of 1,2,4,8 are likely to be supported. Note that different
162 * components may receive different IDCT scalings.
165 /* The downsampled dimensions are the component's actual, unpadded number
166 * of samples at the main buffer (preprocessing/compression interface), thus
167 * downsampled_width = ceil(image_width * Hi/Hmax)
168 * and similarly for height. For decompression, IDCT scaling is included, so
169 * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
171 JDIMENSION downsampled_width; /* actual width in samples */
172 JDIMENSION downsampled_height; /* actual height in samples */
173 /* This flag is used only for decompression. In cases where some of the
174 * components will be ignored (eg grayscale output from YCbCr image),
175 * we can skip most computations for the unused components.
177 jboolean component_needed; /* do we need the value of this component? */
179 /* These values are computed before starting a scan of the component. */
180 /* The decompressor output side may not use these variables. */
181 int MCU_width; /* number of blocks per MCU, horizontally */
182 int MCU_height; /* number of blocks per MCU, vertically */
183 int MCU_blocks; /* MCU_width * MCU_height */
184 int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
185 int last_col_width; /* # of non-dummy blocks across in last MCU */
186 int last_row_height; /* # of non-dummy blocks down in last MCU */
188 /* Saved quantization table for component; NULL if none yet saved.
189 * See jdinput.c comments about the need for this information.
190 * This field is currently used only for decompression.
194 /* Private per-component storage for DCT or IDCT subsystem. */
196 } jpeg_component_info;
198 struct jpeg_decompress_struct
200 struct jpeg_error_mgr *err; // USED
201 struct jpeg_memory_mgr *mem; // USED
205 jboolean is_decompressor;
208 struct jpeg_source_mgr *src; // USED
209 JDIMENSION image_width; // USED
210 JDIMENSION image_height; // USED
213 J_COLOR_SPACE jpeg_color_space;
214 J_COLOR_SPACE out_color_space;
215 unsigned int scale_num, scale_denom;
217 jboolean buffered_image;
218 jboolean raw_data_out;
219 J_DCT_METHOD dct_method;
220 jboolean do_fancy_upsampling;
221 jboolean do_block_smoothing;
222 jboolean quantize_colors;
223 J_DITHER_MODE dither_mode;
224 jboolean two_pass_quantize;
225 int desired_number_of_colors;
226 jboolean enable_1pass_quant;
227 jboolean enable_external_quant;
228 jboolean enable_2pass_quant;
229 JDIMENSION output_width;
231 JDIMENSION output_height; // USED
233 int out_color_components;
235 int output_components; // USED
237 int rec_outbuf_height;
238 int actual_number_of_colors;
241 JDIMENSION output_scanline; // USED
243 int input_scan_number;
244 JDIMENSION input_iMCU_row;
245 int output_scan_number;
246 JDIMENSION output_iMCU_row;
247 int (*coef_bits)[DCTSIZE2];
248 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
249 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
250 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
252 jpeg_component_info *comp_info;
253 jboolean progressive_mode;
255 unsigned char arith_dc_L[NUM_ARITH_TBLS];
256 unsigned char arith_dc_U[NUM_ARITH_TBLS];
257 unsigned char arith_ac_K[NUM_ARITH_TBLS];
258 unsigned int restart_interval;
259 jboolean saw_JFIF_marker;
260 unsigned char JFIF_major_version;
261 unsigned char JFIF_minor_version;
262 unsigned char density_unit;
263 unsigned short X_density;
264 unsigned short Y_density;
265 jboolean saw_Adobe_marker;
266 unsigned char Adobe_transform;
267 jboolean CCIR601_sampling;
269 int max_h_samp_factor;
270 int max_v_samp_factor;
271 int min_DCT_scaled_size;
272 JDIMENSION total_iMCU_rows;
273 void *sample_range_limit;
275 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
276 JDIMENSION MCUs_per_row;
277 JDIMENSION MCU_rows_in_scan;
279 int MCU_membership[D_MAX_BLOCKS_IN_MCU];
296 struct jpeg_compress_struct
298 struct jpeg_error_mgr *err;
299 struct jpeg_memory_mgr *mem;
302 jboolean is_decompressor;
306 JDIMENSION image_width;
307 JDIMENSION image_height;
308 int input_components;
309 J_COLOR_SPACE in_color_space;
314 J_COLOR_SPACE jpeg_color_space;
315 jpeg_component_info *comp_info;
316 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
317 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
318 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
319 unsigned char arith_dc_L[NUM_ARITH_TBLS];
320 unsigned char arith_dc_U[NUM_ARITH_TBLS];
321 unsigned char arith_ac_K[NUM_ARITH_TBLS];
324 const void *scan_info;
325 jboolean raw_data_in;
327 jboolean optimize_coding;
328 jboolean CCIR601_sampling;
329 int smoothing_factor;
330 J_DCT_METHOD dct_method;
332 unsigned int restart_interval;
335 jboolean write_JFIF_header;
336 unsigned char JFIF_major_version;
337 unsigned char JFIF_minor_version;
338 unsigned char density_unit;
339 unsigned short X_density;
340 unsigned short Y_density;
341 jboolean write_Adobe_marker;
342 JDIMENSION next_scanline;
344 jboolean progressive_mode;
345 int max_h_samp_factor;
346 int max_v_samp_factor;
347 JDIMENSION total_iMCU_rows;
349 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
350 JDIMENSION MCUs_per_row;
351 JDIMENSION MCU_rows_in_scan;
353 int MCU_membership[C_MAX_BLOCKS_IN_MCU];
366 int script_space_size;
369 struct jpeg_destination_mgr
371 unsigned char* next_output_byte;
372 size_t free_in_buffer;
374 void (*init_destination) (j_compress_ptr cinfo);
375 jboolean (*empty_output_buffer) (j_compress_ptr cinfo);
376 void (*term_destination) (j_compress_ptr cinfo);
381 =================================================================
383 DarkPlaces definitions
385 =================================================================
388 // Functions exported from libjpeg
389 #define qjpeg_create_compress(cinfo) \
390 qjpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_compress_struct))
391 #define qjpeg_create_decompress(cinfo) \
392 qjpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_decompress_struct))
394 static void (*qjpeg_CreateCompress) (j_compress_ptr cinfo, int version, size_t structsize);
395 static void (*qjpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize);
396 static void (*qjpeg_destroy_compress) (j_compress_ptr cinfo);
397 static void (*qjpeg_destroy_decompress) (j_decompress_ptr cinfo);
398 static void (*qjpeg_finish_compress) (j_compress_ptr cinfo);
399 static jboolean (*qjpeg_finish_decompress) (j_decompress_ptr cinfo);
400 static jboolean (*qjpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired);
401 static int (*qjpeg_read_header) (j_decompress_ptr cinfo, jboolean require_image);
402 static JDIMENSION (*qjpeg_read_scanlines) (j_decompress_ptr cinfo, unsigned char** scanlines, JDIMENSION max_lines);
403 static void (*qjpeg_set_defaults) (j_compress_ptr cinfo);
404 static void (*qjpeg_set_quality) (j_compress_ptr cinfo, int quality, jboolean force_baseline);
405 static jboolean (*qjpeg_start_compress) (j_compress_ptr cinfo, jboolean write_all_tables);
406 static jboolean (*qjpeg_start_decompress) (j_decompress_ptr cinfo);
407 static struct jpeg_error_mgr* (*qjpeg_std_error) (struct jpeg_error_mgr *err);
408 static JDIMENSION (*qjpeg_write_scanlines) (j_compress_ptr cinfo, unsigned char** scanlines, JDIMENSION num_lines);
410 static dllfunction_t jpegfuncs[] =
412 {"jpeg_CreateCompress", (void **) &qjpeg_CreateCompress},
413 {"jpeg_CreateDecompress", (void **) &qjpeg_CreateDecompress},
414 {"jpeg_destroy_compress", (void **) &qjpeg_destroy_compress},
415 {"jpeg_destroy_decompress", (void **) &qjpeg_destroy_decompress},
416 {"jpeg_finish_compress", (void **) &qjpeg_finish_compress},
417 {"jpeg_finish_decompress", (void **) &qjpeg_finish_decompress},
418 {"jpeg_resync_to_restart", (void **) &qjpeg_resync_to_restart},
419 {"jpeg_read_header", (void **) &qjpeg_read_header},
420 {"jpeg_read_scanlines", (void **) &qjpeg_read_scanlines},
421 {"jpeg_set_defaults", (void **) &qjpeg_set_defaults},
422 {"jpeg_set_quality", (void **) &qjpeg_set_quality},
423 {"jpeg_start_compress", (void **) &qjpeg_start_compress},
424 {"jpeg_start_decompress", (void **) &qjpeg_start_decompress},
425 {"jpeg_std_error", (void **) &qjpeg_std_error},
426 {"jpeg_write_scanlines", (void **) &qjpeg_write_scanlines},
430 // Handle for JPEG DLL
431 dllhandle_t jpeg_dll = NULL;
432 qboolean jpeg_tried_loading = 0;
434 static unsigned char jpeg_eoi_marker [2] = {0xFF, JPEG_EOI};
435 static jmp_buf error_in_jpeg;
436 static qboolean jpeg_toolarge;
438 // Our own output manager for JPEG compression
441 struct jpeg_destination_mgr pub;
444 unsigned char* buffer;
445 size_t bufsize; // used if outfile is NULL
446 } my_destination_mgr;
447 typedef my_destination_mgr* my_dest_ptr;
451 =================================================================
455 =================================================================
462 Try to load the JPEG DLL
465 qboolean JPEG_OpenLibrary (void)
467 const char* dllnames [] =
473 #elif defined(MACOSX)
486 if (jpeg_tried_loading) // only try once
489 jpeg_tried_loading = true;
492 return Sys_LoadLibrary (dllnames, &jpeg_dll, jpegfuncs);
503 void JPEG_CloseLibrary (void)
505 Sys_UnloadLibrary (&jpeg_dll);
506 jpeg_tried_loading = false; // allow retry
511 =================================================================
515 =================================================================
518 static void JPEG_Noop (j_decompress_ptr cinfo) {}
520 static jboolean JPEG_FillInputBuffer (j_decompress_ptr cinfo)
522 // Insert a fake EOI marker
523 cinfo->src->next_input_byte = jpeg_eoi_marker;
524 cinfo->src->bytes_in_buffer = 2;
529 static void JPEG_SkipInputData (j_decompress_ptr cinfo, long num_bytes)
531 if (cinfo->src->bytes_in_buffer <= (unsigned long)num_bytes)
533 cinfo->src->bytes_in_buffer = 0;
537 cinfo->src->next_input_byte += num_bytes;
538 cinfo->src->bytes_in_buffer -= num_bytes;
541 static void JPEG_MemSrc (j_decompress_ptr cinfo, const unsigned char *buffer, size_t filesize)
543 cinfo->src = (struct jpeg_source_mgr *)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
545 cinfo->src->next_input_byte = buffer;
546 cinfo->src->bytes_in_buffer = filesize;
548 cinfo->src->init_source = JPEG_Noop;
549 cinfo->src->fill_input_buffer = JPEG_FillInputBuffer;
550 cinfo->src->skip_input_data = JPEG_SkipInputData;
551 cinfo->src->resync_to_restart = qjpeg_resync_to_restart; // use the default method
552 cinfo->src->term_source = JPEG_Noop;
555 static void JPEG_ErrorExit (j_common_ptr cinfo)
557 ((struct jpeg_decompress_struct*)cinfo)->err->output_message (cinfo);
558 longjmp(error_in_jpeg, 1);
566 Load a JPEG image into a BGRA buffer
569 unsigned char* JPEG_LoadImage_BGRA (const unsigned char *f, int filesize)
571 struct jpeg_decompress_struct cinfo;
572 struct jpeg_error_mgr jerr;
573 unsigned char *image_buffer = NULL, *scanline = NULL;
580 cinfo.err = qjpeg_std_error (&jerr);
581 qjpeg_create_decompress (&cinfo);
582 if(setjmp(error_in_jpeg))
584 cinfo.err = qjpeg_std_error (&jerr);
585 cinfo.err->error_exit = JPEG_ErrorExit;
586 JPEG_MemSrc (&cinfo, f, filesize);
587 qjpeg_read_header (&cinfo, TRUE);
588 qjpeg_start_decompress (&cinfo);
590 image_width = cinfo.image_width;
591 image_height = cinfo.image_height;
593 if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
595 Con_Printf("JPEG_LoadImage: invalid image size %ix%i\n", image_width, image_height);
599 image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
600 scanline = (unsigned char *)Mem_Alloc(tempmempool, image_width * cinfo.output_components);
601 if (!image_buffer || !scanline)
604 Mem_Free (image_buffer);
608 Con_Printf("JPEG_LoadImage: not enough memory for %i by %i image\n", image_width, image_height);
609 qjpeg_finish_decompress (&cinfo);
610 qjpeg_destroy_decompress (&cinfo);
614 // Decompress the image, line by line
616 while (cinfo.output_scanline < cinfo.output_height)
618 unsigned char *buffer_ptr;
621 qjpeg_read_scanlines (&cinfo, &scanline, 1);
623 // Convert the image to BGRA
624 switch (cinfo.output_components)
628 buffer_ptr = &image_buffer[image_width * line * 4];
629 for (ind = 0; ind < image_width * 3; ind += 3, buffer_ptr += 4)
631 buffer_ptr[2] = scanline[ind];
632 buffer_ptr[1] = scanline[ind + 1];
633 buffer_ptr[0] = scanline[ind + 2];
638 // Greyscale images (default to it, just in case)
641 buffer_ptr = &image_buffer[image_width * line * 4];
642 for (ind = 0; ind < image_width; ind++, buffer_ptr += 4)
644 buffer_ptr[0] = scanline[ind];
645 buffer_ptr[1] = scanline[ind];
646 buffer_ptr[2] = scanline[ind];
655 qjpeg_finish_decompress (&cinfo);
656 qjpeg_destroy_decompress (&cinfo);
664 Mem_Free (image_buffer);
665 qjpeg_destroy_decompress (&cinfo);
671 =================================================================
675 =================================================================
678 #define JPEG_OUTPUT_BUF_SIZE 4096
679 static void JPEG_InitDestination (j_compress_ptr cinfo)
681 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
682 dest->buffer = (unsigned char*)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_IMAGE, JPEG_OUTPUT_BUF_SIZE * sizeof(unsigned char));
683 dest->pub.next_output_byte = dest->buffer;
684 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
687 static jboolean JPEG_EmptyOutputBuffer (j_compress_ptr cinfo)
689 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
691 if (FS_Write (dest->outfile, dest->buffer, JPEG_OUTPUT_BUF_SIZE) != (size_t) JPEG_OUTPUT_BUF_SIZE)
692 longjmp(error_in_jpeg, 1);
694 dest->pub.next_output_byte = dest->buffer;
695 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
699 static void JPEG_TermDestination (j_compress_ptr cinfo)
701 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
702 size_t datacount = JPEG_OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
704 // Write any data remaining in the buffer
706 if (FS_Write (dest->outfile, dest->buffer, datacount) != (fs_offset_t)datacount)
707 longjmp(error_in_jpeg, 1);
710 static void JPEG_FileDest (j_compress_ptr cinfo, qfile_t* outfile)
714 // First time for this JPEG object?
715 if (cinfo->dest == NULL)
716 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
718 dest = (my_dest_ptr)cinfo->dest;
719 dest->pub.init_destination = JPEG_InitDestination;
720 dest->pub.empty_output_buffer = JPEG_EmptyOutputBuffer;
721 dest->pub.term_destination = JPEG_TermDestination;
722 dest->outfile = outfile;
725 static void JPEG_Mem_InitDestination (j_compress_ptr cinfo)
727 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
728 dest->pub.next_output_byte = dest->buffer;
729 dest->pub.free_in_buffer = dest->bufsize;
732 static jboolean JPEG_Mem_EmptyOutputBuffer (j_compress_ptr cinfo)
734 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
735 jpeg_toolarge = true;
736 dest->pub.next_output_byte = dest->buffer;
737 dest->pub.free_in_buffer = dest->bufsize;
741 static void JPEG_Mem_TermDestination (j_compress_ptr cinfo)
743 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
744 dest->bufsize = dest->pub.next_output_byte - dest->buffer;
746 static void JPEG_MemDest (j_compress_ptr cinfo, void* buf, size_t bufsize)
750 // First time for this JPEG object?
751 if (cinfo->dest == NULL)
752 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
754 dest = (my_dest_ptr)cinfo->dest;
755 dest->pub.init_destination = JPEG_Mem_InitDestination;
756 dest->pub.empty_output_buffer = JPEG_Mem_EmptyOutputBuffer;
757 dest->pub.term_destination = JPEG_Mem_TermDestination;
758 dest->outfile = NULL;
760 dest->buffer = (unsigned char *) buf;
761 dest->bufsize = bufsize;
767 JPEG_SaveImage_preflipped
769 Save a preflipped JPEG image to a file
772 qboolean JPEG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
774 struct jpeg_compress_struct cinfo;
775 struct jpeg_error_mgr jerr;
776 unsigned char *scanline;
777 unsigned int offset, linesize;
783 Con_Print("You need the libjpeg library to save JPEG images\n");
788 file = FS_OpenRealFile(filename, "wb", true);
792 if(setjmp(error_in_jpeg))
794 cinfo.err = qjpeg_std_error (&jerr);
795 cinfo.err->error_exit = JPEG_ErrorExit;
797 qjpeg_create_compress (&cinfo);
798 JPEG_FileDest (&cinfo, file);
800 // Set the parameters for compression
801 cinfo.image_width = width;
802 cinfo.image_height = height;
803 cinfo.in_color_space = JCS_RGB;
804 cinfo.input_components = 3;
805 qjpeg_set_defaults (&cinfo);
806 qjpeg_set_quality (&cinfo, (int)(scr_screenshot_jpeg_quality.value * 100), TRUE);
808 // turn off subsampling (to make text look better)
809 cinfo.optimize_coding = 1;
810 cinfo.comp_info[0].h_samp_factor = 1;
811 cinfo.comp_info[0].v_samp_factor = 1;
812 cinfo.comp_info[1].h_samp_factor = 1;
813 cinfo.comp_info[1].v_samp_factor = 1;
814 cinfo.comp_info[2].h_samp_factor = 1;
815 cinfo.comp_info[2].v_samp_factor = 1;
817 qjpeg_start_compress (&cinfo, true);
819 // Compress each scanline
820 linesize = cinfo.image_width * 3;
821 offset = linesize * (cinfo.image_height - 1);
822 while (cinfo.next_scanline < cinfo.image_height)
824 scanline = &data[offset - cinfo.next_scanline * linesize];
826 qjpeg_write_scanlines (&cinfo, &scanline, 1);
829 qjpeg_finish_compress (&cinfo);
830 qjpeg_destroy_compress (&cinfo);
836 qjpeg_destroy_compress (&cinfo);
841 static size_t JPEG_try_SaveImage_to_Buffer (struct jpeg_compress_struct *cinfo, char *jpegbuf, size_t jpegsize, int quality, int width, int height, unsigned char *data)
843 unsigned char *scanline;
844 unsigned int linesize;
846 jpeg_toolarge = false;
847 JPEG_MemDest (cinfo, jpegbuf, jpegsize);
849 // Set the parameters for compression
850 cinfo->image_width = width;
851 cinfo->image_height = height;
852 cinfo->in_color_space = JCS_RGB;
853 cinfo->input_components = 3;
854 qjpeg_set_defaults (cinfo);
855 qjpeg_set_quality (cinfo, quality, FALSE);
857 cinfo->comp_info[0].h_samp_factor = 2;
858 cinfo->comp_info[0].v_samp_factor = 2;
859 cinfo->comp_info[1].h_samp_factor = 1;
860 cinfo->comp_info[1].v_samp_factor = 1;
861 cinfo->comp_info[2].h_samp_factor = 1;
862 cinfo->comp_info[2].v_samp_factor = 1;
863 cinfo->optimize_coding = 1;
865 qjpeg_start_compress (cinfo, true);
867 // Compress each scanline
868 linesize = width * 3;
869 while (cinfo->next_scanline < cinfo->image_height)
871 scanline = &data[cinfo->next_scanline * linesize];
873 qjpeg_write_scanlines (cinfo, &scanline, 1);
876 qjpeg_finish_compress (cinfo);
881 return ((my_dest_ptr) cinfo->dest)->bufsize;
884 size_t JPEG_SaveImage_to_Buffer (char *jpegbuf, size_t jpegsize, int width, int height, unsigned char *data)
886 struct jpeg_compress_struct cinfo;
887 struct jpeg_error_mgr jerr;
896 Con_Print("You need the libjpeg library to save JPEG images\n");
900 if(setjmp(error_in_jpeg))
902 cinfo.err = qjpeg_std_error (&jerr);
903 cinfo.err->error_exit = JPEG_ErrorExit;
905 qjpeg_create_compress (&cinfo);
908 // used to get the formula below
914 img = Mem_Alloc(tempmempool, width * height * 3);
915 for(i = 0; i < width * height * 3; ++i)
916 img[i] = rand() & 0xFF;
918 for(i = 0; i <= 100; ++i)
920 Con_Printf("! %d %d %d %d\n", width, height, i, (int) JPEG_try_SaveImage_to_Buffer(&cinfo, buf, sizeof(buf), i, width, height, img));
927 //quality_guess = (100 * jpegsize - 41000) / (width*height) + 2; // fits random data
928 quality_guess = (256 * jpegsize - 81920) / (width*height) - 8; // fits Nexuiz's map pictures
930 quality_guess = bound(0, quality_guess, 100);
931 quality = bound(0, quality_guess + sv_writepicture_quality.integer, 100); // assume it can do 10 failed attempts
933 while(!(result = JPEG_try_SaveImage_to_Buffer(&cinfo, jpegbuf, jpegsize, quality, width, height, data)))
938 Con_Printf("couldn't write image at all, probably too big\n");
942 qjpeg_destroy_compress (&cinfo);
943 Con_DPrintf("JPEG_SaveImage_to_Buffer: guessed quality/size %d/%d, actually got %d/%d\n", quality_guess, (int)jpegsize, quality, (int)result);
948 qjpeg_destroy_compress (&cinfo);
952 typedef struct CompressedImageCacheItem
954 char imagename[MAX_QPATH];
957 size_t compressed_size;
958 struct CompressedImageCacheItem *next;
960 CompressedImageCacheItem;
961 #define COMPRESSEDIMAGECACHE_SIZE 4096
962 static CompressedImageCacheItem *CompressedImageCache[COMPRESSEDIMAGECACHE_SIZE];
964 static void CompressedImageCache_Add(const char *imagename, size_t maxsize, void *compressed, size_t compressed_size)
966 const char *hashkey = va("%s:%d", imagename, (int) maxsize);
967 int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
968 CompressedImageCacheItem *i;
970 if(strlen(imagename) >= MAX_QPATH)
971 return; // can't add this
973 i = (CompressedImageCacheItem*) Z_Malloc(sizeof(CompressedImageCacheItem));
974 strlcpy(i->imagename, imagename, sizeof(i->imagename));
975 i->maxsize = maxsize;
976 i->compressed = compressed;
977 i->compressed_size = compressed_size;
978 i->next = CompressedImageCache[hashindex];
979 CompressedImageCache[hashindex] = i;
982 static CompressedImageCacheItem *CompressedImageCache_Find(const char *imagename, size_t maxsize)
984 const char *hashkey = va("%s:%d", imagename, (int) maxsize);
985 int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
986 CompressedImageCacheItem *i = CompressedImageCache[hashindex];
990 if(i->maxsize == maxsize)
991 if(!strcmp(i->imagename, imagename))
998 qboolean Image_Compress(const char *imagename, size_t maxsize, void **buf, size_t *size)
1000 unsigned char *imagedata, *newimagedata;
1002 int components[3] = {2, 1, 0};
1003 CompressedImageCacheItem *i;
1005 JPEG_OpenLibrary (); // for now; LH had the idea of replacing this by a better format
1007 // No DLL = no JPEGs
1010 Con_Print("You need the libjpeg library to save JPEG images\n");
1014 i = CompressedImageCache_Find(imagename, maxsize);
1017 *size = i->compressed_size;
1018 *buf = i->compressed;
1022 imagedata = loadimagepixelsbgra(imagename, true, false);
1026 // find an appropriate size for somewhat okay compression
1028 maxPixelCount = 32 * 32;
1029 else if(maxsize <= 1024)
1030 maxPixelCount = 64 * 64;
1031 else if(maxsize <= 4096)
1032 maxPixelCount = 128 * 128;
1034 maxPixelCount = 256 * 256;
1036 while(image_width * image_height > maxPixelCount)
1039 Image_MipReduce32(imagedata, imagedata, &image_width, &image_height, &one, image_width/2, image_height/2, 1);
1042 newimagedata = (unsigned char *) Mem_Alloc(tempmempool, image_width * image_height * 3);
1044 // convert the image from BGRA to RGB
1045 Image_CopyMux(newimagedata, imagedata, image_width, image_height, false, false, false, 3, 4, components);
1046 Mem_Free(imagedata);
1048 // try to compress it to JPEG
1049 *buf = Z_Malloc(maxsize);
1050 *size = JPEG_SaveImage_to_Buffer((char *) *buf, maxsize, image_width, image_height, newimagedata);
1051 Mem_Free(newimagedata);
1057 Con_Printf("could not compress image %s to %d bytes\n", imagename, (int)maxsize);
1059 // also cache failures!
1062 // store it in the cache
1063 CompressedImageCache_Add(imagename, maxsize, *buf, *size);
1064 return (*buf != NULL);