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
25 #include "darkplaces.h"
26 #include "cl_screen.h"
29 #include "image_png.h"
31 extern cvar_t sv_writepicture_quality;
32 cvar_t r_texture_jpeg_fastpicmip = {CF_CLIENT | CF_ARCHIVE, "r_texture_jpeg_fastpicmip", "1", "perform gl_picmip during decompression for JPEG files (faster)"};
34 // jboolean is unsigned char instead of int on Win32
36 typedef unsigned char jboolean;
41 #ifdef LINK_TO_LIBJPEG
43 #define qjpeg_create_compress jpeg_create_compress
44 #define qjpeg_create_decompress jpeg_create_decompress
45 #define qjpeg_destroy_compress jpeg_destroy_compress
46 #define qjpeg_destroy_decompress jpeg_destroy_decompress
47 #define qjpeg_finish_compress jpeg_finish_compress
48 #define qjpeg_finish_decompress jpeg_finish_decompress
49 #define qjpeg_resync_to_restart jpeg_resync_to_restart
50 #define qjpeg_read_header jpeg_read_header
51 #define qjpeg_read_scanlines jpeg_read_scanlines
52 #define qjpeg_set_defaults jpeg_set_defaults
53 #define qjpeg_set_quality jpeg_set_quality
54 #define qjpeg_start_compress jpeg_start_compress
55 #define qjpeg_start_decompress jpeg_start_decompress
56 #define qjpeg_std_error jpeg_std_error
57 #define qjpeg_write_scanlines jpeg_write_scanlines
58 #define qjpeg_simple_progression jpeg_simple_progression
62 =================================================================
64 Minimal set of definitions from the JPEG lib
66 WARNING: for a matter of simplicity, several pointer types are
67 casted to "void*", and most enumerated values are not included
69 =================================================================
72 typedef void *j_common_ptr;
73 typedef struct jpeg_compress_struct *j_compress_ptr;
74 typedef struct jpeg_decompress_struct *j_decompress_ptr;
76 #define JPEG_LIB_VERSION 62 // Version 6b
87 typedef enum {JPEG_DUMMY1} J_DCT_METHOD;
88 typedef enum {JPEG_DUMMY2} J_DITHER_MODE;
89 typedef unsigned int JDIMENSION;
91 #define JPOOL_PERMANENT 0 // lasts until master record is destroyed
92 #define JPOOL_IMAGE 1 // lasts until done with image/datastream
94 #define JPEG_EOI 0xD9 // EOI marker code
96 #define JMSG_STR_PARM_MAX 80
99 #define NUM_QUANT_TBLS 4
100 #define NUM_HUFF_TBLS 4
101 #define NUM_ARITH_TBLS 16
102 #define MAX_COMPS_IN_SCAN 4
103 #define C_MAX_BLOCKS_IN_MCU 10
104 #define D_MAX_BLOCKS_IN_MCU 10
106 struct jpeg_memory_mgr
108 void* (*alloc_small) (j_common_ptr cinfo, int pool_id, size_t sizeofobject);
109 void (*_reserve_space_for_alloc_large) (void *dummy, ...);
110 void (*_reserve_space_for_alloc_sarray) (void *dummy, ...);
111 void (*_reserve_space_for_alloc_barray) (void *dummy, ...);
112 void (*_reserve_space_for_request_virt_sarray) (void *dummy, ...);
113 void (*_reserve_space_for_request_virt_barray) (void *dummy, ...);
114 void (*_reserve_space_for_realize_virt_arrays) (void *dummy, ...);
115 void (*_reserve_space_for_access_virt_sarray) (void *dummy, ...);
116 void (*_reserve_space_for_access_virt_barray) (void *dummy, ...);
117 void (*_reserve_space_for_free_pool) (void *dummy, ...);
118 void (*_reserve_space_for_self_destruct) (void *dummy, ...);
120 long max_memory_to_use;
121 long max_alloc_chunk;
124 struct jpeg_error_mgr
126 void (*error_exit) (j_common_ptr cinfo);
127 void (*emit_message) (j_common_ptr cinfo, int msg_level);
128 void (*output_message) (j_common_ptr cinfo);
129 void (*format_message) (j_common_ptr cinfo, char * buffer);
130 void (*reset_error_mgr) (j_common_ptr cinfo);
134 char s[JMSG_STR_PARM_MAX];
138 const char * const * jpeg_message_table;
139 int last_jpeg_message;
140 const char * const * addon_message_table;
141 int first_addon_message;
142 int last_addon_message;
145 struct jpeg_source_mgr
147 const unsigned char *next_input_byte;
148 size_t bytes_in_buffer;
150 void (*init_source) (j_decompress_ptr cinfo);
151 jboolean (*fill_input_buffer) (j_decompress_ptr cinfo);
152 void (*skip_input_data) (j_decompress_ptr cinfo, long num_bytes);
153 jboolean (*resync_to_restart) (j_decompress_ptr cinfo, int desired);
154 void (*term_source) (j_decompress_ptr cinfo);
158 /* These values are fixed over the whole image. */
159 /* For compression, they must be supplied by parameter setup; */
160 /* for decompression, they are read from the SOF marker. */
161 int component_id; /* identifier for this component (0..255) */
162 int component_index; /* its index in SOF or cinfo->comp_info[] */
163 int h_samp_factor; /* horizontal sampling factor (1..4) */
164 int v_samp_factor; /* vertical sampling factor (1..4) */
165 int quant_tbl_no; /* quantization table selector (0..3) */
166 /* These values may vary between scans. */
167 /* For compression, they must be supplied by parameter setup; */
168 /* for decompression, they are read from the SOS marker. */
169 /* The decompressor output side may not use these variables. */
170 int dc_tbl_no; /* DC entropy table selector (0..3) */
171 int ac_tbl_no; /* AC entropy table selector (0..3) */
173 /* Remaining fields should be treated as private by applications. */
175 /* These values are computed during compression or decompression startup: */
176 /* Component's size in DCT blocks.
177 * Any dummy blocks added to complete an MCU are not counted; therefore
178 * these values do not depend on whether a scan is interleaved or not.
180 JDIMENSION width_in_blocks;
181 JDIMENSION height_in_blocks;
182 /* Size of a DCT block in samples. Always DCTSIZE for compression.
183 * For decompression this is the size of the output from one DCT block,
184 * reflecting any scaling we choose to apply during the IDCT step.
185 * Values of 1,2,4,8 are likely to be supported. Note that different
186 * components may receive different IDCT scalings.
189 /* The downsampled dimensions are the component's actual, unpadded number
190 * of samples at the main buffer (preprocessing/compression interface), thus
191 * downsampled_width = ceil(image_width * Hi/Hmax)
192 * and similarly for height. For decompression, IDCT scaling is included, so
193 * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
195 JDIMENSION downsampled_width; /* actual width in samples */
196 JDIMENSION downsampled_height; /* actual height in samples */
197 /* This flag is used only for decompression. In cases where some of the
198 * components will be ignored (eg grayscale output from YCbCr image),
199 * we can skip most computations for the unused components.
201 jboolean component_needed; /* do we need the value of this component? */
203 /* These values are computed before starting a scan of the component. */
204 /* The decompressor output side may not use these variables. */
205 int MCU_width; /* number of blocks per MCU, horizontally */
206 int MCU_height; /* number of blocks per MCU, vertically */
207 int MCU_blocks; /* MCU_width * MCU_height */
208 int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
209 int last_col_width; /* # of non-dummy blocks across in last MCU */
210 int last_row_height; /* # of non-dummy blocks down in last MCU */
212 /* Saved quantization table for component; NULL if none yet saved.
213 * See jdinput.c comments about the need for this information.
214 * This field is currently used only for decompression.
218 /* Private per-component storage for DCT or IDCT subsystem. */
220 } jpeg_component_info;
222 struct jpeg_decompress_struct
224 struct jpeg_error_mgr *err; // USED
225 struct jpeg_memory_mgr *mem; // USED
229 jboolean is_decompressor;
232 struct jpeg_source_mgr *src; // USED
233 JDIMENSION image_width; // USED
234 JDIMENSION image_height; // USED
237 J_COLOR_SPACE jpeg_color_space;
238 J_COLOR_SPACE out_color_space;
239 unsigned int scale_num, scale_denom;
241 jboolean buffered_image;
242 jboolean raw_data_out;
243 J_DCT_METHOD dct_method;
244 jboolean do_fancy_upsampling;
245 jboolean do_block_smoothing;
246 jboolean quantize_colors;
247 J_DITHER_MODE dither_mode;
248 jboolean two_pass_quantize;
249 int desired_number_of_colors;
250 jboolean enable_1pass_quant;
251 jboolean enable_external_quant;
252 jboolean enable_2pass_quant;
253 JDIMENSION output_width;
255 JDIMENSION output_height; // USED
257 int out_color_components;
259 int output_components; // USED
261 int rec_outbuf_height;
262 int actual_number_of_colors;
265 JDIMENSION output_scanline; // USED
267 int input_scan_number;
268 JDIMENSION input_iMCU_row;
269 int output_scan_number;
270 JDIMENSION output_iMCU_row;
271 int (*coef_bits)[DCTSIZE2];
272 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
273 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
274 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
276 jpeg_component_info *comp_info;
277 jboolean progressive_mode;
279 unsigned char arith_dc_L[NUM_ARITH_TBLS];
280 unsigned char arith_dc_U[NUM_ARITH_TBLS];
281 unsigned char arith_ac_K[NUM_ARITH_TBLS];
282 unsigned int restart_interval;
283 jboolean saw_JFIF_marker;
284 unsigned char JFIF_major_version;
285 unsigned char JFIF_minor_version;
286 unsigned char density_unit;
287 unsigned short X_density;
288 unsigned short Y_density;
289 jboolean saw_Adobe_marker;
290 unsigned char Adobe_transform;
291 jboolean CCIR601_sampling;
293 int max_h_samp_factor;
294 int max_v_samp_factor;
295 int min_DCT_scaled_size;
296 JDIMENSION total_iMCU_rows;
297 void *sample_range_limit;
299 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
300 JDIMENSION MCUs_per_row;
301 JDIMENSION MCU_rows_in_scan;
303 int MCU_membership[D_MAX_BLOCKS_IN_MCU];
320 struct jpeg_compress_struct
322 struct jpeg_error_mgr *err;
323 struct jpeg_memory_mgr *mem;
326 jboolean is_decompressor;
330 JDIMENSION image_width;
331 JDIMENSION image_height;
332 int input_components;
333 J_COLOR_SPACE in_color_space;
338 J_COLOR_SPACE jpeg_color_space;
339 jpeg_component_info *comp_info;
340 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
341 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
342 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
343 unsigned char arith_dc_L[NUM_ARITH_TBLS];
344 unsigned char arith_dc_U[NUM_ARITH_TBLS];
345 unsigned char arith_ac_K[NUM_ARITH_TBLS];
348 const void *scan_info;
349 jboolean raw_data_in;
351 jboolean optimize_coding;
352 jboolean CCIR601_sampling;
353 int smoothing_factor;
354 J_DCT_METHOD dct_method;
356 unsigned int restart_interval;
359 jboolean write_JFIF_header;
360 unsigned char JFIF_major_version;
361 unsigned char JFIF_minor_version;
362 unsigned char density_unit;
363 unsigned short X_density;
364 unsigned short Y_density;
365 jboolean write_Adobe_marker;
366 JDIMENSION next_scanline;
368 jboolean progressive_mode;
369 int max_h_samp_factor;
370 int max_v_samp_factor;
371 JDIMENSION total_iMCU_rows;
373 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
374 JDIMENSION MCUs_per_row;
375 JDIMENSION MCU_rows_in_scan;
377 int MCU_membership[C_MAX_BLOCKS_IN_MCU];
390 int script_space_size;
393 struct jpeg_destination_mgr
395 unsigned char* next_output_byte;
396 size_t free_in_buffer;
398 void (*init_destination) (j_compress_ptr cinfo);
399 jboolean (*empty_output_buffer) (j_compress_ptr cinfo);
400 void (*term_destination) (j_compress_ptr cinfo);
405 =================================================================
407 DarkPlaces definitions
409 =================================================================
412 // Functions exported from libjpeg
413 #define qjpeg_create_compress(cinfo) \
414 qjpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_compress_struct))
415 #define qjpeg_create_decompress(cinfo) \
416 qjpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_decompress_struct))
418 static void (*qjpeg_CreateCompress) (j_compress_ptr cinfo, int version, size_t structsize);
419 static void (*qjpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize);
420 static void (*qjpeg_destroy_compress) (j_compress_ptr cinfo);
421 static void (*qjpeg_destroy_decompress) (j_decompress_ptr cinfo);
422 static void (*qjpeg_finish_compress) (j_compress_ptr cinfo);
423 static jboolean (*qjpeg_finish_decompress) (j_decompress_ptr cinfo);
424 static jboolean (*qjpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired);
425 static int (*qjpeg_read_header) (j_decompress_ptr cinfo, jboolean require_image);
426 static JDIMENSION (*qjpeg_read_scanlines) (j_decompress_ptr cinfo, unsigned char** scanlines, JDIMENSION max_lines);
427 static void (*qjpeg_set_defaults) (j_compress_ptr cinfo);
428 static void (*qjpeg_set_quality) (j_compress_ptr cinfo, int quality, jboolean force_baseline);
429 static jboolean (*qjpeg_start_compress) (j_compress_ptr cinfo, jboolean write_all_tables);
430 static jboolean (*qjpeg_start_decompress) (j_decompress_ptr cinfo);
431 static struct jpeg_error_mgr* (*qjpeg_std_error) (struct jpeg_error_mgr *err);
432 static JDIMENSION (*qjpeg_write_scanlines) (j_compress_ptr cinfo, unsigned char** scanlines, JDIMENSION num_lines);
433 static void (*qjpeg_simple_progression) (j_compress_ptr cinfo);
435 static dllfunction_t jpegfuncs[] =
437 {"jpeg_CreateCompress", (void **) &qjpeg_CreateCompress},
438 {"jpeg_CreateDecompress", (void **) &qjpeg_CreateDecompress},
439 {"jpeg_destroy_compress", (void **) &qjpeg_destroy_compress},
440 {"jpeg_destroy_decompress", (void **) &qjpeg_destroy_decompress},
441 {"jpeg_finish_compress", (void **) &qjpeg_finish_compress},
442 {"jpeg_finish_decompress", (void **) &qjpeg_finish_decompress},
443 {"jpeg_resync_to_restart", (void **) &qjpeg_resync_to_restart},
444 {"jpeg_read_header", (void **) &qjpeg_read_header},
445 {"jpeg_read_scanlines", (void **) &qjpeg_read_scanlines},
446 {"jpeg_set_defaults", (void **) &qjpeg_set_defaults},
447 {"jpeg_set_quality", (void **) &qjpeg_set_quality},
448 {"jpeg_start_compress", (void **) &qjpeg_start_compress},
449 {"jpeg_start_decompress", (void **) &qjpeg_start_decompress},
450 {"jpeg_std_error", (void **) &qjpeg_std_error},
451 {"jpeg_write_scanlines", (void **) &qjpeg_write_scanlines},
452 {"jpeg_simple_progression", (void **) &qjpeg_simple_progression},
456 // Handle for JPEG DLL
457 dllhandle_t jpeg_dll = NULL;
458 qbool jpeg_tried_loading = 0;
461 static unsigned char jpeg_eoi_marker [2] = {0xFF, JPEG_EOI};
462 static jmp_buf error_in_jpeg;
463 static qbool jpeg_toolarge;
465 // Our own output manager for JPEG compression
468 struct jpeg_destination_mgr pub;
471 unsigned char* buffer;
472 size_t bufsize; // used if outfile is NULL
473 } my_destination_mgr;
474 typedef my_destination_mgr* my_dest_ptr;
478 =================================================================
482 =================================================================
489 Try to load the JPEG DLL
492 qbool JPEG_OpenLibrary (void)
494 #ifdef LINK_TO_LIBJPEG
497 const char* dllnames [] =
501 #elif defined(MACOSX)
514 if (jpeg_tried_loading) // only try once
517 jpeg_tried_loading = true;
520 // loading the native Android libjpeg.so causes crashes
521 Con_Printf("Not opening libjpeg.so dynamically on Android - use LINK_TO_LIBJPEG instead if it is needed.\n");
526 return Sys_LoadDependency (dllnames, &jpeg_dll, jpegfuncs);
538 void JPEG_CloseLibrary (void)
540 #ifndef LINK_TO_LIBJPEG
541 Sys_FreeLibrary (&jpeg_dll);
542 jpeg_tried_loading = false; // allow retry
548 =================================================================
552 =================================================================
555 static void JPEG_Noop (j_decompress_ptr cinfo) {}
557 static jboolean JPEG_FillInputBuffer (j_decompress_ptr cinfo)
559 // Insert a fake EOI marker
560 cinfo->src->next_input_byte = jpeg_eoi_marker;
561 cinfo->src->bytes_in_buffer = 2;
566 static void JPEG_SkipInputData (j_decompress_ptr cinfo, long num_bytes)
568 if (cinfo->src->bytes_in_buffer <= (unsigned long)num_bytes)
570 cinfo->src->bytes_in_buffer = 0;
574 cinfo->src->next_input_byte += num_bytes;
575 cinfo->src->bytes_in_buffer -= num_bytes;
578 static void JPEG_MemSrc (j_decompress_ptr cinfo, const unsigned char *buffer, size_t filesize)
580 cinfo->src = (struct jpeg_source_mgr *)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
582 cinfo->src->next_input_byte = buffer;
583 cinfo->src->bytes_in_buffer = filesize;
585 cinfo->src->init_source = JPEG_Noop;
586 cinfo->src->fill_input_buffer = JPEG_FillInputBuffer;
587 cinfo->src->skip_input_data = JPEG_SkipInputData;
588 cinfo->src->resync_to_restart = qjpeg_resync_to_restart; // use the default method
589 cinfo->src->term_source = JPEG_Noop;
592 static void JPEG_ErrorExit (j_common_ptr cinfo)
594 ((struct jpeg_decompress_struct*)cinfo)->err->output_message (cinfo);
595 longjmp(error_in_jpeg, 1);
603 Load a JPEG image into a BGRA buffer
606 unsigned char* JPEG_LoadImage_BGRA (const unsigned char *f, int filesize, int *miplevel)
608 struct jpeg_decompress_struct cinfo;
609 struct jpeg_error_mgr jerr;
610 unsigned char *image_buffer = NULL, *scanline = NULL;
618 if(miplevel && r_texture_jpeg_fastpicmip.integer)
619 submip = bound(0, *miplevel, 3);
621 cinfo.err = qjpeg_std_error (&jerr);
622 qjpeg_create_decompress (&cinfo);
623 if(setjmp(error_in_jpeg))
625 cinfo.err = qjpeg_std_error (&jerr);
626 cinfo.err->error_exit = JPEG_ErrorExit;
627 JPEG_MemSrc (&cinfo, f, filesize);
628 qjpeg_read_header (&cinfo, true);
630 cinfo.scale_denom = (1 << submip);
631 qjpeg_start_decompress (&cinfo);
633 image_width = cinfo.output_width;
634 image_height = cinfo.output_height;
636 if (image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
638 Con_Printf("JPEG_LoadImage: invalid image size %ix%i\n", image_width, image_height);
642 image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
643 scanline = (unsigned char *)Mem_Alloc(tempmempool, image_width * cinfo.output_components);
644 if (!image_buffer || !scanline)
647 Mem_Free (image_buffer);
651 Con_Printf("JPEG_LoadImage: not enough memory for %i by %i image\n", image_width, image_height);
652 qjpeg_finish_decompress (&cinfo);
653 qjpeg_destroy_decompress (&cinfo);
657 // Decompress the image, line by line
659 while (cinfo.output_scanline < cinfo.output_height)
661 unsigned char *buffer_ptr;
664 qjpeg_read_scanlines (&cinfo, &scanline, 1);
666 // Convert the image to BGRA
667 switch (cinfo.output_components)
671 buffer_ptr = &image_buffer[image_width * line * 4];
672 for (ind = 0; ind < image_width * 3; ind += 3, buffer_ptr += 4)
674 buffer_ptr[2] = scanline[ind];
675 buffer_ptr[1] = scanline[ind + 1];
676 buffer_ptr[0] = scanline[ind + 2];
681 // Greyscale images (default to it, just in case)
684 buffer_ptr = &image_buffer[image_width * line * 4];
685 for (ind = 0; ind < image_width; ind++, buffer_ptr += 4)
687 buffer_ptr[0] = scanline[ind];
688 buffer_ptr[1] = scanline[ind];
689 buffer_ptr[2] = scanline[ind];
696 Mem_Free (scanline); scanline = NULL;
698 qjpeg_finish_decompress (&cinfo);
699 qjpeg_destroy_decompress (&cinfo);
710 Mem_Free (image_buffer);
711 qjpeg_destroy_decompress (&cinfo);
717 =================================================================
721 =================================================================
724 #define JPEG_OUTPUT_BUF_SIZE 4096
725 static void JPEG_InitDestination (j_compress_ptr cinfo)
727 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
728 dest->buffer = (unsigned char*)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_IMAGE, JPEG_OUTPUT_BUF_SIZE * sizeof(unsigned char));
729 dest->pub.next_output_byte = dest->buffer;
730 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
733 static jboolean JPEG_EmptyOutputBuffer (j_compress_ptr cinfo)
735 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
737 if (FS_Write (dest->outfile, dest->buffer, JPEG_OUTPUT_BUF_SIZE) != (size_t) JPEG_OUTPUT_BUF_SIZE)
738 longjmp(error_in_jpeg, 1);
740 dest->pub.next_output_byte = dest->buffer;
741 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
745 static void JPEG_TermDestination (j_compress_ptr cinfo)
747 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
748 size_t datacount = JPEG_OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
750 // Write any data remaining in the buffer
752 if (FS_Write (dest->outfile, dest->buffer, datacount) != (fs_offset_t)datacount)
753 longjmp(error_in_jpeg, 1);
756 static void JPEG_FileDest (j_compress_ptr cinfo, qfile_t* outfile)
760 // First time for this JPEG object?
761 if (cinfo->dest == NULL)
762 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
764 dest = (my_dest_ptr)cinfo->dest;
765 dest->pub.init_destination = JPEG_InitDestination;
766 dest->pub.empty_output_buffer = JPEG_EmptyOutputBuffer;
767 dest->pub.term_destination = JPEG_TermDestination;
768 dest->outfile = outfile;
771 static void JPEG_Mem_InitDestination (j_compress_ptr cinfo)
773 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
774 dest->pub.next_output_byte = dest->buffer;
775 dest->pub.free_in_buffer = dest->bufsize;
778 static jboolean JPEG_Mem_EmptyOutputBuffer (j_compress_ptr cinfo)
780 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
781 jpeg_toolarge = true;
782 dest->pub.next_output_byte = dest->buffer;
783 dest->pub.free_in_buffer = dest->bufsize;
787 static void JPEG_Mem_TermDestination (j_compress_ptr cinfo)
789 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
790 dest->bufsize = dest->pub.next_output_byte - dest->buffer;
792 static void JPEG_MemDest (j_compress_ptr cinfo, void* buf, size_t bufsize)
796 // First time for this JPEG object?
797 if (cinfo->dest == NULL)
798 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
800 dest = (my_dest_ptr)cinfo->dest;
801 dest->pub.init_destination = JPEG_Mem_InitDestination;
802 dest->pub.empty_output_buffer = JPEG_Mem_EmptyOutputBuffer;
803 dest->pub.term_destination = JPEG_Mem_TermDestination;
804 dest->outfile = NULL;
806 dest->buffer = (unsigned char *) buf;
807 dest->bufsize = bufsize;
813 JPEG_SaveImage_preflipped
815 Save a preflipped JPEG image to a file
818 qbool JPEG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
820 struct jpeg_compress_struct cinfo;
821 struct jpeg_error_mgr jerr;
822 unsigned char *scanline;
823 unsigned int offset, linesize;
829 Con_Print("You need the libjpeg library to save JPEG images\n");
834 file = FS_OpenRealFile(filename, "wb", true);
838 if(setjmp(error_in_jpeg))
840 cinfo.err = qjpeg_std_error (&jerr);
841 cinfo.err->error_exit = JPEG_ErrorExit;
843 qjpeg_create_compress (&cinfo);
844 JPEG_FileDest (&cinfo, file);
846 // Set the parameters for compression
847 cinfo.image_width = width;
848 cinfo.image_height = height;
849 cinfo.in_color_space = JCS_RGB;
850 cinfo.input_components = 3;
851 qjpeg_set_defaults (&cinfo);
852 qjpeg_set_quality (&cinfo, (int)(scr_screenshot_jpeg_quality.value * 100), true);
853 qjpeg_simple_progression (&cinfo);
855 // turn off subsampling (to make text look better)
856 cinfo.optimize_coding = 1;
857 cinfo.comp_info[0].h_samp_factor = 1;
858 cinfo.comp_info[0].v_samp_factor = 1;
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;
864 qjpeg_start_compress (&cinfo, true);
866 // Compress each scanline
867 linesize = cinfo.image_width * 3;
868 offset = linesize * (cinfo.image_height - 1);
869 while (cinfo.next_scanline < cinfo.image_height)
871 scanline = &data[offset - cinfo.next_scanline * linesize];
873 qjpeg_write_scanlines (&cinfo, &scanline, 1);
876 qjpeg_finish_compress (&cinfo);
877 qjpeg_destroy_compress (&cinfo);
883 qjpeg_destroy_compress (&cinfo);
888 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)
890 unsigned char *scanline;
891 unsigned int linesize;
893 jpeg_toolarge = false;
894 JPEG_MemDest (cinfo, jpegbuf, jpegsize);
896 // Set the parameters for compression
897 cinfo->image_width = width;
898 cinfo->image_height = height;
899 cinfo->in_color_space = JCS_RGB;
900 cinfo->input_components = 3;
901 qjpeg_set_defaults (cinfo);
902 qjpeg_set_quality (cinfo, quality, false);
904 cinfo->comp_info[0].h_samp_factor = 2;
905 cinfo->comp_info[0].v_samp_factor = 2;
906 cinfo->comp_info[1].h_samp_factor = 1;
907 cinfo->comp_info[1].v_samp_factor = 1;
908 cinfo->comp_info[2].h_samp_factor = 1;
909 cinfo->comp_info[2].v_samp_factor = 1;
910 cinfo->optimize_coding = 1;
912 qjpeg_start_compress (cinfo, true);
914 // Compress each scanline
915 linesize = width * 3;
916 while (cinfo->next_scanline < cinfo->image_height)
918 scanline = &data[cinfo->next_scanline * linesize];
920 qjpeg_write_scanlines (cinfo, &scanline, 1);
923 qjpeg_finish_compress (cinfo);
928 return ((my_dest_ptr) cinfo->dest)->bufsize;
931 size_t JPEG_SaveImage_to_Buffer (char *jpegbuf, size_t jpegsize, int width, int height, unsigned char *data)
933 struct jpeg_compress_struct cinfo;
934 struct jpeg_error_mgr jerr;
943 Con_Print("You need the libjpeg library to save JPEG images\n");
947 if(setjmp(error_in_jpeg))
949 cinfo.err = qjpeg_std_error (&jerr);
950 cinfo.err->error_exit = JPEG_ErrorExit;
952 qjpeg_create_compress (&cinfo);
955 // used to get the formula below
961 img = Mem_Alloc(tempmempool, width * height * 3);
962 for(i = 0; i < width * height * 3; ++i)
963 img[i] = rand() & 0xFF;
965 for(i = 0; i <= 100; ++i)
967 Con_Printf("! %d %d %d %d\n", width, height, i, (int) JPEG_try_SaveImage_to_Buffer(&cinfo, buf, sizeof(buf), i, width, height, img));
974 //quality_guess = (int)((100 * jpegsize - 41000) / (width*height) + 2); // fits random data
975 quality_guess = (int)((256 * jpegsize - 81920) / (width*height) - 8); // fits Nexuiz's/Xonotic's map pictures
977 quality_guess = bound(0, quality_guess, 100);
978 quality = bound(0, quality_guess + sv_writepicture_quality.integer, 100); // assume it can do 10 failed attempts
980 while(!(result = JPEG_try_SaveImage_to_Buffer(&cinfo, jpegbuf, jpegsize, quality, width, height, data)))
985 Con_Printf("couldn't write image at all, probably too big\n");
989 qjpeg_destroy_compress (&cinfo);
990 Con_DPrintf("JPEG_SaveImage_to_Buffer: guessed quality/size %d/%d, actually got %d/%d\n", quality_guess, (int)jpegsize, quality, (int)result);
995 qjpeg_destroy_compress (&cinfo);
999 typedef struct CompressedImageCacheItem
1001 char imagename[MAX_QPATH];
1004 size_t compressed_size;
1005 struct CompressedImageCacheItem *next;
1007 CompressedImageCacheItem;
1008 #define COMPRESSEDIMAGECACHE_SIZE 4096
1009 static CompressedImageCacheItem *CompressedImageCache[COMPRESSEDIMAGECACHE_SIZE];
1011 static void CompressedImageCache_Add(const char *imagename, size_t maxsize, void *compressed, size_t compressed_size)
1014 const char *hashkey = va(vabuf, sizeof(vabuf), "%s:%d", imagename, (int) maxsize);
1015 int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
1016 CompressedImageCacheItem *i;
1018 if(strlen(imagename) >= MAX_QPATH)
1019 return; // can't add this
1021 i = (CompressedImageCacheItem*) Z_Malloc(sizeof(CompressedImageCacheItem));
1022 dp_strlcpy(i->imagename, imagename, sizeof(i->imagename));
1023 i->maxsize = maxsize;
1024 i->compressed = compressed;
1025 i->compressed_size = compressed_size;
1026 i->next = CompressedImageCache[hashindex];
1027 CompressedImageCache[hashindex] = i;
1030 static CompressedImageCacheItem *CompressedImageCache_Find(const char *imagename, size_t maxsize)
1033 const char *hashkey = va(vabuf, sizeof(vabuf), "%s:%d", imagename, (int) maxsize);
1034 int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
1035 CompressedImageCacheItem *i = CompressedImageCache[hashindex];
1039 if(i->maxsize == maxsize)
1040 if(!strcmp(i->imagename, imagename))
1047 qbool Image_Compress(const char *imagename, size_t maxsize, void **buf, size_t *size)
1049 unsigned char *imagedata, *newimagedata;
1051 int components[3] = {2, 1, 0};
1052 CompressedImageCacheItem *i;
1054 JPEG_OpenLibrary (); // for now; LH had the idea of replacing this by a better format
1055 PNG_OpenLibrary (); // for loading
1057 // No DLL = no JPEGs
1060 Con_Print("You need the libjpeg library to save JPEG images\n");
1064 i = CompressedImageCache_Find(imagename, maxsize);
1067 *size = i->compressed_size;
1068 *buf = i->compressed;
1069 return (*buf != NULL);
1073 imagedata = loadimagepixelsbgra(imagename, true, false, false, NULL);
1077 // find an appropriate size for somewhat okay compression
1079 maxPixelCount = 32 * 32;
1080 else if(maxsize <= 1024)
1081 maxPixelCount = 64 * 64;
1082 else if(maxsize <= 4096)
1083 maxPixelCount = 128 * 128;
1085 maxPixelCount = 256 * 256;
1087 while(image_width * image_height > maxPixelCount)
1090 Image_MipReduce32(imagedata, imagedata, &image_width, &image_height, &one, image_width/2, image_height/2, 1);
1093 newimagedata = (unsigned char *) Mem_Alloc(tempmempool, image_width * image_height * 3);
1095 // convert the image from BGRA to RGB
1096 Image_CopyMux(newimagedata, imagedata, image_width, image_height, false, false, false, 3, 4, components);
1097 Mem_Free(imagedata);
1099 // try to compress it to JPEG
1100 *buf = Z_Malloc(maxsize);
1101 *size = JPEG_SaveImage_to_Buffer((char *) *buf, maxsize, image_width, image_height, newimagedata);
1102 Mem_Free(newimagedata);
1108 Con_Printf("could not compress image %s to %d bytes\n", imagename, (int)maxsize);
1110 // also cache failures!
1113 // store it in the cache
1114 CompressedImageCache_Add(imagename, maxsize, *buf, *size);
1115 return (*buf != NULL);