]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - jpeg.c
add a missing include
[xonotic/darkplaces.git] / jpeg.c
1 /*
2         Copyright (C) 2002  Mathieu Olivier
3
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.
8
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.
12
13         See the GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to:
17
18                 Free Software Foundation, Inc.
19                 59 Temple Place - Suite 330
20                 Boston, MA  02111-1307, USA
21
22 */
23
24
25 #include "quakedef.h"
26 #include "image.h"
27 #include "jpeg.h"
28 #include "image_png.h"
29
30 cvar_t sv_writepicture_quality = {CVAR_SAVE, "sv_writepicture_quality", "10", "WritePicture quality offset (higher means better quality, but slower)"};
31
32 // jboolean is unsigned char instead of int on Win32
33 #ifdef WIN32
34 typedef unsigned char jboolean;
35 #else
36 typedef int jboolean;
37 #endif
38
39 #ifdef LINK_TO_LIBJPEG
40 #include <jpeglib.h>
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
57 #define jpeg_dll true
58 #else
59 /*
60 =================================================================
61
62   Minimal set of definitions from the JPEG lib
63
64   WARNING: for a matter of simplicity, several pointer types are
65   casted to "void*", and most enumerated values are not included
66
67 =================================================================
68 */
69
70 typedef void *j_common_ptr;
71 typedef struct jpeg_compress_struct *j_compress_ptr;
72 typedef struct jpeg_decompress_struct *j_decompress_ptr;
73
74 #define JPEG_LIB_VERSION  62  // Version 6b
75
76 typedef enum
77 {
78         JCS_UNKNOWN,
79         JCS_GRAYSCALE,
80         JCS_RGB,
81         JCS_YCbCr,
82         JCS_CMYK,
83         JCS_YCCK
84 } J_COLOR_SPACE;
85 typedef enum {JPEG_DUMMY1} J_DCT_METHOD;
86 typedef enum {JPEG_DUMMY2} J_DITHER_MODE;
87 typedef unsigned int JDIMENSION;
88
89 #define JPOOL_PERMANENT 0       // lasts until master record is destroyed
90 #define JPOOL_IMAGE             1       // lasts until done with image/datastream
91
92 #define JPEG_EOI        0xD9  // EOI marker code
93
94 #define JMSG_STR_PARM_MAX  80
95
96 #define DCTSIZE2 64
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
103
104 struct jpeg_memory_mgr
105 {
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, ...);
117
118   long max_memory_to_use;
119   long max_alloc_chunk;
120 };
121
122 struct jpeg_error_mgr
123 {
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);
129         int msg_code;
130         union {
131                 int i[8];
132                 char s[JMSG_STR_PARM_MAX];
133         } msg_parm;
134         int trace_level;
135         long num_warnings;
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;
141 };
142
143 struct jpeg_source_mgr
144 {
145         const unsigned char *next_input_byte;
146         size_t bytes_in_buffer;
147
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);
153 };
154
155 typedef struct {
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) */
170   
171   /* Remaining fields should be treated as private by applications. */
172   
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.
177    */
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.
185    */
186   int DCT_scaled_size;
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)
192    */
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.
198    */
199   jboolean component_needed;     /* do we need the value of this component? */
200
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 */
209
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.
213    */
214   void *quant_table;
215
216   /* Private per-component storage for DCT or IDCT subsystem. */
217   void * dct_table;
218 } jpeg_component_info;
219
220 struct jpeg_decompress_struct
221 {
222         struct jpeg_error_mgr *err;             // USED
223         struct jpeg_memory_mgr *mem;    // USED
224
225         void *progress;
226         void *client_data;
227         jboolean is_decompressor;
228         int global_state;
229
230         struct jpeg_source_mgr *src;    // USED
231         JDIMENSION image_width;                 // USED
232         JDIMENSION image_height;                // USED
233
234         int num_components;
235         J_COLOR_SPACE jpeg_color_space;
236         J_COLOR_SPACE out_color_space;
237         unsigned int scale_num, scale_denom;
238         double output_gamma;
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;
252
253         JDIMENSION output_height;       // USED
254
255         int out_color_components;
256
257         int output_components;          // USED
258
259         int rec_outbuf_height;
260         int actual_number_of_colors;
261         void *colormap;
262
263         JDIMENSION output_scanline;     // USED
264
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];
273         int data_precision;
274         jpeg_component_info *comp_info;
275         jboolean progressive_mode;
276         jboolean arith_code;
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;
290         void *marker_list;
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;
296         int comps_in_scan;
297         jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
298         JDIMENSION MCUs_per_row;
299         JDIMENSION MCU_rows_in_scan;
300         int blocks_in_MCU;
301         int MCU_membership[D_MAX_BLOCKS_IN_MCU];
302         int Ss, Se, Ah, Al;
303         int unread_marker;
304         void *master;
305         void *main;
306         void *coef;
307         void *post;
308         void *inputctl;
309         void *marker;
310         void *entropy;
311         void *idct;
312         void *upsample;
313         void *cconvert;
314         void *cquantize;
315 };
316
317
318 struct jpeg_compress_struct
319 {
320         struct jpeg_error_mgr *err;
321         struct jpeg_memory_mgr *mem;
322         void *progress;
323         void *client_data;
324         jboolean is_decompressor;
325         int global_state;
326
327         void *dest;
328         JDIMENSION image_width;
329         JDIMENSION image_height;
330         int input_components;
331         J_COLOR_SPACE in_color_space;
332         double input_gamma;
333         int data_precision;
334
335         int num_components;
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];
344
345         int num_scans;
346         const void *scan_info;
347         jboolean raw_data_in;
348         jboolean arith_code;
349         jboolean optimize_coding;
350         jboolean CCIR601_sampling;
351         int smoothing_factor;
352         J_DCT_METHOD dct_method;
353
354         unsigned int restart_interval;
355         int restart_in_rows;
356
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;
365
366         jboolean progressive_mode;
367         int max_h_samp_factor;
368         int max_v_samp_factor;
369         JDIMENSION total_iMCU_rows;
370         int comps_in_scan;
371         jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
372         JDIMENSION MCUs_per_row;
373         JDIMENSION MCU_rows_in_scan;
374         int blocks_in_MCU;
375         int MCU_membership[C_MAX_BLOCKS_IN_MCU];
376         int Ss, Se, Ah, Al;
377
378         void *master;
379         void *main;
380         void *prep;
381         void *coef;
382         void *marker;
383         void *cconvert;
384         void *downsample;
385         void *fdct;
386         void *entropy;
387         void *script_space;
388         int script_space_size;
389 };
390
391 struct jpeg_destination_mgr
392 {
393         unsigned char* next_output_byte;
394         size_t free_in_buffer;
395
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);
399 };
400
401
402 /*
403 =================================================================
404
405   DarkPlaces definitions
406
407 =================================================================
408 */
409
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))
415
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);
432
433 static dllfunction_t jpegfuncs[] =
434 {
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},
451         {NULL, NULL}
452 };
453
454 // Handle for JPEG DLL
455 dllhandle_t jpeg_dll = NULL;
456 qboolean jpeg_tried_loading = 0;
457 #endif
458
459 static unsigned char jpeg_eoi_marker [2] = {0xFF, JPEG_EOI};
460 static jmp_buf error_in_jpeg;
461 static qboolean jpeg_toolarge;
462
463 // Our own output manager for JPEG compression
464 typedef struct
465 {
466         struct jpeg_destination_mgr pub;
467
468         qfile_t* outfile;
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;
473
474
475 /*
476 =================================================================
477
478   DLL load & unload
479
480 =================================================================
481 */
482
483 /*
484 ====================
485 JPEG_OpenLibrary
486
487 Try to load the JPEG DLL
488 ====================
489 */
490 qboolean JPEG_OpenLibrary (void)
491 {
492 #ifdef LINK_TO_LIBJPEG
493         return true;
494 #else
495         const char* dllnames [] =
496         {
497 #if defined(WIN32)
498                 "libjpeg.dll",
499 #elif defined(MACOSX)
500                 "libjpeg.62.dylib",
501 #else
502                 "libjpeg.so.62",
503                 "libjpeg.so",
504 #endif
505                 NULL
506         };
507
508         // Already loaded?
509         if (jpeg_dll)
510                 return true;
511
512         if (jpeg_tried_loading) // only try once
513                 return false;
514
515         jpeg_tried_loading = true;
516
517         // Load the DLL
518         return Sys_LoadLibrary (dllnames, &jpeg_dll, jpegfuncs);
519 #endif
520 }
521
522
523 /*
524 ====================
525 JPEG_CloseLibrary
526
527 Unload the JPEG DLL
528 ====================
529 */
530 void JPEG_CloseLibrary (void)
531 {
532 #ifndef LINK_TO_LIBJPEG
533         Sys_UnloadLibrary (&jpeg_dll);
534         jpeg_tried_loading = false; // allow retry
535 #endif
536 }
537
538
539 /*
540 =================================================================
541
542         JPEG decompression
543
544 =================================================================
545 */
546
547 static void JPEG_Noop (j_decompress_ptr cinfo) {}
548
549 static jboolean JPEG_FillInputBuffer (j_decompress_ptr cinfo)
550 {
551     // Insert a fake EOI marker
552     cinfo->src->next_input_byte = jpeg_eoi_marker;
553     cinfo->src->bytes_in_buffer = 2;
554
555         return TRUE;
556 }
557
558 static void JPEG_SkipInputData (j_decompress_ptr cinfo, long num_bytes)
559 {
560     if (cinfo->src->bytes_in_buffer <= (unsigned long)num_bytes)
561         {
562                 cinfo->src->bytes_in_buffer = 0;
563                 return;
564         }
565
566     cinfo->src->next_input_byte += num_bytes;
567     cinfo->src->bytes_in_buffer -= num_bytes;
568 }
569
570 static void JPEG_MemSrc (j_decompress_ptr cinfo, const unsigned char *buffer, size_t filesize)
571 {
572         cinfo->src = (struct jpeg_source_mgr *)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
573
574         cinfo->src->next_input_byte = buffer;
575         cinfo->src->bytes_in_buffer = filesize;
576
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;
582 }
583
584 static void JPEG_ErrorExit (j_common_ptr cinfo)
585 {
586         ((struct jpeg_decompress_struct*)cinfo)->err->output_message (cinfo);
587         longjmp(error_in_jpeg, 1);
588 }
589
590
591 /*
592 ====================
593 JPEG_LoadImage
594
595 Load a JPEG image into a BGRA buffer
596 ====================
597 */
598 unsigned char* JPEG_LoadImage_BGRA (const unsigned char *f, int filesize)
599 {
600         struct jpeg_decompress_struct cinfo;
601         struct jpeg_error_mgr jerr;
602         unsigned char *image_buffer = NULL, *scanline = NULL;
603         unsigned int line;
604
605         // No DLL = no JPEGs
606         if (!jpeg_dll)
607                 return NULL;
608
609         cinfo.err = qjpeg_std_error (&jerr);
610         qjpeg_create_decompress (&cinfo);
611         if(setjmp(error_in_jpeg))
612                 goto error_caught;
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);
618
619         image_width = cinfo.image_width;
620         image_height = cinfo.image_height;
621
622         if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
623         {
624                 Con_Printf("JPEG_LoadImage: invalid image size %ix%i\n", image_width, image_height);
625                 return NULL;
626         }
627
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)
631         {
632                 if (image_buffer)
633                         Mem_Free (image_buffer);
634                 if (scanline)
635                         Mem_Free (scanline);
636
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);
640                 return NULL;
641         }
642
643         // Decompress the image, line by line
644         line = 0;
645         while (cinfo.output_scanline < cinfo.output_height)
646         {
647                 unsigned char *buffer_ptr;
648                 int ind;
649
650                 qjpeg_read_scanlines (&cinfo, &scanline, 1);
651
652                 // Convert the image to BGRA
653                 switch (cinfo.output_components)
654                 {
655                         // RGB images
656                         case 3:
657                                 buffer_ptr = &image_buffer[image_width * line * 4];
658                                 for (ind = 0; ind < image_width * 3; ind += 3, buffer_ptr += 4)
659                                 {
660                                         buffer_ptr[2] = scanline[ind];
661                                         buffer_ptr[1] = scanline[ind + 1];
662                                         buffer_ptr[0] = scanline[ind + 2];
663                                         buffer_ptr[3] = 255;
664                                 }
665                                 break;
666
667                         // Greyscale images (default to it, just in case)
668                         case 1:
669                         default:
670                                 buffer_ptr = &image_buffer[image_width * line * 4];
671                                 for (ind = 0; ind < image_width; ind++, buffer_ptr += 4)
672                                 {
673                                         buffer_ptr[0] = scanline[ind];
674                                         buffer_ptr[1] = scanline[ind];
675                                         buffer_ptr[2] = scanline[ind];
676                                         buffer_ptr[3] = 255;
677                                 }
678                 }
679
680                 line++;
681         }
682         Mem_Free (scanline);
683
684         qjpeg_finish_decompress (&cinfo);
685         qjpeg_destroy_decompress (&cinfo);
686
687         return image_buffer;
688
689 error_caught:
690         if(scanline)
691                 Mem_Free (scanline);
692         if(image_buffer)
693                 Mem_Free (image_buffer);
694         qjpeg_destroy_decompress (&cinfo);
695         return NULL;
696 }
697
698
699 /*
700 =================================================================
701
702   JPEG compression
703
704 =================================================================
705 */
706
707 #define JPEG_OUTPUT_BUF_SIZE 4096
708 static void JPEG_InitDestination (j_compress_ptr cinfo)
709 {
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;
714 }
715
716 static jboolean JPEG_EmptyOutputBuffer (j_compress_ptr cinfo)
717 {
718         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
719
720         if (FS_Write (dest->outfile, dest->buffer, JPEG_OUTPUT_BUF_SIZE) != (size_t) JPEG_OUTPUT_BUF_SIZE)
721                 longjmp(error_in_jpeg, 1);
722
723         dest->pub.next_output_byte = dest->buffer;
724         dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
725         return true;
726 }
727
728 static void JPEG_TermDestination (j_compress_ptr cinfo)
729 {
730         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
731         size_t datacount = JPEG_OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
732
733         // Write any data remaining in the buffer
734         if (datacount > 0)
735                 if (FS_Write (dest->outfile, dest->buffer, datacount) != (fs_offset_t)datacount)
736                         longjmp(error_in_jpeg, 1);
737 }
738
739 static void JPEG_FileDest (j_compress_ptr cinfo, qfile_t* outfile)
740 {
741         my_dest_ptr dest;
742
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));
746
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;
752 }
753
754 static void JPEG_Mem_InitDestination (j_compress_ptr cinfo)
755 {
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;
759 }
760
761 static jboolean JPEG_Mem_EmptyOutputBuffer (j_compress_ptr cinfo)
762 {
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;
767         return true;
768 }
769
770 static void JPEG_Mem_TermDestination (j_compress_ptr cinfo)
771 {
772         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
773         dest->bufsize = dest->pub.next_output_byte - dest->buffer;
774 }
775 static void JPEG_MemDest (j_compress_ptr cinfo, void* buf, size_t bufsize)
776 {
777         my_dest_ptr dest;
778
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));
782
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;
788
789         dest->buffer = (unsigned char *) buf;
790         dest->bufsize = bufsize;
791 }
792
793
794 /*
795 ====================
796 JPEG_SaveImage_preflipped
797
798 Save a preflipped JPEG image to a file
799 ====================
800 */
801 qboolean JPEG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
802 {
803         struct jpeg_compress_struct cinfo;
804         struct jpeg_error_mgr jerr;
805         unsigned char *scanline;
806         unsigned int offset, linesize;
807         qfile_t* file;
808
809         // No DLL = no JPEGs
810         if (!jpeg_dll)
811         {
812                 Con_Print("You need the libjpeg library to save JPEG images\n");
813                 return false;
814         }
815
816         // Open the file
817         file = FS_OpenRealFile(filename, "wb", true);
818         if (!file)
819                 return false;
820
821         if(setjmp(error_in_jpeg))
822                 goto error_caught;
823         cinfo.err = qjpeg_std_error (&jerr);
824         cinfo.err->error_exit = JPEG_ErrorExit;
825
826         qjpeg_create_compress (&cinfo);
827         JPEG_FileDest (&cinfo, file);
828
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);
837
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;
846
847         qjpeg_start_compress (&cinfo, true);
848
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)
853         {
854                 scanline = &data[offset - cinfo.next_scanline * linesize];
855
856                 qjpeg_write_scanlines (&cinfo, &scanline, 1);
857         }
858
859         qjpeg_finish_compress (&cinfo);
860         qjpeg_destroy_compress (&cinfo);
861
862         FS_Close (file);
863         return true;
864
865 error_caught:
866         qjpeg_destroy_compress (&cinfo);
867         FS_Close (file);
868         return false;
869 }
870
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)
872 {
873         unsigned char *scanline;
874         unsigned int linesize;
875
876         jpeg_toolarge = false;
877         JPEG_MemDest (cinfo, jpegbuf, jpegsize);
878
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);
886
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;
894
895         qjpeg_start_compress (cinfo, true);
896
897         // Compress each scanline
898         linesize = width * 3;
899         while (cinfo->next_scanline < cinfo->image_height)
900         {
901                 scanline = &data[cinfo->next_scanline * linesize];
902
903                 qjpeg_write_scanlines (cinfo, &scanline, 1);
904         }
905
906         qjpeg_finish_compress (cinfo);
907
908         if(jpeg_toolarge)
909                 return 0;
910
911         return ((my_dest_ptr) cinfo->dest)->bufsize;
912 }
913
914 size_t JPEG_SaveImage_to_Buffer (char *jpegbuf, size_t jpegsize, int width, int height, unsigned char *data)
915 {
916         struct jpeg_compress_struct cinfo;
917         struct jpeg_error_mgr jerr;
918
919         int quality;
920         int quality_guess;
921         size_t result;
922
923         // No DLL = no JPEGs
924         if (!jpeg_dll)
925         {
926                 Con_Print("You need the libjpeg library to save JPEG images\n");
927                 return false;
928         }
929
930         if(setjmp(error_in_jpeg))
931                 goto error_caught;
932         cinfo.err = qjpeg_std_error (&jerr);
933         cinfo.err->error_exit = JPEG_ErrorExit;
934
935         qjpeg_create_compress (&cinfo);
936
937 #if 0
938         // used to get the formula below
939         {
940                 char buf[1048576];
941                 unsigned char *img;
942                 int i;
943
944                 img = Mem_Alloc(tempmempool, width * height * 3);
945                 for(i = 0; i < width * height * 3; ++i)
946                         img[i] = rand() & 0xFF;
947
948                 for(i = 0; i <= 100; ++i)
949                 {
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));
951                 }
952
953                 Mem_Free(img);
954         }
955 #endif
956
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
959
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
962
963         while(!(result = JPEG_try_SaveImage_to_Buffer(&cinfo, jpegbuf, jpegsize, quality, width, height, data)))
964         {
965                 --quality;
966                 if(quality < 0)
967                 {
968                         Con_Printf("couldn't write image at all, probably too big\n");
969                         return 0;
970                 }
971         }
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);
974
975         return result;
976
977 error_caught:
978         qjpeg_destroy_compress (&cinfo);
979         return 0;
980 }
981
982 typedef struct CompressedImageCacheItem
983 {
984         char imagename[MAX_QPATH];
985         size_t maxsize;
986         void *compressed;
987         size_t compressed_size;
988         struct CompressedImageCacheItem *next;
989 }
990 CompressedImageCacheItem;
991 #define COMPRESSEDIMAGECACHE_SIZE 4096
992 static CompressedImageCacheItem *CompressedImageCache[COMPRESSEDIMAGECACHE_SIZE];
993
994 static void CompressedImageCache_Add(const char *imagename, size_t maxsize, void *compressed, size_t compressed_size)
995 {
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;
999
1000         if(strlen(imagename) >= MAX_QPATH)
1001                 return; // can't add this
1002         
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;
1010 }
1011
1012 static CompressedImageCacheItem *CompressedImageCache_Find(const char *imagename, size_t maxsize)
1013 {
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];
1017
1018         while(i)
1019         {
1020                 if(i->maxsize == maxsize)
1021                         if(!strcmp(i->imagename, imagename))
1022                                 return i;
1023                 i = i->next;
1024         }
1025         return NULL;
1026 }
1027
1028 qboolean Image_Compress(const char *imagename, size_t maxsize, void **buf, size_t *size)
1029 {
1030         unsigned char *imagedata, *newimagedata;
1031         int maxPixelCount;
1032         int components[3] = {2, 1, 0};
1033         CompressedImageCacheItem *i;
1034
1035         JPEG_OpenLibrary (); // for now; LH had the idea of replacing this by a better format
1036         PNG_OpenLibrary (); // for loading
1037
1038         // No DLL = no JPEGs
1039         if (!jpeg_dll)
1040         {
1041                 Con_Print("You need the libjpeg library to save JPEG images\n");
1042                 return false;
1043         }
1044
1045         i = CompressedImageCache_Find(imagename, maxsize);
1046         if(i)
1047         {
1048                 *size = i->compressed_size;
1049                 *buf = i->compressed;
1050         }
1051
1052         // load the image
1053         imagedata = loadimagepixelsbgra(imagename, true, false, false);
1054         if(!imagedata)
1055                 return false;
1056
1057         // find an appropriate size for somewhat okay compression
1058         if(maxsize <= 768)
1059                 maxPixelCount = 32 * 32;
1060         else if(maxsize <= 1024)
1061                 maxPixelCount = 64 * 64;
1062         else if(maxsize <= 4096)
1063                 maxPixelCount = 128 * 128;
1064         else
1065                 maxPixelCount = 256 * 256;
1066
1067         while(image_width * image_height > maxPixelCount)
1068         {
1069                 int one = 1;
1070                 Image_MipReduce32(imagedata, imagedata, &image_width, &image_height, &one, image_width/2, image_height/2, 1);
1071         }
1072
1073         newimagedata = (unsigned char *) Mem_Alloc(tempmempool, image_width * image_height * 3);
1074
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);
1078
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);
1083
1084         if(!*size)
1085         {
1086                 Z_Free(*buf);
1087                 *buf = NULL;
1088                 Con_Printf("could not compress image %s to %d bytes\n", imagename, (int)maxsize);
1089                 // return false;
1090                 // also cache failures!
1091         }
1092
1093         // store it in the cache
1094         CompressedImageCache_Add(imagename, maxsize, *buf, *size);
1095         return (*buf != NULL);
1096 }