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)"};
31 // jboolean is unsigned char instead of int on Win32
33 typedef unsigned char jboolean;
38 #ifdef LINK_TO_LIBJPEG
40 #define qjpeg_create_compress jpeg_create_compress
41 #define qjpeg_create_decompress jpeg_create_decompress
42 #define qjpeg_destroy_compress jpeg_destroy_compress
43 #define qjpeg_destroy_decompress jpeg_destroy_decompress
44 #define qjpeg_finish_compress jpeg_finish_compress
45 #define qjpeg_finish_decompress jpeg_finish_decompress
46 #define qjpeg_resync_to_restart jpeg_resync_to_restart
47 #define qjpeg_read_header jpeg_read_header
48 #define qjpeg_read_scanlines jpeg_read_scanlines
49 #define qjpeg_set_defaults jpeg_set_defaults
50 #define qjpeg_set_quality jpeg_set_quality
51 #define qjpeg_start_compress jpeg_start_compress
52 #define qjpeg_start_decompress jpeg_start_decompress
53 #define qjpeg_std_error jpeg_std_error
54 #define qjpeg_write_scanlines jpeg_write_scanlines
55 #define qjpeg_simple_progression jpeg_simple_progression
59 =================================================================
61 Minimal set of definitions from the JPEG lib
63 WARNING: for a matter of simplicity, several pointer types are
64 casted to "void*", and most enumerated values are not included
66 =================================================================
69 typedef void *j_common_ptr;
70 typedef struct jpeg_compress_struct *j_compress_ptr;
71 typedef struct jpeg_decompress_struct *j_decompress_ptr;
73 #define JPEG_LIB_VERSION 62 // Version 6b
84 typedef enum {JPEG_DUMMY1} J_DCT_METHOD;
85 typedef enum {JPEG_DUMMY2} J_DITHER_MODE;
86 typedef unsigned int JDIMENSION;
88 #define JPOOL_PERMANENT 0 // lasts until master record is destroyed
89 #define JPOOL_IMAGE 1 // lasts until done with image/datastream
91 #define JPEG_EOI 0xD9 // EOI marker code
93 #define JMSG_STR_PARM_MAX 80
96 #define NUM_QUANT_TBLS 4
97 #define NUM_HUFF_TBLS 4
98 #define NUM_ARITH_TBLS 16
99 #define MAX_COMPS_IN_SCAN 4
100 #define C_MAX_BLOCKS_IN_MCU 10
101 #define D_MAX_BLOCKS_IN_MCU 10
103 struct jpeg_memory_mgr
105 void* (*alloc_small) (j_common_ptr cinfo, int pool_id, size_t sizeofobject);
106 void (*_reserve_space_for_alloc_large) (void *dummy, ...);
107 void (*_reserve_space_for_alloc_sarray) (void *dummy, ...);
108 void (*_reserve_space_for_alloc_barray) (void *dummy, ...);
109 void (*_reserve_space_for_request_virt_sarray) (void *dummy, ...);
110 void (*_reserve_space_for_request_virt_barray) (void *dummy, ...);
111 void (*_reserve_space_for_realize_virt_arrays) (void *dummy, ...);
112 void (*_reserve_space_for_access_virt_sarray) (void *dummy, ...);
113 void (*_reserve_space_for_access_virt_barray) (void *dummy, ...);
114 void (*_reserve_space_for_free_pool) (void *dummy, ...);
115 void (*_reserve_space_for_self_destruct) (void *dummy, ...);
117 long max_memory_to_use;
118 long max_alloc_chunk;
121 struct jpeg_error_mgr
123 void (*error_exit) (j_common_ptr cinfo);
124 void (*emit_message) (j_common_ptr cinfo, int msg_level);
125 void (*output_message) (j_common_ptr cinfo);
126 void (*format_message) (j_common_ptr cinfo, char * buffer);
127 void (*reset_error_mgr) (j_common_ptr cinfo);
131 char s[JMSG_STR_PARM_MAX];
135 const char * const * jpeg_message_table;
136 int last_jpeg_message;
137 const char * const * addon_message_table;
138 int first_addon_message;
139 int last_addon_message;
142 struct jpeg_source_mgr
144 const unsigned char *next_input_byte;
145 size_t bytes_in_buffer;
147 void (*init_source) (j_decompress_ptr cinfo);
148 jboolean (*fill_input_buffer) (j_decompress_ptr cinfo);
149 void (*skip_input_data) (j_decompress_ptr cinfo, long num_bytes);
150 jboolean (*resync_to_restart) (j_decompress_ptr cinfo, int desired);
151 void (*term_source) (j_decompress_ptr cinfo);
155 /* These values are fixed over the whole image. */
156 /* For compression, they must be supplied by parameter setup; */
157 /* for decompression, they are read from the SOF marker. */
158 int component_id; /* identifier for this component (0..255) */
159 int component_index; /* its index in SOF or cinfo->comp_info[] */
160 int h_samp_factor; /* horizontal sampling factor (1..4) */
161 int v_samp_factor; /* vertical sampling factor (1..4) */
162 int quant_tbl_no; /* quantization table selector (0..3) */
163 /* These values may vary between scans. */
164 /* For compression, they must be supplied by parameter setup; */
165 /* for decompression, they are read from the SOS marker. */
166 /* The decompressor output side may not use these variables. */
167 int dc_tbl_no; /* DC entropy table selector (0..3) */
168 int ac_tbl_no; /* AC entropy table selector (0..3) */
170 /* Remaining fields should be treated as private by applications. */
172 /* These values are computed during compression or decompression startup: */
173 /* Component's size in DCT blocks.
174 * Any dummy blocks added to complete an MCU are not counted; therefore
175 * these values do not depend on whether a scan is interleaved or not.
177 JDIMENSION width_in_blocks;
178 JDIMENSION height_in_blocks;
179 /* Size of a DCT block in samples. Always DCTSIZE for compression.
180 * For decompression this is the size of the output from one DCT block,
181 * reflecting any scaling we choose to apply during the IDCT step.
182 * Values of 1,2,4,8 are likely to be supported. Note that different
183 * components may receive different IDCT scalings.
186 /* The downsampled dimensions are the component's actual, unpadded number
187 * of samples at the main buffer (preprocessing/compression interface), thus
188 * downsampled_width = ceil(image_width * Hi/Hmax)
189 * and similarly for height. For decompression, IDCT scaling is included, so
190 * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
192 JDIMENSION downsampled_width; /* actual width in samples */
193 JDIMENSION downsampled_height; /* actual height in samples */
194 /* This flag is used only for decompression. In cases where some of the
195 * components will be ignored (eg grayscale output from YCbCr image),
196 * we can skip most computations for the unused components.
198 jboolean component_needed; /* do we need the value of this component? */
200 /* These values are computed before starting a scan of the component. */
201 /* The decompressor output side may not use these variables. */
202 int MCU_width; /* number of blocks per MCU, horizontally */
203 int MCU_height; /* number of blocks per MCU, vertically */
204 int MCU_blocks; /* MCU_width * MCU_height */
205 int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
206 int last_col_width; /* # of non-dummy blocks across in last MCU */
207 int last_row_height; /* # of non-dummy blocks down in last MCU */
209 /* Saved quantization table for component; NULL if none yet saved.
210 * See jdinput.c comments about the need for this information.
211 * This field is currently used only for decompression.
215 /* Private per-component storage for DCT or IDCT subsystem. */
217 } jpeg_component_info;
219 struct jpeg_decompress_struct
221 struct jpeg_error_mgr *err; // USED
222 struct jpeg_memory_mgr *mem; // USED
226 jboolean is_decompressor;
229 struct jpeg_source_mgr *src; // USED
230 JDIMENSION image_width; // USED
231 JDIMENSION image_height; // USED
234 J_COLOR_SPACE jpeg_color_space;
235 J_COLOR_SPACE out_color_space;
236 unsigned int scale_num, scale_denom;
238 jboolean buffered_image;
239 jboolean raw_data_out;
240 J_DCT_METHOD dct_method;
241 jboolean do_fancy_upsampling;
242 jboolean do_block_smoothing;
243 jboolean quantize_colors;
244 J_DITHER_MODE dither_mode;
245 jboolean two_pass_quantize;
246 int desired_number_of_colors;
247 jboolean enable_1pass_quant;
248 jboolean enable_external_quant;
249 jboolean enable_2pass_quant;
250 JDIMENSION output_width;
252 JDIMENSION output_height; // USED
254 int out_color_components;
256 int output_components; // USED
258 int rec_outbuf_height;
259 int actual_number_of_colors;
262 JDIMENSION output_scanline; // USED
264 int input_scan_number;
265 JDIMENSION input_iMCU_row;
266 int output_scan_number;
267 JDIMENSION output_iMCU_row;
268 int (*coef_bits)[DCTSIZE2];
269 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
270 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
271 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
273 jpeg_component_info *comp_info;
274 jboolean progressive_mode;
276 unsigned char arith_dc_L[NUM_ARITH_TBLS];
277 unsigned char arith_dc_U[NUM_ARITH_TBLS];
278 unsigned char arith_ac_K[NUM_ARITH_TBLS];
279 unsigned int restart_interval;
280 jboolean saw_JFIF_marker;
281 unsigned char JFIF_major_version;
282 unsigned char JFIF_minor_version;
283 unsigned char density_unit;
284 unsigned short X_density;
285 unsigned short Y_density;
286 jboolean saw_Adobe_marker;
287 unsigned char Adobe_transform;
288 jboolean CCIR601_sampling;
290 int max_h_samp_factor;
291 int max_v_samp_factor;
292 int min_DCT_scaled_size;
293 JDIMENSION total_iMCU_rows;
294 void *sample_range_limit;
296 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
297 JDIMENSION MCUs_per_row;
298 JDIMENSION MCU_rows_in_scan;
300 int MCU_membership[D_MAX_BLOCKS_IN_MCU];
317 struct jpeg_compress_struct
319 struct jpeg_error_mgr *err;
320 struct jpeg_memory_mgr *mem;
323 jboolean is_decompressor;
327 JDIMENSION image_width;
328 JDIMENSION image_height;
329 int input_components;
330 J_COLOR_SPACE in_color_space;
335 J_COLOR_SPACE jpeg_color_space;
336 jpeg_component_info *comp_info;
337 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
338 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
339 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
340 unsigned char arith_dc_L[NUM_ARITH_TBLS];
341 unsigned char arith_dc_U[NUM_ARITH_TBLS];
342 unsigned char arith_ac_K[NUM_ARITH_TBLS];
345 const void *scan_info;
346 jboolean raw_data_in;
348 jboolean optimize_coding;
349 jboolean CCIR601_sampling;
350 int smoothing_factor;
351 J_DCT_METHOD dct_method;
353 unsigned int restart_interval;
356 jboolean write_JFIF_header;
357 unsigned char JFIF_major_version;
358 unsigned char JFIF_minor_version;
359 unsigned char density_unit;
360 unsigned short X_density;
361 unsigned short Y_density;
362 jboolean write_Adobe_marker;
363 JDIMENSION next_scanline;
365 jboolean progressive_mode;
366 int max_h_samp_factor;
367 int max_v_samp_factor;
368 JDIMENSION total_iMCU_rows;
370 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
371 JDIMENSION MCUs_per_row;
372 JDIMENSION MCU_rows_in_scan;
374 int MCU_membership[C_MAX_BLOCKS_IN_MCU];
387 int script_space_size;
390 struct jpeg_destination_mgr
392 unsigned char* next_output_byte;
393 size_t free_in_buffer;
395 void (*init_destination) (j_compress_ptr cinfo);
396 jboolean (*empty_output_buffer) (j_compress_ptr cinfo);
397 void (*term_destination) (j_compress_ptr cinfo);
402 =================================================================
404 DarkPlaces definitions
406 =================================================================
409 // Functions exported from libjpeg
410 #define qjpeg_create_compress(cinfo) \
411 qjpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_compress_struct))
412 #define qjpeg_create_decompress(cinfo) \
413 qjpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_decompress_struct))
415 static void (*qjpeg_CreateCompress) (j_compress_ptr cinfo, int version, size_t structsize);
416 static void (*qjpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize);
417 static void (*qjpeg_destroy_compress) (j_compress_ptr cinfo);
418 static void (*qjpeg_destroy_decompress) (j_decompress_ptr cinfo);
419 static void (*qjpeg_finish_compress) (j_compress_ptr cinfo);
420 static jboolean (*qjpeg_finish_decompress) (j_decompress_ptr cinfo);
421 static jboolean (*qjpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired);
422 static int (*qjpeg_read_header) (j_decompress_ptr cinfo, jboolean require_image);
423 static JDIMENSION (*qjpeg_read_scanlines) (j_decompress_ptr cinfo, unsigned char** scanlines, JDIMENSION max_lines);
424 static void (*qjpeg_set_defaults) (j_compress_ptr cinfo);
425 static void (*qjpeg_set_quality) (j_compress_ptr cinfo, int quality, jboolean force_baseline);
426 static jboolean (*qjpeg_start_compress) (j_compress_ptr cinfo, jboolean write_all_tables);
427 static jboolean (*qjpeg_start_decompress) (j_decompress_ptr cinfo);
428 static struct jpeg_error_mgr* (*qjpeg_std_error) (struct jpeg_error_mgr *err);
429 static JDIMENSION (*qjpeg_write_scanlines) (j_compress_ptr cinfo, unsigned char** scanlines, JDIMENSION num_lines);
430 static void (*qjpeg_simple_progression) (j_compress_ptr cinfo);
432 static dllfunction_t jpegfuncs[] =
434 {"jpeg_CreateCompress", (void **) &qjpeg_CreateCompress},
435 {"jpeg_CreateDecompress", (void **) &qjpeg_CreateDecompress},
436 {"jpeg_destroy_compress", (void **) &qjpeg_destroy_compress},
437 {"jpeg_destroy_decompress", (void **) &qjpeg_destroy_decompress},
438 {"jpeg_finish_compress", (void **) &qjpeg_finish_compress},
439 {"jpeg_finish_decompress", (void **) &qjpeg_finish_decompress},
440 {"jpeg_resync_to_restart", (void **) &qjpeg_resync_to_restart},
441 {"jpeg_read_header", (void **) &qjpeg_read_header},
442 {"jpeg_read_scanlines", (void **) &qjpeg_read_scanlines},
443 {"jpeg_set_defaults", (void **) &qjpeg_set_defaults},
444 {"jpeg_set_quality", (void **) &qjpeg_set_quality},
445 {"jpeg_start_compress", (void **) &qjpeg_start_compress},
446 {"jpeg_start_decompress", (void **) &qjpeg_start_decompress},
447 {"jpeg_std_error", (void **) &qjpeg_std_error},
448 {"jpeg_write_scanlines", (void **) &qjpeg_write_scanlines},
449 {"jpeg_simple_progression", (void **) &qjpeg_simple_progression},
453 // Handle for JPEG DLL
454 dllhandle_t jpeg_dll = NULL;
455 qboolean jpeg_tried_loading = 0;
458 static unsigned char jpeg_eoi_marker [2] = {0xFF, JPEG_EOI};
459 static jmp_buf error_in_jpeg;
460 static qboolean jpeg_toolarge;
462 // Our own output manager for JPEG compression
465 struct jpeg_destination_mgr pub;
468 unsigned char* buffer;
469 size_t bufsize; // used if outfile is NULL
470 } my_destination_mgr;
471 typedef my_destination_mgr* my_dest_ptr;
475 =================================================================
479 =================================================================
486 Try to load the JPEG DLL
489 qboolean JPEG_OpenLibrary (void)
491 #ifdef LINK_TO_LIBJPEG
494 const char* dllnames [] =
498 #elif defined(MACOSX)
511 if (jpeg_tried_loading) // only try once
514 jpeg_tried_loading = true;
517 return Sys_LoadLibrary (dllnames, &jpeg_dll, jpegfuncs);
529 void JPEG_CloseLibrary (void)
531 #ifndef LINK_TO_LIBJPEG
532 Sys_UnloadLibrary (&jpeg_dll);
533 jpeg_tried_loading = false; // allow retry
539 =================================================================
543 =================================================================
546 static void JPEG_Noop (j_decompress_ptr cinfo) {}
548 static jboolean JPEG_FillInputBuffer (j_decompress_ptr cinfo)
550 // Insert a fake EOI marker
551 cinfo->src->next_input_byte = jpeg_eoi_marker;
552 cinfo->src->bytes_in_buffer = 2;
557 static void JPEG_SkipInputData (j_decompress_ptr cinfo, long num_bytes)
559 if (cinfo->src->bytes_in_buffer <= (unsigned long)num_bytes)
561 cinfo->src->bytes_in_buffer = 0;
565 cinfo->src->next_input_byte += num_bytes;
566 cinfo->src->bytes_in_buffer -= num_bytes;
569 static void JPEG_MemSrc (j_decompress_ptr cinfo, const unsigned char *buffer, size_t filesize)
571 cinfo->src = (struct jpeg_source_mgr *)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
573 cinfo->src->next_input_byte = buffer;
574 cinfo->src->bytes_in_buffer = filesize;
576 cinfo->src->init_source = JPEG_Noop;
577 cinfo->src->fill_input_buffer = JPEG_FillInputBuffer;
578 cinfo->src->skip_input_data = JPEG_SkipInputData;
579 cinfo->src->resync_to_restart = qjpeg_resync_to_restart; // use the default method
580 cinfo->src->term_source = JPEG_Noop;
583 static void JPEG_ErrorExit (j_common_ptr cinfo)
585 ((struct jpeg_decompress_struct*)cinfo)->err->output_message (cinfo);
586 longjmp(error_in_jpeg, 1);
594 Load a JPEG image into a BGRA buffer
597 unsigned char* JPEG_LoadImage_BGRA (const unsigned char *f, int filesize)
599 struct jpeg_decompress_struct cinfo;
600 struct jpeg_error_mgr jerr;
601 unsigned char *image_buffer = NULL, *scanline = NULL;
608 cinfo.err = qjpeg_std_error (&jerr);
609 qjpeg_create_decompress (&cinfo);
610 if(setjmp(error_in_jpeg))
612 cinfo.err = qjpeg_std_error (&jerr);
613 cinfo.err->error_exit = JPEG_ErrorExit;
614 JPEG_MemSrc (&cinfo, f, filesize);
615 qjpeg_read_header (&cinfo, TRUE);
616 qjpeg_start_decompress (&cinfo);
618 image_width = cinfo.image_width;
619 image_height = cinfo.image_height;
621 if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
623 Con_Printf("JPEG_LoadImage: invalid image size %ix%i\n", image_width, image_height);
627 image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
628 scanline = (unsigned char *)Mem_Alloc(tempmempool, image_width * cinfo.output_components);
629 if (!image_buffer || !scanline)
632 Mem_Free (image_buffer);
636 Con_Printf("JPEG_LoadImage: not enough memory for %i by %i image\n", image_width, image_height);
637 qjpeg_finish_decompress (&cinfo);
638 qjpeg_destroy_decompress (&cinfo);
642 // Decompress the image, line by line
644 while (cinfo.output_scanline < cinfo.output_height)
646 unsigned char *buffer_ptr;
649 qjpeg_read_scanlines (&cinfo, &scanline, 1);
651 // Convert the image to BGRA
652 switch (cinfo.output_components)
656 buffer_ptr = &image_buffer[image_width * line * 4];
657 for (ind = 0; ind < image_width * 3; ind += 3, buffer_ptr += 4)
659 buffer_ptr[2] = scanline[ind];
660 buffer_ptr[1] = scanline[ind + 1];
661 buffer_ptr[0] = scanline[ind + 2];
666 // Greyscale images (default to it, just in case)
669 buffer_ptr = &image_buffer[image_width * line * 4];
670 for (ind = 0; ind < image_width; ind++, buffer_ptr += 4)
672 buffer_ptr[0] = scanline[ind];
673 buffer_ptr[1] = scanline[ind];
674 buffer_ptr[2] = scanline[ind];
683 qjpeg_finish_decompress (&cinfo);
684 qjpeg_destroy_decompress (&cinfo);
692 Mem_Free (image_buffer);
693 qjpeg_destroy_decompress (&cinfo);
699 =================================================================
703 =================================================================
706 #define JPEG_OUTPUT_BUF_SIZE 4096
707 static void JPEG_InitDestination (j_compress_ptr cinfo)
709 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
710 dest->buffer = (unsigned char*)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_IMAGE, JPEG_OUTPUT_BUF_SIZE * sizeof(unsigned char));
711 dest->pub.next_output_byte = dest->buffer;
712 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
715 static jboolean JPEG_EmptyOutputBuffer (j_compress_ptr cinfo)
717 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
719 if (FS_Write (dest->outfile, dest->buffer, JPEG_OUTPUT_BUF_SIZE) != (size_t) JPEG_OUTPUT_BUF_SIZE)
720 longjmp(error_in_jpeg, 1);
722 dest->pub.next_output_byte = dest->buffer;
723 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
727 static void JPEG_TermDestination (j_compress_ptr cinfo)
729 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
730 size_t datacount = JPEG_OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
732 // Write any data remaining in the buffer
734 if (FS_Write (dest->outfile, dest->buffer, datacount) != (fs_offset_t)datacount)
735 longjmp(error_in_jpeg, 1);
738 static void JPEG_FileDest (j_compress_ptr cinfo, qfile_t* outfile)
742 // First time for this JPEG object?
743 if (cinfo->dest == NULL)
744 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
746 dest = (my_dest_ptr)cinfo->dest;
747 dest->pub.init_destination = JPEG_InitDestination;
748 dest->pub.empty_output_buffer = JPEG_EmptyOutputBuffer;
749 dest->pub.term_destination = JPEG_TermDestination;
750 dest->outfile = outfile;
753 static void JPEG_Mem_InitDestination (j_compress_ptr cinfo)
755 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
756 dest->pub.next_output_byte = dest->buffer;
757 dest->pub.free_in_buffer = dest->bufsize;
760 static jboolean JPEG_Mem_EmptyOutputBuffer (j_compress_ptr cinfo)
762 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
763 jpeg_toolarge = true;
764 dest->pub.next_output_byte = dest->buffer;
765 dest->pub.free_in_buffer = dest->bufsize;
769 static void JPEG_Mem_TermDestination (j_compress_ptr cinfo)
771 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
772 dest->bufsize = dest->pub.next_output_byte - dest->buffer;
774 static void JPEG_MemDest (j_compress_ptr cinfo, void* buf, size_t bufsize)
778 // First time for this JPEG object?
779 if (cinfo->dest == NULL)
780 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
782 dest = (my_dest_ptr)cinfo->dest;
783 dest->pub.init_destination = JPEG_Mem_InitDestination;
784 dest->pub.empty_output_buffer = JPEG_Mem_EmptyOutputBuffer;
785 dest->pub.term_destination = JPEG_Mem_TermDestination;
786 dest->outfile = NULL;
788 dest->buffer = (unsigned char *) buf;
789 dest->bufsize = bufsize;
795 JPEG_SaveImage_preflipped
797 Save a preflipped JPEG image to a file
800 qboolean JPEG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
802 struct jpeg_compress_struct cinfo;
803 struct jpeg_error_mgr jerr;
804 unsigned char *scanline;
805 unsigned int offset, linesize;
811 Con_Print("You need the libjpeg library to save JPEG images\n");
816 file = FS_OpenRealFile(filename, "wb", true);
820 if(setjmp(error_in_jpeg))
822 cinfo.err = qjpeg_std_error (&jerr);
823 cinfo.err->error_exit = JPEG_ErrorExit;
825 qjpeg_create_compress (&cinfo);
826 JPEG_FileDest (&cinfo, file);
828 // Set the parameters for compression
829 cinfo.image_width = width;
830 cinfo.image_height = height;
831 cinfo.in_color_space = JCS_RGB;
832 cinfo.input_components = 3;
833 qjpeg_set_defaults (&cinfo);
834 qjpeg_set_quality (&cinfo, (int)(scr_screenshot_jpeg_quality.value * 100), TRUE);
835 qjpeg_simple_progression (&cinfo);
837 // turn off subsampling (to make text look better)
838 cinfo.optimize_coding = 1;
839 cinfo.comp_info[0].h_samp_factor = 1;
840 cinfo.comp_info[0].v_samp_factor = 1;
841 cinfo.comp_info[1].h_samp_factor = 1;
842 cinfo.comp_info[1].v_samp_factor = 1;
843 cinfo.comp_info[2].h_samp_factor = 1;
844 cinfo.comp_info[2].v_samp_factor = 1;
846 qjpeg_start_compress (&cinfo, true);
848 // Compress each scanline
849 linesize = cinfo.image_width * 3;
850 offset = linesize * (cinfo.image_height - 1);
851 while (cinfo.next_scanline < cinfo.image_height)
853 scanline = &data[offset - cinfo.next_scanline * linesize];
855 qjpeg_write_scanlines (&cinfo, &scanline, 1);
858 qjpeg_finish_compress (&cinfo);
859 qjpeg_destroy_compress (&cinfo);
865 qjpeg_destroy_compress (&cinfo);
870 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)
872 unsigned char *scanline;
873 unsigned int linesize;
875 jpeg_toolarge = false;
876 JPEG_MemDest (cinfo, jpegbuf, jpegsize);
878 // Set the parameters for compression
879 cinfo->image_width = width;
880 cinfo->image_height = height;
881 cinfo->in_color_space = JCS_RGB;
882 cinfo->input_components = 3;
883 qjpeg_set_defaults (cinfo);
884 qjpeg_set_quality (cinfo, quality, FALSE);
886 cinfo->comp_info[0].h_samp_factor = 2;
887 cinfo->comp_info[0].v_samp_factor = 2;
888 cinfo->comp_info[1].h_samp_factor = 1;
889 cinfo->comp_info[1].v_samp_factor = 1;
890 cinfo->comp_info[2].h_samp_factor = 1;
891 cinfo->comp_info[2].v_samp_factor = 1;
892 cinfo->optimize_coding = 1;
894 qjpeg_start_compress (cinfo, true);
896 // Compress each scanline
897 linesize = width * 3;
898 while (cinfo->next_scanline < cinfo->image_height)
900 scanline = &data[cinfo->next_scanline * linesize];
902 qjpeg_write_scanlines (cinfo, &scanline, 1);
905 qjpeg_finish_compress (cinfo);
910 return ((my_dest_ptr) cinfo->dest)->bufsize;
913 size_t JPEG_SaveImage_to_Buffer (char *jpegbuf, size_t jpegsize, int width, int height, unsigned char *data)
915 struct jpeg_compress_struct cinfo;
916 struct jpeg_error_mgr jerr;
925 Con_Print("You need the libjpeg library to save JPEG images\n");
929 if(setjmp(error_in_jpeg))
931 cinfo.err = qjpeg_std_error (&jerr);
932 cinfo.err->error_exit = JPEG_ErrorExit;
934 qjpeg_create_compress (&cinfo);
937 // used to get the formula below
943 img = Mem_Alloc(tempmempool, width * height * 3);
944 for(i = 0; i < width * height * 3; ++i)
945 img[i] = rand() & 0xFF;
947 for(i = 0; i <= 100; ++i)
949 Con_Printf("! %d %d %d %d\n", width, height, i, (int) JPEG_try_SaveImage_to_Buffer(&cinfo, buf, sizeof(buf), i, width, height, img));
956 //quality_guess = (100 * jpegsize - 41000) / (width*height) + 2; // fits random data
957 quality_guess = (256 * jpegsize - 81920) / (width*height) - 8; // fits Nexuiz's map pictures
959 quality_guess = bound(0, quality_guess, 100);
960 quality = bound(0, quality_guess + sv_writepicture_quality.integer, 100); // assume it can do 10 failed attempts
962 while(!(result = JPEG_try_SaveImage_to_Buffer(&cinfo, jpegbuf, jpegsize, quality, width, height, data)))
967 Con_Printf("couldn't write image at all, probably too big\n");
971 qjpeg_destroy_compress (&cinfo);
972 Con_DPrintf("JPEG_SaveImage_to_Buffer: guessed quality/size %d/%d, actually got %d/%d\n", quality_guess, (int)jpegsize, quality, (int)result);
977 qjpeg_destroy_compress (&cinfo);
981 typedef struct CompressedImageCacheItem
983 char imagename[MAX_QPATH];
986 size_t compressed_size;
987 struct CompressedImageCacheItem *next;
989 CompressedImageCacheItem;
990 #define COMPRESSEDIMAGECACHE_SIZE 4096
991 static CompressedImageCacheItem *CompressedImageCache[COMPRESSEDIMAGECACHE_SIZE];
993 static void CompressedImageCache_Add(const char *imagename, size_t maxsize, void *compressed, size_t compressed_size)
995 const char *hashkey = va("%s:%d", imagename, (int) maxsize);
996 int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
997 CompressedImageCacheItem *i;
999 if(strlen(imagename) >= MAX_QPATH)
1000 return; // can't add this
1002 i = (CompressedImageCacheItem*) Z_Malloc(sizeof(CompressedImageCacheItem));
1003 strlcpy(i->imagename, imagename, sizeof(i->imagename));
1004 i->maxsize = maxsize;
1005 i->compressed = compressed;
1006 i->compressed_size = compressed_size;
1007 i->next = CompressedImageCache[hashindex];
1008 CompressedImageCache[hashindex] = i;
1011 static CompressedImageCacheItem *CompressedImageCache_Find(const char *imagename, size_t maxsize)
1013 const char *hashkey = va("%s:%d", imagename, (int) maxsize);
1014 int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
1015 CompressedImageCacheItem *i = CompressedImageCache[hashindex];
1019 if(i->maxsize == maxsize)
1020 if(!strcmp(i->imagename, imagename))
1027 qboolean Image_Compress(const char *imagename, size_t maxsize, void **buf, size_t *size)
1029 unsigned char *imagedata, *newimagedata;
1031 int components[3] = {2, 1, 0};
1032 CompressedImageCacheItem *i;
1034 JPEG_OpenLibrary (); // for now; LH had the idea of replacing this by a better format
1036 // No DLL = no JPEGs
1039 Con_Print("You need the libjpeg library to save JPEG images\n");
1043 i = CompressedImageCache_Find(imagename, maxsize);
1046 *size = i->compressed_size;
1047 *buf = i->compressed;
1051 imagedata = loadimagepixelsbgra(imagename, true, false, false);
1055 // find an appropriate size for somewhat okay compression
1057 maxPixelCount = 32 * 32;
1058 else if(maxsize <= 1024)
1059 maxPixelCount = 64 * 64;
1060 else if(maxsize <= 4096)
1061 maxPixelCount = 128 * 128;
1063 maxPixelCount = 256 * 256;
1065 while(image_width * image_height > maxPixelCount)
1068 Image_MipReduce32(imagedata, imagedata, &image_width, &image_height, &one, image_width/2, image_height/2, 1);
1071 newimagedata = (unsigned char *) Mem_Alloc(tempmempool, image_width * image_height * 3);
1073 // convert the image from BGRA to RGB
1074 Image_CopyMux(newimagedata, imagedata, image_width, image_height, false, false, false, 3, 4, components);
1075 Mem_Free(imagedata);
1077 // try to compress it to JPEG
1078 *buf = Z_Malloc(maxsize);
1079 *size = JPEG_SaveImage_to_Buffer((char *) *buf, maxsize, image_width, image_height, newimagedata);
1080 Mem_Free(newimagedata);
1086 Con_Printf("could not compress image %s to %d bytes\n", imagename, (int)maxsize);
1088 // also cache failures!
1091 // store it in the cache
1092 CompressedImageCache_Add(imagename, maxsize, *buf, *size);
1093 return (*buf != NULL);