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
28 #include "image_png.h"
30 cvar_t sv_writepicture_quality = {CVAR_SAVE, "sv_writepicture_quality", "10", "WritePicture quality offset (higher means better quality, but slower)"};
32 // jboolean is unsigned char instead of int on Win32
34 typedef unsigned char jboolean;
39 #ifdef LINK_TO_LIBJPEG
41 #define qjpeg_create_compress jpeg_create_compress
42 #define qjpeg_create_decompress jpeg_create_decompress
43 #define qjpeg_destroy_compress jpeg_destroy_compress
44 #define qjpeg_destroy_decompress jpeg_destroy_decompress
45 #define qjpeg_finish_compress jpeg_finish_compress
46 #define qjpeg_finish_decompress jpeg_finish_decompress
47 #define qjpeg_resync_to_restart jpeg_resync_to_restart
48 #define qjpeg_read_header jpeg_read_header
49 #define qjpeg_read_scanlines jpeg_read_scanlines
50 #define qjpeg_set_defaults jpeg_set_defaults
51 #define qjpeg_set_quality jpeg_set_quality
52 #define qjpeg_start_compress jpeg_start_compress
53 #define qjpeg_start_decompress jpeg_start_decompress
54 #define qjpeg_std_error jpeg_std_error
55 #define qjpeg_write_scanlines jpeg_write_scanlines
56 #define qjpeg_simple_progression jpeg_simple_progression
60 =================================================================
62 Minimal set of definitions from the JPEG lib
64 WARNING: for a matter of simplicity, several pointer types are
65 casted to "void*", and most enumerated values are not included
67 =================================================================
70 typedef void *j_common_ptr;
71 typedef struct jpeg_compress_struct *j_compress_ptr;
72 typedef struct jpeg_decompress_struct *j_decompress_ptr;
74 #define JPEG_LIB_VERSION 62 // Version 6b
85 typedef enum {JPEG_DUMMY1} J_DCT_METHOD;
86 typedef enum {JPEG_DUMMY2} J_DITHER_MODE;
87 typedef unsigned int JDIMENSION;
89 #define JPOOL_PERMANENT 0 // lasts until master record is destroyed
90 #define JPOOL_IMAGE 1 // lasts until done with image/datastream
92 #define JPEG_EOI 0xD9 // EOI marker code
94 #define JMSG_STR_PARM_MAX 80
97 #define NUM_QUANT_TBLS 4
98 #define NUM_HUFF_TBLS 4
99 #define NUM_ARITH_TBLS 16
100 #define MAX_COMPS_IN_SCAN 4
101 #define C_MAX_BLOCKS_IN_MCU 10
102 #define D_MAX_BLOCKS_IN_MCU 10
104 struct jpeg_memory_mgr
106 void* (*alloc_small) (j_common_ptr cinfo, int pool_id, size_t sizeofobject);
107 void (*_reserve_space_for_alloc_large) (void *dummy, ...);
108 void (*_reserve_space_for_alloc_sarray) (void *dummy, ...);
109 void (*_reserve_space_for_alloc_barray) (void *dummy, ...);
110 void (*_reserve_space_for_request_virt_sarray) (void *dummy, ...);
111 void (*_reserve_space_for_request_virt_barray) (void *dummy, ...);
112 void (*_reserve_space_for_realize_virt_arrays) (void *dummy, ...);
113 void (*_reserve_space_for_access_virt_sarray) (void *dummy, ...);
114 void (*_reserve_space_for_access_virt_barray) (void *dummy, ...);
115 void (*_reserve_space_for_free_pool) (void *dummy, ...);
116 void (*_reserve_space_for_self_destruct) (void *dummy, ...);
118 long max_memory_to_use;
119 long max_alloc_chunk;
122 struct jpeg_error_mgr
124 void (*error_exit) (j_common_ptr cinfo);
125 void (*emit_message) (j_common_ptr cinfo, int msg_level);
126 void (*output_message) (j_common_ptr cinfo);
127 void (*format_message) (j_common_ptr cinfo, char * buffer);
128 void (*reset_error_mgr) (j_common_ptr cinfo);
132 char s[JMSG_STR_PARM_MAX];
136 const char * const * jpeg_message_table;
137 int last_jpeg_message;
138 const char * const * addon_message_table;
139 int first_addon_message;
140 int last_addon_message;
143 struct jpeg_source_mgr
145 const unsigned char *next_input_byte;
146 size_t bytes_in_buffer;
148 void (*init_source) (j_decompress_ptr cinfo);
149 jboolean (*fill_input_buffer) (j_decompress_ptr cinfo);
150 void (*skip_input_data) (j_decompress_ptr cinfo, long num_bytes);
151 jboolean (*resync_to_restart) (j_decompress_ptr cinfo, int desired);
152 void (*term_source) (j_decompress_ptr cinfo);
156 /* These values are fixed over the whole image. */
157 /* For compression, they must be supplied by parameter setup; */
158 /* for decompression, they are read from the SOF marker. */
159 int component_id; /* identifier for this component (0..255) */
160 int component_index; /* its index in SOF or cinfo->comp_info[] */
161 int h_samp_factor; /* horizontal sampling factor (1..4) */
162 int v_samp_factor; /* vertical sampling factor (1..4) */
163 int quant_tbl_no; /* quantization table selector (0..3) */
164 /* These values may vary between scans. */
165 /* For compression, they must be supplied by parameter setup; */
166 /* for decompression, they are read from the SOS marker. */
167 /* The decompressor output side may not use these variables. */
168 int dc_tbl_no; /* DC entropy table selector (0..3) */
169 int ac_tbl_no; /* AC entropy table selector (0..3) */
171 /* Remaining fields should be treated as private by applications. */
173 /* These values are computed during compression or decompression startup: */
174 /* Component's size in DCT blocks.
175 * Any dummy blocks added to complete an MCU are not counted; therefore
176 * these values do not depend on whether a scan is interleaved or not.
178 JDIMENSION width_in_blocks;
179 JDIMENSION height_in_blocks;
180 /* Size of a DCT block in samples. Always DCTSIZE for compression.
181 * For decompression this is the size of the output from one DCT block,
182 * reflecting any scaling we choose to apply during the IDCT step.
183 * Values of 1,2,4,8 are likely to be supported. Note that different
184 * components may receive different IDCT scalings.
187 /* The downsampled dimensions are the component's actual, unpadded number
188 * of samples at the main buffer (preprocessing/compression interface), thus
189 * downsampled_width = ceil(image_width * Hi/Hmax)
190 * and similarly for height. For decompression, IDCT scaling is included, so
191 * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
193 JDIMENSION downsampled_width; /* actual width in samples */
194 JDIMENSION downsampled_height; /* actual height in samples */
195 /* This flag is used only for decompression. In cases where some of the
196 * components will be ignored (eg grayscale output from YCbCr image),
197 * we can skip most computations for the unused components.
199 jboolean component_needed; /* do we need the value of this component? */
201 /* These values are computed before starting a scan of the component. */
202 /* The decompressor output side may not use these variables. */
203 int MCU_width; /* number of blocks per MCU, horizontally */
204 int MCU_height; /* number of blocks per MCU, vertically */
205 int MCU_blocks; /* MCU_width * MCU_height */
206 int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
207 int last_col_width; /* # of non-dummy blocks across in last MCU */
208 int last_row_height; /* # of non-dummy blocks down in last MCU */
210 /* Saved quantization table for component; NULL if none yet saved.
211 * See jdinput.c comments about the need for this information.
212 * This field is currently used only for decompression.
216 /* Private per-component storage for DCT or IDCT subsystem. */
218 } jpeg_component_info;
220 struct jpeg_decompress_struct
222 struct jpeg_error_mgr *err; // USED
223 struct jpeg_memory_mgr *mem; // USED
227 jboolean is_decompressor;
230 struct jpeg_source_mgr *src; // USED
231 JDIMENSION image_width; // USED
232 JDIMENSION image_height; // USED
235 J_COLOR_SPACE jpeg_color_space;
236 J_COLOR_SPACE out_color_space;
237 unsigned int scale_num, scale_denom;
239 jboolean buffered_image;
240 jboolean raw_data_out;
241 J_DCT_METHOD dct_method;
242 jboolean do_fancy_upsampling;
243 jboolean do_block_smoothing;
244 jboolean quantize_colors;
245 J_DITHER_MODE dither_mode;
246 jboolean two_pass_quantize;
247 int desired_number_of_colors;
248 jboolean enable_1pass_quant;
249 jboolean enable_external_quant;
250 jboolean enable_2pass_quant;
251 JDIMENSION output_width;
253 JDIMENSION output_height; // USED
255 int out_color_components;
257 int output_components; // USED
259 int rec_outbuf_height;
260 int actual_number_of_colors;
263 JDIMENSION output_scanline; // USED
265 int input_scan_number;
266 JDIMENSION input_iMCU_row;
267 int output_scan_number;
268 JDIMENSION output_iMCU_row;
269 int (*coef_bits)[DCTSIZE2];
270 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
271 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
272 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
274 jpeg_component_info *comp_info;
275 jboolean progressive_mode;
277 unsigned char arith_dc_L[NUM_ARITH_TBLS];
278 unsigned char arith_dc_U[NUM_ARITH_TBLS];
279 unsigned char arith_ac_K[NUM_ARITH_TBLS];
280 unsigned int restart_interval;
281 jboolean saw_JFIF_marker;
282 unsigned char JFIF_major_version;
283 unsigned char JFIF_minor_version;
284 unsigned char density_unit;
285 unsigned short X_density;
286 unsigned short Y_density;
287 jboolean saw_Adobe_marker;
288 unsigned char Adobe_transform;
289 jboolean CCIR601_sampling;
291 int max_h_samp_factor;
292 int max_v_samp_factor;
293 int min_DCT_scaled_size;
294 JDIMENSION total_iMCU_rows;
295 void *sample_range_limit;
297 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
298 JDIMENSION MCUs_per_row;
299 JDIMENSION MCU_rows_in_scan;
301 int MCU_membership[D_MAX_BLOCKS_IN_MCU];
318 struct jpeg_compress_struct
320 struct jpeg_error_mgr *err;
321 struct jpeg_memory_mgr *mem;
324 jboolean is_decompressor;
328 JDIMENSION image_width;
329 JDIMENSION image_height;
330 int input_components;
331 J_COLOR_SPACE in_color_space;
336 J_COLOR_SPACE jpeg_color_space;
337 jpeg_component_info *comp_info;
338 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
339 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
340 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
341 unsigned char arith_dc_L[NUM_ARITH_TBLS];
342 unsigned char arith_dc_U[NUM_ARITH_TBLS];
343 unsigned char arith_ac_K[NUM_ARITH_TBLS];
346 const void *scan_info;
347 jboolean raw_data_in;
349 jboolean optimize_coding;
350 jboolean CCIR601_sampling;
351 int smoothing_factor;
352 J_DCT_METHOD dct_method;
354 unsigned int restart_interval;
357 jboolean write_JFIF_header;
358 unsigned char JFIF_major_version;
359 unsigned char JFIF_minor_version;
360 unsigned char density_unit;
361 unsigned short X_density;
362 unsigned short Y_density;
363 jboolean write_Adobe_marker;
364 JDIMENSION next_scanline;
366 jboolean progressive_mode;
367 int max_h_samp_factor;
368 int max_v_samp_factor;
369 JDIMENSION total_iMCU_rows;
371 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
372 JDIMENSION MCUs_per_row;
373 JDIMENSION MCU_rows_in_scan;
375 int MCU_membership[C_MAX_BLOCKS_IN_MCU];
388 int script_space_size;
391 struct jpeg_destination_mgr
393 unsigned char* next_output_byte;
394 size_t free_in_buffer;
396 void (*init_destination) (j_compress_ptr cinfo);
397 jboolean (*empty_output_buffer) (j_compress_ptr cinfo);
398 void (*term_destination) (j_compress_ptr cinfo);
403 =================================================================
405 DarkPlaces definitions
407 =================================================================
410 // Functions exported from libjpeg
411 #define qjpeg_create_compress(cinfo) \
412 qjpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_compress_struct))
413 #define qjpeg_create_decompress(cinfo) \
414 qjpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_decompress_struct))
416 static void (*qjpeg_CreateCompress) (j_compress_ptr cinfo, int version, size_t structsize);
417 static void (*qjpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize);
418 static void (*qjpeg_destroy_compress) (j_compress_ptr cinfo);
419 static void (*qjpeg_destroy_decompress) (j_decompress_ptr cinfo);
420 static void (*qjpeg_finish_compress) (j_compress_ptr cinfo);
421 static jboolean (*qjpeg_finish_decompress) (j_decompress_ptr cinfo);
422 static jboolean (*qjpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired);
423 static int (*qjpeg_read_header) (j_decompress_ptr cinfo, jboolean require_image);
424 static JDIMENSION (*qjpeg_read_scanlines) (j_decompress_ptr cinfo, unsigned char** scanlines, JDIMENSION max_lines);
425 static void (*qjpeg_set_defaults) (j_compress_ptr cinfo);
426 static void (*qjpeg_set_quality) (j_compress_ptr cinfo, int quality, jboolean force_baseline);
427 static jboolean (*qjpeg_start_compress) (j_compress_ptr cinfo, jboolean write_all_tables);
428 static jboolean (*qjpeg_start_decompress) (j_decompress_ptr cinfo);
429 static struct jpeg_error_mgr* (*qjpeg_std_error) (struct jpeg_error_mgr *err);
430 static JDIMENSION (*qjpeg_write_scanlines) (j_compress_ptr cinfo, unsigned char** scanlines, JDIMENSION num_lines);
431 static void (*qjpeg_simple_progression) (j_compress_ptr cinfo);
433 static dllfunction_t jpegfuncs[] =
435 {"jpeg_CreateCompress", (void **) &qjpeg_CreateCompress},
436 {"jpeg_CreateDecompress", (void **) &qjpeg_CreateDecompress},
437 {"jpeg_destroy_compress", (void **) &qjpeg_destroy_compress},
438 {"jpeg_destroy_decompress", (void **) &qjpeg_destroy_decompress},
439 {"jpeg_finish_compress", (void **) &qjpeg_finish_compress},
440 {"jpeg_finish_decompress", (void **) &qjpeg_finish_decompress},
441 {"jpeg_resync_to_restart", (void **) &qjpeg_resync_to_restart},
442 {"jpeg_read_header", (void **) &qjpeg_read_header},
443 {"jpeg_read_scanlines", (void **) &qjpeg_read_scanlines},
444 {"jpeg_set_defaults", (void **) &qjpeg_set_defaults},
445 {"jpeg_set_quality", (void **) &qjpeg_set_quality},
446 {"jpeg_start_compress", (void **) &qjpeg_start_compress},
447 {"jpeg_start_decompress", (void **) &qjpeg_start_decompress},
448 {"jpeg_std_error", (void **) &qjpeg_std_error},
449 {"jpeg_write_scanlines", (void **) &qjpeg_write_scanlines},
450 {"jpeg_simple_progression", (void **) &qjpeg_simple_progression},
454 // Handle for JPEG DLL
455 dllhandle_t jpeg_dll = NULL;
456 qboolean jpeg_tried_loading = 0;
459 static unsigned char jpeg_eoi_marker [2] = {0xFF, JPEG_EOI};
460 static jmp_buf error_in_jpeg;
461 static qboolean jpeg_toolarge;
463 // Our own output manager for JPEG compression
466 struct jpeg_destination_mgr pub;
469 unsigned char* buffer;
470 size_t bufsize; // used if outfile is NULL
471 } my_destination_mgr;
472 typedef my_destination_mgr* my_dest_ptr;
476 =================================================================
480 =================================================================
487 Try to load the JPEG DLL
490 qboolean JPEG_OpenLibrary (void)
492 #ifdef LINK_TO_LIBJPEG
495 const char* dllnames [] =
499 #elif defined(MACOSX)
512 if (jpeg_tried_loading) // only try once
515 jpeg_tried_loading = true;
518 return Sys_LoadLibrary (dllnames, &jpeg_dll, jpegfuncs);
530 void JPEG_CloseLibrary (void)
532 #ifndef LINK_TO_LIBJPEG
533 Sys_UnloadLibrary (&jpeg_dll);
534 jpeg_tried_loading = false; // allow retry
540 =================================================================
544 =================================================================
547 static void JPEG_Noop (j_decompress_ptr cinfo) {}
549 static jboolean JPEG_FillInputBuffer (j_decompress_ptr cinfo)
551 // Insert a fake EOI marker
552 cinfo->src->next_input_byte = jpeg_eoi_marker;
553 cinfo->src->bytes_in_buffer = 2;
558 static void JPEG_SkipInputData (j_decompress_ptr cinfo, long num_bytes)
560 if (cinfo->src->bytes_in_buffer <= (unsigned long)num_bytes)
562 cinfo->src->bytes_in_buffer = 0;
566 cinfo->src->next_input_byte += num_bytes;
567 cinfo->src->bytes_in_buffer -= num_bytes;
570 static void JPEG_MemSrc (j_decompress_ptr cinfo, const unsigned char *buffer, size_t filesize)
572 cinfo->src = (struct jpeg_source_mgr *)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
574 cinfo->src->next_input_byte = buffer;
575 cinfo->src->bytes_in_buffer = filesize;
577 cinfo->src->init_source = JPEG_Noop;
578 cinfo->src->fill_input_buffer = JPEG_FillInputBuffer;
579 cinfo->src->skip_input_data = JPEG_SkipInputData;
580 cinfo->src->resync_to_restart = qjpeg_resync_to_restart; // use the default method
581 cinfo->src->term_source = JPEG_Noop;
584 static void JPEG_ErrorExit (j_common_ptr cinfo)
586 ((struct jpeg_decompress_struct*)cinfo)->err->output_message (cinfo);
587 longjmp(error_in_jpeg, 1);
595 Load a JPEG image into a BGRA buffer
598 unsigned char* JPEG_LoadImage_BGRA (const unsigned char *f, int filesize)
600 struct jpeg_decompress_struct cinfo;
601 struct jpeg_error_mgr jerr;
602 unsigned char *image_buffer = NULL, *scanline = NULL;
609 cinfo.err = qjpeg_std_error (&jerr);
610 qjpeg_create_decompress (&cinfo);
611 if(setjmp(error_in_jpeg))
613 cinfo.err = qjpeg_std_error (&jerr);
614 cinfo.err->error_exit = JPEG_ErrorExit;
615 JPEG_MemSrc (&cinfo, f, filesize);
616 qjpeg_read_header (&cinfo, TRUE);
617 qjpeg_start_decompress (&cinfo);
619 image_width = cinfo.image_width;
620 image_height = cinfo.image_height;
622 if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
624 Con_Printf("JPEG_LoadImage: invalid image size %ix%i\n", image_width, image_height);
628 image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
629 scanline = (unsigned char *)Mem_Alloc(tempmempool, image_width * cinfo.output_components);
630 if (!image_buffer || !scanline)
633 Mem_Free (image_buffer);
637 Con_Printf("JPEG_LoadImage: not enough memory for %i by %i image\n", image_width, image_height);
638 qjpeg_finish_decompress (&cinfo);
639 qjpeg_destroy_decompress (&cinfo);
643 // Decompress the image, line by line
645 while (cinfo.output_scanline < cinfo.output_height)
647 unsigned char *buffer_ptr;
650 qjpeg_read_scanlines (&cinfo, &scanline, 1);
652 // Convert the image to BGRA
653 switch (cinfo.output_components)
657 buffer_ptr = &image_buffer[image_width * line * 4];
658 for (ind = 0; ind < image_width * 3; ind += 3, buffer_ptr += 4)
660 buffer_ptr[2] = scanline[ind];
661 buffer_ptr[1] = scanline[ind + 1];
662 buffer_ptr[0] = scanline[ind + 2];
667 // Greyscale images (default to it, just in case)
670 buffer_ptr = &image_buffer[image_width * line * 4];
671 for (ind = 0; ind < image_width; ind++, buffer_ptr += 4)
673 buffer_ptr[0] = scanline[ind];
674 buffer_ptr[1] = scanline[ind];
675 buffer_ptr[2] = scanline[ind];
684 qjpeg_finish_decompress (&cinfo);
685 qjpeg_destroy_decompress (&cinfo);
693 Mem_Free (image_buffer);
694 qjpeg_destroy_decompress (&cinfo);
700 =================================================================
704 =================================================================
707 #define JPEG_OUTPUT_BUF_SIZE 4096
708 static void JPEG_InitDestination (j_compress_ptr cinfo)
710 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
711 dest->buffer = (unsigned char*)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_IMAGE, JPEG_OUTPUT_BUF_SIZE * sizeof(unsigned char));
712 dest->pub.next_output_byte = dest->buffer;
713 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
716 static jboolean JPEG_EmptyOutputBuffer (j_compress_ptr cinfo)
718 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
720 if (FS_Write (dest->outfile, dest->buffer, JPEG_OUTPUT_BUF_SIZE) != (size_t) JPEG_OUTPUT_BUF_SIZE)
721 longjmp(error_in_jpeg, 1);
723 dest->pub.next_output_byte = dest->buffer;
724 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
728 static void JPEG_TermDestination (j_compress_ptr cinfo)
730 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
731 size_t datacount = JPEG_OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
733 // Write any data remaining in the buffer
735 if (FS_Write (dest->outfile, dest->buffer, datacount) != (fs_offset_t)datacount)
736 longjmp(error_in_jpeg, 1);
739 static void JPEG_FileDest (j_compress_ptr cinfo, qfile_t* outfile)
743 // First time for this JPEG object?
744 if (cinfo->dest == NULL)
745 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
747 dest = (my_dest_ptr)cinfo->dest;
748 dest->pub.init_destination = JPEG_InitDestination;
749 dest->pub.empty_output_buffer = JPEG_EmptyOutputBuffer;
750 dest->pub.term_destination = JPEG_TermDestination;
751 dest->outfile = outfile;
754 static void JPEG_Mem_InitDestination (j_compress_ptr cinfo)
756 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
757 dest->pub.next_output_byte = dest->buffer;
758 dest->pub.free_in_buffer = dest->bufsize;
761 static jboolean JPEG_Mem_EmptyOutputBuffer (j_compress_ptr cinfo)
763 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
764 jpeg_toolarge = true;
765 dest->pub.next_output_byte = dest->buffer;
766 dest->pub.free_in_buffer = dest->bufsize;
770 static void JPEG_Mem_TermDestination (j_compress_ptr cinfo)
772 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
773 dest->bufsize = dest->pub.next_output_byte - dest->buffer;
775 static void JPEG_MemDest (j_compress_ptr cinfo, void* buf, size_t bufsize)
779 // First time for this JPEG object?
780 if (cinfo->dest == NULL)
781 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
783 dest = (my_dest_ptr)cinfo->dest;
784 dest->pub.init_destination = JPEG_Mem_InitDestination;
785 dest->pub.empty_output_buffer = JPEG_Mem_EmptyOutputBuffer;
786 dest->pub.term_destination = JPEG_Mem_TermDestination;
787 dest->outfile = NULL;
789 dest->buffer = (unsigned char *) buf;
790 dest->bufsize = bufsize;
796 JPEG_SaveImage_preflipped
798 Save a preflipped JPEG image to a file
801 qboolean JPEG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
803 struct jpeg_compress_struct cinfo;
804 struct jpeg_error_mgr jerr;
805 unsigned char *scanline;
806 unsigned int offset, linesize;
812 Con_Print("You need the libjpeg library to save JPEG images\n");
817 file = FS_OpenRealFile(filename, "wb", true);
821 if(setjmp(error_in_jpeg))
823 cinfo.err = qjpeg_std_error (&jerr);
824 cinfo.err->error_exit = JPEG_ErrorExit;
826 qjpeg_create_compress (&cinfo);
827 JPEG_FileDest (&cinfo, file);
829 // Set the parameters for compression
830 cinfo.image_width = width;
831 cinfo.image_height = height;
832 cinfo.in_color_space = JCS_RGB;
833 cinfo.input_components = 3;
834 qjpeg_set_defaults (&cinfo);
835 qjpeg_set_quality (&cinfo, (int)(scr_screenshot_jpeg_quality.value * 100), TRUE);
836 qjpeg_simple_progression (&cinfo);
838 // turn off subsampling (to make text look better)
839 cinfo.optimize_coding = 1;
840 cinfo.comp_info[0].h_samp_factor = 1;
841 cinfo.comp_info[0].v_samp_factor = 1;
842 cinfo.comp_info[1].h_samp_factor = 1;
843 cinfo.comp_info[1].v_samp_factor = 1;
844 cinfo.comp_info[2].h_samp_factor = 1;
845 cinfo.comp_info[2].v_samp_factor = 1;
847 qjpeg_start_compress (&cinfo, true);
849 // Compress each scanline
850 linesize = cinfo.image_width * 3;
851 offset = linesize * (cinfo.image_height - 1);
852 while (cinfo.next_scanline < cinfo.image_height)
854 scanline = &data[offset - cinfo.next_scanline * linesize];
856 qjpeg_write_scanlines (&cinfo, &scanline, 1);
859 qjpeg_finish_compress (&cinfo);
860 qjpeg_destroy_compress (&cinfo);
866 qjpeg_destroy_compress (&cinfo);
871 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)
873 unsigned char *scanline;
874 unsigned int linesize;
876 jpeg_toolarge = false;
877 JPEG_MemDest (cinfo, jpegbuf, jpegsize);
879 // Set the parameters for compression
880 cinfo->image_width = width;
881 cinfo->image_height = height;
882 cinfo->in_color_space = JCS_RGB;
883 cinfo->input_components = 3;
884 qjpeg_set_defaults (cinfo);
885 qjpeg_set_quality (cinfo, quality, FALSE);
887 cinfo->comp_info[0].h_samp_factor = 2;
888 cinfo->comp_info[0].v_samp_factor = 2;
889 cinfo->comp_info[1].h_samp_factor = 1;
890 cinfo->comp_info[1].v_samp_factor = 1;
891 cinfo->comp_info[2].h_samp_factor = 1;
892 cinfo->comp_info[2].v_samp_factor = 1;
893 cinfo->optimize_coding = 1;
895 qjpeg_start_compress (cinfo, true);
897 // Compress each scanline
898 linesize = width * 3;
899 while (cinfo->next_scanline < cinfo->image_height)
901 scanline = &data[cinfo->next_scanline * linesize];
903 qjpeg_write_scanlines (cinfo, &scanline, 1);
906 qjpeg_finish_compress (cinfo);
911 return ((my_dest_ptr) cinfo->dest)->bufsize;
914 size_t JPEG_SaveImage_to_Buffer (char *jpegbuf, size_t jpegsize, int width, int height, unsigned char *data)
916 struct jpeg_compress_struct cinfo;
917 struct jpeg_error_mgr jerr;
926 Con_Print("You need the libjpeg library to save JPEG images\n");
930 if(setjmp(error_in_jpeg))
932 cinfo.err = qjpeg_std_error (&jerr);
933 cinfo.err->error_exit = JPEG_ErrorExit;
935 qjpeg_create_compress (&cinfo);
938 // used to get the formula below
944 img = Mem_Alloc(tempmempool, width * height * 3);
945 for(i = 0; i < width * height * 3; ++i)
946 img[i] = rand() & 0xFF;
948 for(i = 0; i <= 100; ++i)
950 Con_Printf("! %d %d %d %d\n", width, height, i, (int) JPEG_try_SaveImage_to_Buffer(&cinfo, buf, sizeof(buf), i, width, height, img));
957 //quality_guess = (100 * jpegsize - 41000) / (width*height) + 2; // fits random data
958 quality_guess = (256 * jpegsize - 81920) / (width*height) - 8; // fits Nexuiz's map pictures
960 quality_guess = bound(0, quality_guess, 100);
961 quality = bound(0, quality_guess + sv_writepicture_quality.integer, 100); // assume it can do 10 failed attempts
963 while(!(result = JPEG_try_SaveImage_to_Buffer(&cinfo, jpegbuf, jpegsize, quality, width, height, data)))
968 Con_Printf("couldn't write image at all, probably too big\n");
972 qjpeg_destroy_compress (&cinfo);
973 Con_DPrintf("JPEG_SaveImage_to_Buffer: guessed quality/size %d/%d, actually got %d/%d\n", quality_guess, (int)jpegsize, quality, (int)result);
978 qjpeg_destroy_compress (&cinfo);
982 typedef struct CompressedImageCacheItem
984 char imagename[MAX_QPATH];
987 size_t compressed_size;
988 struct CompressedImageCacheItem *next;
990 CompressedImageCacheItem;
991 #define COMPRESSEDIMAGECACHE_SIZE 4096
992 static CompressedImageCacheItem *CompressedImageCache[COMPRESSEDIMAGECACHE_SIZE];
994 static void CompressedImageCache_Add(const char *imagename, size_t maxsize, void *compressed, size_t compressed_size)
996 const char *hashkey = va("%s:%d", imagename, (int) maxsize);
997 int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
998 CompressedImageCacheItem *i;
1000 if(strlen(imagename) >= MAX_QPATH)
1001 return; // can't add this
1003 i = (CompressedImageCacheItem*) Z_Malloc(sizeof(CompressedImageCacheItem));
1004 strlcpy(i->imagename, imagename, sizeof(i->imagename));
1005 i->maxsize = maxsize;
1006 i->compressed = compressed;
1007 i->compressed_size = compressed_size;
1008 i->next = CompressedImageCache[hashindex];
1009 CompressedImageCache[hashindex] = i;
1012 static CompressedImageCacheItem *CompressedImageCache_Find(const char *imagename, size_t maxsize)
1014 const char *hashkey = va("%s:%d", imagename, (int) maxsize);
1015 int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
1016 CompressedImageCacheItem *i = CompressedImageCache[hashindex];
1020 if(i->maxsize == maxsize)
1021 if(!strcmp(i->imagename, imagename))
1028 qboolean Image_Compress(const char *imagename, size_t maxsize, void **buf, size_t *size)
1030 unsigned char *imagedata, *newimagedata;
1032 int components[3] = {2, 1, 0};
1033 CompressedImageCacheItem *i;
1035 JPEG_OpenLibrary (); // for now; LH had the idea of replacing this by a better format
1036 PNG_OpenLibrary (); // for loading
1038 // No DLL = no JPEGs
1041 Con_Print("You need the libjpeg library to save JPEG images\n");
1045 i = CompressedImageCache_Find(imagename, maxsize);
1048 *size = i->compressed_size;
1049 *buf = i->compressed;
1053 imagedata = loadimagepixelsbgra(imagename, true, false, false);
1057 // find an appropriate size for somewhat okay compression
1059 maxPixelCount = 32 * 32;
1060 else if(maxsize <= 1024)
1061 maxPixelCount = 64 * 64;
1062 else if(maxsize <= 4096)
1063 maxPixelCount = 128 * 128;
1065 maxPixelCount = 256 * 256;
1067 while(image_width * image_height > maxPixelCount)
1070 Image_MipReduce32(imagedata, imagedata, &image_width, &image_height, &one, image_width/2, image_height/2, 1);
1073 newimagedata = (unsigned char *) Mem_Alloc(tempmempool, image_width * image_height * 3);
1075 // convert the image from BGRA to RGB
1076 Image_CopyMux(newimagedata, imagedata, image_width, image_height, false, false, false, 3, 4, components);
1077 Mem_Free(imagedata);
1079 // try to compress it to JPEG
1080 *buf = Z_Malloc(maxsize);
1081 *size = JPEG_SaveImage_to_Buffer((char *) *buf, maxsize, image_width, image_height, newimagedata);
1082 Mem_Free(newimagedata);
1088 Con_Printf("could not compress image %s to %d bytes\n", imagename, (int)maxsize);
1090 // also cache failures!
1093 // store it in the cache
1094 CompressedImageCache_Add(imagename, maxsize, *buf, *size);
1095 return (*buf != NULL);