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
31 =================================================================
33 Minimal set of definitions from the JPEG lib
35 WARNING: for a matter of simplicity, several pointer types are
36 casted to "void*", and most enumerated values are not included
38 =================================================================
41 // jboolean is unsigned char instead of int on Win32
43 typedef unsigned char jboolean;
48 #define JPEG_LIB_VERSION 62 // Version 6b
50 typedef void *j_common_ptr;
51 typedef struct jpeg_compress_struct *j_compress_ptr;
52 typedef struct jpeg_decompress_struct *j_decompress_ptr;
62 typedef enum {JPEG_DUMMY1} J_DCT_METHOD;
63 typedef enum {JPEG_DUMMY2} J_DITHER_MODE;
64 typedef unsigned int JDIMENSION;
66 #define JPOOL_PERMANENT 0 // lasts until master record is destroyed
67 #define JPOOL_IMAGE 1 // lasts until done with image/datastream
69 #define JPEG_EOI 0xD9 // EOI marker code
71 #define JMSG_STR_PARM_MAX 80
74 #define NUM_QUANT_TBLS 4
75 #define NUM_HUFF_TBLS 4
76 #define NUM_ARITH_TBLS 16
77 #define MAX_COMPS_IN_SCAN 4
78 #define C_MAX_BLOCKS_IN_MCU 10
79 #define D_MAX_BLOCKS_IN_MCU 10
81 struct jpeg_memory_mgr
83 void* (*alloc_small) (j_common_ptr cinfo, int pool_id, size_t sizeofobject);
84 void (*alloc_large) ();
85 void (*alloc_sarray) ();
86 void (*alloc_barray) ();
87 void (*request_virt_sarray) ();
88 void (*request_virt_barray) ();
89 void (*realize_virt_arrays) ();
90 void (*access_virt_sarray) ();
91 void (*access_virt_barray) ();
93 void (*self_destruct) ();
95 long max_memory_to_use;
101 void (*error_exit) (j_common_ptr cinfo);
102 void (*emit_message) (j_common_ptr cinfo, int msg_level);
103 void (*output_message) (j_common_ptr cinfo);
104 void (*format_message) (j_common_ptr cinfo, char * buffer);
105 void (*reset_error_mgr) (j_common_ptr cinfo);
109 char s[JMSG_STR_PARM_MAX];
113 const char * const * jpeg_message_table;
114 int last_jpeg_message;
115 const char * const * addon_message_table;
116 int first_addon_message;
117 int last_addon_message;
120 struct jpeg_source_mgr
122 const unsigned char *next_input_byte;
123 size_t bytes_in_buffer;
125 void (*init_source) (j_decompress_ptr cinfo);
126 jboolean (*fill_input_buffer) (j_decompress_ptr cinfo);
127 void (*skip_input_data) (j_decompress_ptr cinfo, long num_bytes);
128 jboolean (*resync_to_restart) (j_decompress_ptr cinfo, int desired);
129 void (*term_source) (j_decompress_ptr cinfo);
133 /* These values are fixed over the whole image. */
134 /* For compression, they must be supplied by parameter setup; */
135 /* for decompression, they are read from the SOF marker. */
136 int component_id; /* identifier for this component (0..255) */
137 int component_index; /* its index in SOF or cinfo->comp_info[] */
138 int h_samp_factor; /* horizontal sampling factor (1..4) */
139 int v_samp_factor; /* vertical sampling factor (1..4) */
140 int quant_tbl_no; /* quantization table selector (0..3) */
141 /* These values may vary between scans. */
142 /* For compression, they must be supplied by parameter setup; */
143 /* for decompression, they are read from the SOS marker. */
144 /* The decompressor output side may not use these variables. */
145 int dc_tbl_no; /* DC entropy table selector (0..3) */
146 int ac_tbl_no; /* AC entropy table selector (0..3) */
148 /* Remaining fields should be treated as private by applications. */
150 /* These values are computed during compression or decompression startup: */
151 /* Component's size in DCT blocks.
152 * Any dummy blocks added to complete an MCU are not counted; therefore
153 * these values do not depend on whether a scan is interleaved or not.
155 JDIMENSION width_in_blocks;
156 JDIMENSION height_in_blocks;
157 /* Size of a DCT block in samples. Always DCTSIZE for compression.
158 * For decompression this is the size of the output from one DCT block,
159 * reflecting any scaling we choose to apply during the IDCT step.
160 * Values of 1,2,4,8 are likely to be supported. Note that different
161 * components may receive different IDCT scalings.
164 /* The downsampled dimensions are the component's actual, unpadded number
165 * of samples at the main buffer (preprocessing/compression interface), thus
166 * downsampled_width = ceil(image_width * Hi/Hmax)
167 * and similarly for height. For decompression, IDCT scaling is included, so
168 * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
170 JDIMENSION downsampled_width; /* actual width in samples */
171 JDIMENSION downsampled_height; /* actual height in samples */
172 /* This flag is used only for decompression. In cases where some of the
173 * components will be ignored (eg grayscale output from YCbCr image),
174 * we can skip most computations for the unused components.
176 jboolean component_needed; /* do we need the value of this component? */
178 /* These values are computed before starting a scan of the component. */
179 /* The decompressor output side may not use these variables. */
180 int MCU_width; /* number of blocks per MCU, horizontally */
181 int MCU_height; /* number of blocks per MCU, vertically */
182 int MCU_blocks; /* MCU_width * MCU_height */
183 int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
184 int last_col_width; /* # of non-dummy blocks across in last MCU */
185 int last_row_height; /* # of non-dummy blocks down in last MCU */
187 /* Saved quantization table for component; NULL if none yet saved.
188 * See jdinput.c comments about the need for this information.
189 * This field is currently used only for decompression.
193 /* Private per-component storage for DCT or IDCT subsystem. */
195 } jpeg_component_info;
197 struct jpeg_decompress_struct
199 struct jpeg_error_mgr *err; // USED
200 struct jpeg_memory_mgr *mem; // USED
204 jboolean is_decompressor;
207 struct jpeg_source_mgr *src; // USED
208 JDIMENSION image_width; // USED
209 JDIMENSION image_height; // USED
212 J_COLOR_SPACE jpeg_color_space;
213 J_COLOR_SPACE out_color_space;
214 unsigned int scale_num, scale_denom;
216 jboolean buffered_image;
217 jboolean raw_data_out;
218 J_DCT_METHOD dct_method;
219 jboolean do_fancy_upsampling;
220 jboolean do_block_smoothing;
221 jboolean quantize_colors;
222 J_DITHER_MODE dither_mode;
223 jboolean two_pass_quantize;
224 int desired_number_of_colors;
225 jboolean enable_1pass_quant;
226 jboolean enable_external_quant;
227 jboolean enable_2pass_quant;
228 JDIMENSION output_width;
230 JDIMENSION output_height; // USED
232 int out_color_components;
234 int output_components; // USED
236 int rec_outbuf_height;
237 int actual_number_of_colors;
240 JDIMENSION output_scanline; // USED
242 int input_scan_number;
243 JDIMENSION input_iMCU_row;
244 int output_scan_number;
245 JDIMENSION output_iMCU_row;
246 int (*coef_bits)[DCTSIZE2];
247 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
248 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
249 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
251 jpeg_component_info *comp_info;
252 jboolean progressive_mode;
254 unsigned char arith_dc_L[NUM_ARITH_TBLS];
255 unsigned char arith_dc_U[NUM_ARITH_TBLS];
256 unsigned char arith_ac_K[NUM_ARITH_TBLS];
257 unsigned int restart_interval;
258 jboolean saw_JFIF_marker;
259 unsigned char JFIF_major_version;
260 unsigned char JFIF_minor_version;
261 unsigned char density_unit;
262 unsigned short X_density;
263 unsigned short Y_density;
264 jboolean saw_Adobe_marker;
265 unsigned char Adobe_transform;
266 jboolean CCIR601_sampling;
268 int max_h_samp_factor;
269 int max_v_samp_factor;
270 int min_DCT_scaled_size;
271 JDIMENSION total_iMCU_rows;
272 void *sample_range_limit;
274 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
275 JDIMENSION MCUs_per_row;
276 JDIMENSION MCU_rows_in_scan;
278 int MCU_membership[D_MAX_BLOCKS_IN_MCU];
295 struct jpeg_compress_struct
297 struct jpeg_error_mgr *err;
298 struct jpeg_memory_mgr *mem;
301 jboolean is_decompressor;
305 JDIMENSION image_width;
306 JDIMENSION image_height;
307 int input_components;
308 J_COLOR_SPACE in_color_space;
313 J_COLOR_SPACE jpeg_color_space;
314 jpeg_component_info *comp_info;
315 void *quant_tbl_ptrs[NUM_QUANT_TBLS];
316 void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
317 void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
318 unsigned char arith_dc_L[NUM_ARITH_TBLS];
319 unsigned char arith_dc_U[NUM_ARITH_TBLS];
320 unsigned char arith_ac_K[NUM_ARITH_TBLS];
323 const void *scan_info;
324 jboolean raw_data_in;
326 jboolean optimize_coding;
327 jboolean CCIR601_sampling;
328 int smoothing_factor;
329 J_DCT_METHOD dct_method;
331 unsigned int restart_interval;
334 jboolean write_JFIF_header;
335 unsigned char JFIF_major_version;
336 unsigned char JFIF_minor_version;
337 unsigned char density_unit;
338 unsigned short X_density;
339 unsigned short Y_density;
340 jboolean write_Adobe_marker;
341 JDIMENSION next_scanline;
343 jboolean progressive_mode;
344 int max_h_samp_factor;
345 int max_v_samp_factor;
346 JDIMENSION total_iMCU_rows;
348 jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
349 JDIMENSION MCUs_per_row;
350 JDIMENSION MCU_rows_in_scan;
352 int MCU_membership[C_MAX_BLOCKS_IN_MCU];
365 int script_space_size;
368 struct jpeg_destination_mgr
370 unsigned char* next_output_byte;
371 size_t free_in_buffer;
373 void (*init_destination) (j_compress_ptr cinfo);
374 jboolean (*empty_output_buffer) (j_compress_ptr cinfo);
375 void (*term_destination) (j_compress_ptr cinfo);
380 =================================================================
382 DarkPlaces definitions
384 =================================================================
387 // Functions exported from libjpeg
388 #define qjpeg_create_compress(cinfo) \
389 qjpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_compress_struct))
390 #define qjpeg_create_decompress(cinfo) \
391 qjpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_decompress_struct))
393 static void (*qjpeg_CreateCompress) (j_compress_ptr cinfo, int version, size_t structsize);
394 static void (*qjpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize);
395 static void (*qjpeg_destroy_compress) (j_compress_ptr cinfo);
396 static void (*qjpeg_destroy_decompress) (j_decompress_ptr cinfo);
397 static void (*qjpeg_finish_compress) (j_compress_ptr cinfo);
398 static jboolean (*qjpeg_finish_decompress) (j_decompress_ptr cinfo);
399 static jboolean (*qjpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired);
400 static int (*qjpeg_read_header) (j_decompress_ptr cinfo, jboolean require_image);
401 static JDIMENSION (*qjpeg_read_scanlines) (j_decompress_ptr cinfo, unsigned char** scanlines, JDIMENSION max_lines);
402 static void (*qjpeg_set_defaults) (j_compress_ptr cinfo);
403 static void (*qjpeg_set_quality) (j_compress_ptr cinfo, int quality, jboolean force_baseline);
404 static jboolean (*qjpeg_start_compress) (j_compress_ptr cinfo, jboolean write_all_tables);
405 static jboolean (*qjpeg_start_decompress) (j_decompress_ptr cinfo);
406 static struct jpeg_error_mgr* (*qjpeg_std_error) (struct jpeg_error_mgr *err);
407 static JDIMENSION (*qjpeg_write_scanlines) (j_compress_ptr cinfo, unsigned char** scanlines, JDIMENSION num_lines);
409 static dllfunction_t jpegfuncs[] =
411 {"jpeg_CreateCompress", (void **) &qjpeg_CreateCompress},
412 {"jpeg_CreateDecompress", (void **) &qjpeg_CreateDecompress},
413 {"jpeg_destroy_compress", (void **) &qjpeg_destroy_compress},
414 {"jpeg_destroy_decompress", (void **) &qjpeg_destroy_decompress},
415 {"jpeg_finish_compress", (void **) &qjpeg_finish_compress},
416 {"jpeg_finish_decompress", (void **) &qjpeg_finish_decompress},
417 {"jpeg_resync_to_restart", (void **) &qjpeg_resync_to_restart},
418 {"jpeg_read_header", (void **) &qjpeg_read_header},
419 {"jpeg_read_scanlines", (void **) &qjpeg_read_scanlines},
420 {"jpeg_set_defaults", (void **) &qjpeg_set_defaults},
421 {"jpeg_set_quality", (void **) &qjpeg_set_quality},
422 {"jpeg_start_compress", (void **) &qjpeg_start_compress},
423 {"jpeg_start_decompress", (void **) &qjpeg_start_decompress},
424 {"jpeg_std_error", (void **) &qjpeg_std_error},
425 {"jpeg_write_scanlines", (void **) &qjpeg_write_scanlines},
429 // Handle for JPEG DLL
430 dllhandle_t jpeg_dll = NULL;
432 static unsigned char jpeg_eoi_marker [2] = {0xFF, JPEG_EOI};
433 static qboolean error_in_jpeg;
435 // Our own output manager for JPEG compression
438 struct jpeg_destination_mgr pub;
441 unsigned char* buffer;
442 } my_destination_mgr;
443 typedef my_destination_mgr* my_dest_ptr;
447 =================================================================
451 =================================================================
458 Try to load the JPEG DLL
461 qboolean JPEG_OpenLibrary (void)
463 const char* dllnames [] =
469 #elif defined(MACOSX)
483 return Sys_LoadLibrary (dllnames, &jpeg_dll, jpegfuncs);
494 void JPEG_CloseLibrary (void)
496 Sys_UnloadLibrary (&jpeg_dll);
501 =================================================================
505 =================================================================
508 static void JPEG_Noop (j_decompress_ptr cinfo) {}
510 static jboolean JPEG_FillInputBuffer (j_decompress_ptr cinfo)
512 // Insert a fake EOI marker
513 cinfo->src->next_input_byte = jpeg_eoi_marker;
514 cinfo->src->bytes_in_buffer = 2;
519 static void JPEG_SkipInputData (j_decompress_ptr cinfo, long num_bytes)
521 if (cinfo->src->bytes_in_buffer <= (unsigned long)num_bytes)
523 cinfo->src->bytes_in_buffer = 0;
527 cinfo->src->next_input_byte += num_bytes;
528 cinfo->src->bytes_in_buffer -= num_bytes;
531 static void JPEG_MemSrc (j_decompress_ptr cinfo, const unsigned char *buffer, size_t filesize)
533 cinfo->src = (struct jpeg_source_mgr *)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
535 cinfo->src->next_input_byte = buffer;
536 cinfo->src->bytes_in_buffer = filesize;
538 cinfo->src->init_source = JPEG_Noop;
539 cinfo->src->fill_input_buffer = JPEG_FillInputBuffer;
540 cinfo->src->skip_input_data = JPEG_SkipInputData;
541 cinfo->src->resync_to_restart = qjpeg_resync_to_restart; // use the default method
542 cinfo->src->term_source = JPEG_Noop;
545 static void JPEG_ErrorExit (j_common_ptr cinfo)
547 ((struct jpeg_decompress_struct*)cinfo)->err->output_message (cinfo);
548 error_in_jpeg = true;
556 Load a JPEG image into a BGRA buffer
559 unsigned char* JPEG_LoadImage_BGRA (const unsigned char *f, int filesize)
561 struct jpeg_decompress_struct cinfo;
562 struct jpeg_error_mgr jerr;
563 unsigned char *image_buffer, *scanline;
570 cinfo.err = qjpeg_std_error (&jerr);
571 qjpeg_create_decompress (&cinfo);
572 JPEG_MemSrc (&cinfo, f, filesize);
573 qjpeg_read_header (&cinfo, TRUE);
574 qjpeg_start_decompress (&cinfo);
576 image_width = cinfo.image_width;
577 image_height = cinfo.image_height;
579 if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
581 Con_Printf("JPEG_LoadImage: invalid image size %ix%i\n", image_width, image_height);
585 image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
586 scanline = (unsigned char *)Mem_Alloc(tempmempool, image_width * cinfo.output_components);
587 if (!image_buffer || !scanline)
590 Mem_Free (image_buffer);
594 Con_Printf("JPEG_LoadImage: not enough memory for %i by %i image\n", image_width, image_height);
595 qjpeg_finish_decompress (&cinfo);
596 qjpeg_destroy_decompress (&cinfo);
600 // Decompress the image, line by line
602 while (cinfo.output_scanline < cinfo.output_height)
604 unsigned char *buffer_ptr;
607 qjpeg_read_scanlines (&cinfo, &scanline, 1);
609 // Convert the image to BGRA
610 switch (cinfo.output_components)
614 buffer_ptr = &image_buffer[image_width * line * 4];
615 for (ind = 0; ind < image_width * 3; ind += 3, buffer_ptr += 4)
617 buffer_ptr[2] = scanline[ind];
618 buffer_ptr[1] = scanline[ind + 1];
619 buffer_ptr[0] = scanline[ind + 2];
624 // Greyscale images (default to it, just in case)
627 buffer_ptr = &image_buffer[image_width * line * 4];
628 for (ind = 0; ind < image_width; ind++, buffer_ptr += 4)
630 buffer_ptr[0] = scanline[ind];
631 buffer_ptr[1] = scanline[ind];
632 buffer_ptr[2] = scanline[ind];
641 qjpeg_finish_decompress (&cinfo);
642 qjpeg_destroy_decompress (&cinfo);
649 =================================================================
653 =================================================================
656 #define JPEG_OUTPUT_BUF_SIZE 4096
657 static void JPEG_InitDestination (j_compress_ptr cinfo)
659 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
660 dest->buffer = (unsigned char*)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_IMAGE, JPEG_OUTPUT_BUF_SIZE * sizeof(unsigned char));
661 dest->pub.next_output_byte = dest->buffer;
662 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
665 static jboolean JPEG_EmptyOutputBuffer (j_compress_ptr cinfo)
667 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
669 if (FS_Write (dest->outfile, dest->buffer, JPEG_OUTPUT_BUF_SIZE) != (size_t) JPEG_OUTPUT_BUF_SIZE)
671 error_in_jpeg = true;
675 dest->pub.next_output_byte = dest->buffer;
676 dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
680 static void JPEG_TermDestination (j_compress_ptr cinfo)
682 my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
683 size_t datacount = JPEG_OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
685 // Write any data remaining in the buffer
687 if (FS_Write (dest->outfile, dest->buffer, datacount) != (fs_offset_t)datacount)
688 error_in_jpeg = true;
691 static void JPEG_MemDest (j_compress_ptr cinfo, qfile_t* outfile)
695 // First time for this JPEG object?
696 if (cinfo->dest == NULL)
697 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
699 dest = (my_dest_ptr)cinfo->dest;
700 dest->pub.init_destination = JPEG_InitDestination;
701 dest->pub.empty_output_buffer = JPEG_EmptyOutputBuffer;
702 dest->pub.term_destination = JPEG_TermDestination;
703 dest->outfile = outfile;
709 JPEG_SaveImage_preflipped
711 Save a preflipped JPEG image to a file
714 qboolean JPEG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
716 struct jpeg_compress_struct cinfo;
717 struct jpeg_error_mgr jerr;
718 unsigned char *scanline;
719 unsigned int offset, linesize;
725 Con_Print("You need the libjpeg library to save JPEG images\n");
730 file = FS_Open (filename, "wb", true, false);
734 cinfo.err = qjpeg_std_error (&jerr);
735 cinfo.err->error_exit = JPEG_ErrorExit;
736 error_in_jpeg = false;
738 qjpeg_create_compress (&cinfo);
739 JPEG_MemDest (&cinfo, file);
741 // Set the parameters for compression
742 cinfo.image_width = width;
743 cinfo.image_height = height;
744 cinfo.in_color_space = JCS_RGB;
745 cinfo.input_components = 3;
746 qjpeg_set_defaults (&cinfo);
747 qjpeg_set_quality (&cinfo, (int)(scr_screenshot_jpeg_quality.value * 100), TRUE);
749 // turn off subsampling (to make text look better)
750 cinfo.optimize_coding = 1;
751 cinfo.comp_info[0].h_samp_factor = 1;
752 cinfo.comp_info[0].v_samp_factor = 1;
753 cinfo.comp_info[1].h_samp_factor = 1;
754 cinfo.comp_info[1].v_samp_factor = 1;
755 cinfo.comp_info[2].h_samp_factor = 1;
756 cinfo.comp_info[2].v_samp_factor = 1;
758 qjpeg_start_compress (&cinfo, true);
760 // Compress each scanline
761 linesize = cinfo.image_width * 3;
762 offset = linesize * (cinfo.image_height - 1);
763 while (cinfo.next_scanline < cinfo.image_height)
765 scanline = &data[offset - cinfo.next_scanline * linesize];
767 qjpeg_write_scanlines (&cinfo, &scanline, 1);
772 qjpeg_finish_compress (&cinfo);
773 qjpeg_destroy_compress (&cinfo);