]> icculus.org git repositories - divverent/darkplaces.git/blob - jpeg.c
+ added bih.c and bih.h files into SDL project file for DevCPP
[divverent/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
29 cvar_t sv_writepicture_quality = {CVAR_SAVE, "sv_writepicture_quality", "10", "WritePicture quality offset (higher means better quality, but slower)"};
30
31 // jboolean is unsigned char instead of int on Win32
32 #ifdef WIN32
33 typedef unsigned char jboolean;
34 #else
35 typedef int jboolean;
36 #endif
37
38 #ifdef LINK_TO_LIBJPEG
39 #include <jpeglib.h>
40 #define qjpeg_create_compress jpeg_create_compress
41 #define qjpeg_create_decompress jpeg_create_decompress
42 #define qjpeg_destroy_compress jpeg_destroy_compress
43 #define qjpeg_destroy_decompress jpeg_destroy_decompress
44 #define qjpeg_finish_compress jpeg_finish_compress
45 #define qjpeg_finish_decompress jpeg_finish_decompress
46 #define qjpeg_resync_to_restart jpeg_resync_to_restart
47 #define qjpeg_read_header jpeg_read_header
48 #define qjpeg_read_scanlines jpeg_read_scanlines
49 #define qjpeg_set_defaults jpeg_set_defaults
50 #define qjpeg_set_quality jpeg_set_quality
51 #define qjpeg_start_compress jpeg_start_compress
52 #define qjpeg_start_decompress jpeg_start_decompress
53 #define qjpeg_std_error jpeg_std_error
54 #define qjpeg_write_scanlines jpeg_write_scanlines
55 #define qjpeg_simple_progression jpeg_simple_progression
56 #define jpeg_dll true
57 #else
58 /*
59 =================================================================
60
61   Minimal set of definitions from the JPEG lib
62
63   WARNING: for a matter of simplicity, several pointer types are
64   casted to "void*", and most enumerated values are not included
65
66 =================================================================
67 */
68
69 typedef void *j_common_ptr;
70 typedef struct jpeg_compress_struct *j_compress_ptr;
71 typedef struct jpeg_decompress_struct *j_decompress_ptr;
72
73 #define JPEG_LIB_VERSION  62  // Version 6b
74
75 typedef enum
76 {
77         JCS_UNKNOWN,
78         JCS_GRAYSCALE,
79         JCS_RGB,
80         JCS_YCbCr,
81         JCS_CMYK,
82         JCS_YCCK
83 } J_COLOR_SPACE;
84 typedef enum {JPEG_DUMMY1} J_DCT_METHOD;
85 typedef enum {JPEG_DUMMY2} J_DITHER_MODE;
86 typedef unsigned int JDIMENSION;
87
88 #define JPOOL_PERMANENT 0       // lasts until master record is destroyed
89 #define JPOOL_IMAGE             1       // lasts until done with image/datastream
90
91 #define JPEG_EOI        0xD9  // EOI marker code
92
93 #define JMSG_STR_PARM_MAX  80
94
95 #define DCTSIZE2 64
96 #define NUM_QUANT_TBLS 4
97 #define NUM_HUFF_TBLS 4
98 #define NUM_ARITH_TBLS 16
99 #define MAX_COMPS_IN_SCAN 4
100 #define C_MAX_BLOCKS_IN_MCU 10
101 #define D_MAX_BLOCKS_IN_MCU 10
102
103 struct jpeg_memory_mgr
104 {
105   void* (*alloc_small) (j_common_ptr cinfo, int pool_id, size_t sizeofobject);
106   void (*_reserve_space_for_alloc_large) (void *dummy, ...);
107   void (*_reserve_space_for_alloc_sarray) (void *dummy, ...);
108   void (*_reserve_space_for_alloc_barray) (void *dummy, ...);
109   void (*_reserve_space_for_request_virt_sarray) (void *dummy, ...);
110   void (*_reserve_space_for_request_virt_barray) (void *dummy, ...);
111   void (*_reserve_space_for_realize_virt_arrays) (void *dummy, ...);
112   void (*_reserve_space_for_access_virt_sarray) (void *dummy, ...);
113   void (*_reserve_space_for_access_virt_barray) (void *dummy, ...);
114   void (*_reserve_space_for_free_pool) (void *dummy, ...);
115   void (*_reserve_space_for_self_destruct) (void *dummy, ...);
116
117   long max_memory_to_use;
118   long max_alloc_chunk;
119 };
120
121 struct jpeg_error_mgr
122 {
123         void (*error_exit) (j_common_ptr cinfo);
124         void (*emit_message) (j_common_ptr cinfo, int msg_level);
125         void (*output_message) (j_common_ptr cinfo);
126         void (*format_message) (j_common_ptr cinfo, char * buffer);
127         void (*reset_error_mgr) (j_common_ptr cinfo);
128         int msg_code;
129         union {
130                 int i[8];
131                 char s[JMSG_STR_PARM_MAX];
132         } msg_parm;
133         int trace_level;
134         long num_warnings;
135         const char * const * jpeg_message_table;
136         int last_jpeg_message;
137         const char * const * addon_message_table;
138         int first_addon_message;
139         int last_addon_message;
140 };
141
142 struct jpeg_source_mgr
143 {
144         const unsigned char *next_input_byte;
145         size_t bytes_in_buffer;
146
147         void (*init_source) (j_decompress_ptr cinfo);
148         jboolean (*fill_input_buffer) (j_decompress_ptr cinfo);
149         void (*skip_input_data) (j_decompress_ptr cinfo, long num_bytes);
150         jboolean (*resync_to_restart) (j_decompress_ptr cinfo, int desired);
151         void (*term_source) (j_decompress_ptr cinfo);
152 };
153
154 typedef struct {
155   /* These values are fixed over the whole image. */
156   /* For compression, they must be supplied by parameter setup; */
157   /* for decompression, they are read from the SOF marker. */
158   int component_id;             /* identifier for this component (0..255) */
159   int component_index;          /* its index in SOF or cinfo->comp_info[] */
160   int h_samp_factor;            /* horizontal sampling factor (1..4) */
161   int v_samp_factor;            /* vertical sampling factor (1..4) */
162   int quant_tbl_no;             /* quantization table selector (0..3) */
163   /* These values may vary between scans. */
164   /* For compression, they must be supplied by parameter setup; */
165   /* for decompression, they are read from the SOS marker. */
166   /* The decompressor output side may not use these variables. */
167   int dc_tbl_no;                /* DC entropy table selector (0..3) */
168   int ac_tbl_no;                /* AC entropy table selector (0..3) */
169   
170   /* Remaining fields should be treated as private by applications. */
171   
172   /* These values are computed during compression or decompression startup: */
173   /* Component's size in DCT blocks.
174    * Any dummy blocks added to complete an MCU are not counted; therefore
175    * these values do not depend on whether a scan is interleaved or not.
176    */
177   JDIMENSION width_in_blocks;
178   JDIMENSION height_in_blocks;
179   /* Size of a DCT block in samples.  Always DCTSIZE for compression.
180    * For decompression this is the size of the output from one DCT block,
181    * reflecting any scaling we choose to apply during the IDCT step.
182    * Values of 1,2,4,8 are likely to be supported.  Note that different
183    * components may receive different IDCT scalings.
184    */
185   int DCT_scaled_size;
186   /* The downsampled dimensions are the component's actual, unpadded number
187    * of samples at the main buffer (preprocessing/compression interface), thus
188    * downsampled_width = ceil(image_width * Hi/Hmax)
189    * and similarly for height.  For decompression, IDCT scaling is included, so
190    * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
191    */
192   JDIMENSION downsampled_width;  /* actual width in samples */
193   JDIMENSION downsampled_height; /* actual height in samples */
194   /* This flag is used only for decompression.  In cases where some of the
195    * components will be ignored (eg grayscale output from YCbCr image),
196    * we can skip most computations for the unused components.
197    */
198   jboolean component_needed;     /* do we need the value of this component? */
199
200   /* These values are computed before starting a scan of the component. */
201   /* The decompressor output side may not use these variables. */
202   int MCU_width;                /* number of blocks per MCU, horizontally */
203   int MCU_height;               /* number of blocks per MCU, vertically */
204   int MCU_blocks;               /* MCU_width * MCU_height */
205   int MCU_sample_width;         /* MCU width in samples, MCU_width*DCT_scaled_size */
206   int last_col_width;           /* # of non-dummy blocks across in last MCU */
207   int last_row_height;          /* # of non-dummy blocks down in last MCU */
208
209   /* Saved quantization table for component; NULL if none yet saved.
210    * See jdinput.c comments about the need for this information.
211    * This field is currently used only for decompression.
212    */
213   void *quant_table;
214
215   /* Private per-component storage for DCT or IDCT subsystem. */
216   void * dct_table;
217 } jpeg_component_info;
218
219 struct jpeg_decompress_struct
220 {
221         struct jpeg_error_mgr *err;             // USED
222         struct jpeg_memory_mgr *mem;    // USED
223
224         void *progress;
225         void *client_data;
226         jboolean is_decompressor;
227         int global_state;
228
229         struct jpeg_source_mgr *src;    // USED
230         JDIMENSION image_width;                 // USED
231         JDIMENSION image_height;                // USED
232
233         int num_components;
234         J_COLOR_SPACE jpeg_color_space;
235         J_COLOR_SPACE out_color_space;
236         unsigned int scale_num, scale_denom;
237         double output_gamma;
238         jboolean buffered_image;
239         jboolean raw_data_out;
240         J_DCT_METHOD dct_method;
241         jboolean do_fancy_upsampling;
242         jboolean do_block_smoothing;
243         jboolean quantize_colors;
244         J_DITHER_MODE dither_mode;
245         jboolean two_pass_quantize;
246         int desired_number_of_colors;
247         jboolean enable_1pass_quant;
248         jboolean enable_external_quant;
249         jboolean enable_2pass_quant;
250         JDIMENSION output_width;
251
252         JDIMENSION output_height;       // USED
253
254         int out_color_components;
255
256         int output_components;          // USED
257
258         int rec_outbuf_height;
259         int actual_number_of_colors;
260         void *colormap;
261
262         JDIMENSION output_scanline;     // USED
263
264         int input_scan_number;
265         JDIMENSION input_iMCU_row;
266         int output_scan_number;
267         JDIMENSION output_iMCU_row;
268         int (*coef_bits)[DCTSIZE2];
269         void *quant_tbl_ptrs[NUM_QUANT_TBLS];
270         void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
271         void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
272         int data_precision;
273         jpeg_component_info *comp_info;
274         jboolean progressive_mode;
275         jboolean arith_code;
276         unsigned char arith_dc_L[NUM_ARITH_TBLS];
277         unsigned char arith_dc_U[NUM_ARITH_TBLS];
278         unsigned char arith_ac_K[NUM_ARITH_TBLS];
279         unsigned int restart_interval;
280         jboolean saw_JFIF_marker;
281         unsigned char JFIF_major_version;
282         unsigned char JFIF_minor_version;
283         unsigned char density_unit;
284         unsigned short X_density;
285         unsigned short Y_density;
286         jboolean saw_Adobe_marker;
287         unsigned char Adobe_transform;
288         jboolean CCIR601_sampling;
289         void *marker_list;
290         int max_h_samp_factor;
291         int max_v_samp_factor;
292         int min_DCT_scaled_size;
293         JDIMENSION total_iMCU_rows;
294         void *sample_range_limit;
295         int comps_in_scan;
296         jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
297         JDIMENSION MCUs_per_row;
298         JDIMENSION MCU_rows_in_scan;
299         int blocks_in_MCU;
300         int MCU_membership[D_MAX_BLOCKS_IN_MCU];
301         int Ss, Se, Ah, Al;
302         int unread_marker;
303         void *master;
304         void *main;
305         void *coef;
306         void *post;
307         void *inputctl;
308         void *marker;
309         void *entropy;
310         void *idct;
311         void *upsample;
312         void *cconvert;
313         void *cquantize;
314 };
315
316
317 struct jpeg_compress_struct
318 {
319         struct jpeg_error_mgr *err;
320         struct jpeg_memory_mgr *mem;
321         void *progress;
322         void *client_data;
323         jboolean is_decompressor;
324         int global_state;
325
326         void *dest;
327         JDIMENSION image_width;
328         JDIMENSION image_height;
329         int input_components;
330         J_COLOR_SPACE in_color_space;
331         double input_gamma;
332         int data_precision;
333
334         int num_components;
335         J_COLOR_SPACE jpeg_color_space;
336         jpeg_component_info *comp_info;
337         void *quant_tbl_ptrs[NUM_QUANT_TBLS];
338         void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
339         void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
340         unsigned char arith_dc_L[NUM_ARITH_TBLS];
341         unsigned char arith_dc_U[NUM_ARITH_TBLS];
342         unsigned char arith_ac_K[NUM_ARITH_TBLS];
343
344         int num_scans;
345         const void *scan_info;
346         jboolean raw_data_in;
347         jboolean arith_code;
348         jboolean optimize_coding;
349         jboolean CCIR601_sampling;
350         int smoothing_factor;
351         J_DCT_METHOD dct_method;
352
353         unsigned int restart_interval;
354         int restart_in_rows;
355
356         jboolean write_JFIF_header;
357         unsigned char JFIF_major_version;
358         unsigned char JFIF_minor_version;
359         unsigned char density_unit;
360         unsigned short X_density;
361         unsigned short Y_density;
362         jboolean write_Adobe_marker;
363         JDIMENSION next_scanline;
364
365         jboolean progressive_mode;
366         int max_h_samp_factor;
367         int max_v_samp_factor;
368         JDIMENSION total_iMCU_rows;
369         int comps_in_scan;
370         jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN];
371         JDIMENSION MCUs_per_row;
372         JDIMENSION MCU_rows_in_scan;
373         int blocks_in_MCU;
374         int MCU_membership[C_MAX_BLOCKS_IN_MCU];
375         int Ss, Se, Ah, Al;
376
377         void *master;
378         void *main;
379         void *prep;
380         void *coef;
381         void *marker;
382         void *cconvert;
383         void *downsample;
384         void *fdct;
385         void *entropy;
386         void *script_space;
387         int script_space_size;
388 };
389
390 struct jpeg_destination_mgr
391 {
392         unsigned char* next_output_byte;
393         size_t free_in_buffer;
394
395         void (*init_destination) (j_compress_ptr cinfo);
396         jboolean (*empty_output_buffer) (j_compress_ptr cinfo);
397         void (*term_destination) (j_compress_ptr cinfo);
398 };
399
400
401 /*
402 =================================================================
403
404   DarkPlaces definitions
405
406 =================================================================
407 */
408
409 // Functions exported from libjpeg
410 #define qjpeg_create_compress(cinfo) \
411         qjpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_compress_struct))
412 #define qjpeg_create_decompress(cinfo) \
413         qjpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_decompress_struct))
414
415 static void (*qjpeg_CreateCompress) (j_compress_ptr cinfo, int version, size_t structsize);
416 static void (*qjpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize);
417 static void (*qjpeg_destroy_compress) (j_compress_ptr cinfo);
418 static void (*qjpeg_destroy_decompress) (j_decompress_ptr cinfo);
419 static void (*qjpeg_finish_compress) (j_compress_ptr cinfo);
420 static jboolean (*qjpeg_finish_decompress) (j_decompress_ptr cinfo);
421 static jboolean (*qjpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired);
422 static int (*qjpeg_read_header) (j_decompress_ptr cinfo, jboolean require_image);
423 static JDIMENSION (*qjpeg_read_scanlines) (j_decompress_ptr cinfo, unsigned char** scanlines, JDIMENSION max_lines);
424 static void (*qjpeg_set_defaults) (j_compress_ptr cinfo);
425 static void (*qjpeg_set_quality) (j_compress_ptr cinfo, int quality, jboolean force_baseline);
426 static jboolean (*qjpeg_start_compress) (j_compress_ptr cinfo, jboolean write_all_tables);
427 static jboolean (*qjpeg_start_decompress) (j_decompress_ptr cinfo);
428 static struct jpeg_error_mgr* (*qjpeg_std_error) (struct jpeg_error_mgr *err);
429 static JDIMENSION (*qjpeg_write_scanlines) (j_compress_ptr cinfo, unsigned char** scanlines, JDIMENSION num_lines);
430 static void (*qjpeg_simple_progression) (j_compress_ptr cinfo);
431
432 static dllfunction_t jpegfuncs[] =
433 {
434         {"jpeg_CreateCompress",         (void **) &qjpeg_CreateCompress},
435         {"jpeg_CreateDecompress",       (void **) &qjpeg_CreateDecompress},
436         {"jpeg_destroy_compress",       (void **) &qjpeg_destroy_compress},
437         {"jpeg_destroy_decompress",     (void **) &qjpeg_destroy_decompress},
438         {"jpeg_finish_compress",        (void **) &qjpeg_finish_compress},
439         {"jpeg_finish_decompress",      (void **) &qjpeg_finish_decompress},
440         {"jpeg_resync_to_restart",      (void **) &qjpeg_resync_to_restart},
441         {"jpeg_read_header",            (void **) &qjpeg_read_header},
442         {"jpeg_read_scanlines",         (void **) &qjpeg_read_scanlines},
443         {"jpeg_set_defaults",           (void **) &qjpeg_set_defaults},
444         {"jpeg_set_quality",            (void **) &qjpeg_set_quality},
445         {"jpeg_start_compress",         (void **) &qjpeg_start_compress},
446         {"jpeg_start_decompress",       (void **) &qjpeg_start_decompress},
447         {"jpeg_std_error",                      (void **) &qjpeg_std_error},
448         {"jpeg_write_scanlines",        (void **) &qjpeg_write_scanlines},
449         {"jpeg_simple_progression",     (void **) &qjpeg_simple_progression},
450         {NULL, NULL}
451 };
452
453 // Handle for JPEG DLL
454 dllhandle_t jpeg_dll = NULL;
455 qboolean jpeg_tried_loading = 0;
456 #endif
457
458 static unsigned char jpeg_eoi_marker [2] = {0xFF, JPEG_EOI};
459 static jmp_buf error_in_jpeg;
460 static qboolean jpeg_toolarge;
461
462 // Our own output manager for JPEG compression
463 typedef struct
464 {
465         struct jpeg_destination_mgr pub;
466
467         qfile_t* outfile;
468         unsigned char* buffer;
469         size_t bufsize; // used if outfile is NULL
470 } my_destination_mgr;
471 typedef my_destination_mgr* my_dest_ptr;
472
473
474 /*
475 =================================================================
476
477   DLL load & unload
478
479 =================================================================
480 */
481
482 /*
483 ====================
484 JPEG_OpenLibrary
485
486 Try to load the JPEG DLL
487 ====================
488 */
489 qboolean JPEG_OpenLibrary (void)
490 {
491 #ifdef LINK_TO_LIBJPEG
492         return true;
493 #else
494         const char* dllnames [] =
495         {
496 #if defined(WIN32)
497                 "libjpeg.dll",
498 #elif defined(MACOSX)
499                 "libjpeg.62.dylib",
500 #else
501                 "libjpeg.so.62",
502                 "libjpeg.so",
503 #endif
504                 NULL
505         };
506
507         // Already loaded?
508         if (jpeg_dll)
509                 return true;
510
511         if (jpeg_tried_loading) // only try once
512                 return false;
513
514         jpeg_tried_loading = true;
515
516         // Load the DLL
517         return Sys_LoadLibrary (dllnames, &jpeg_dll, jpegfuncs);
518 #endif
519 }
520
521
522 /*
523 ====================
524 JPEG_CloseLibrary
525
526 Unload the JPEG DLL
527 ====================
528 */
529 void JPEG_CloseLibrary (void)
530 {
531 #ifndef LINK_TO_LIBJPEG
532         Sys_UnloadLibrary (&jpeg_dll);
533         jpeg_tried_loading = false; // allow retry
534 #endif
535 }
536
537
538 /*
539 =================================================================
540
541         JPEG decompression
542
543 =================================================================
544 */
545
546 static void JPEG_Noop (j_decompress_ptr cinfo) {}
547
548 static jboolean JPEG_FillInputBuffer (j_decompress_ptr cinfo)
549 {
550     // Insert a fake EOI marker
551     cinfo->src->next_input_byte = jpeg_eoi_marker;
552     cinfo->src->bytes_in_buffer = 2;
553
554         return TRUE;
555 }
556
557 static void JPEG_SkipInputData (j_decompress_ptr cinfo, long num_bytes)
558 {
559     if (cinfo->src->bytes_in_buffer <= (unsigned long)num_bytes)
560         {
561                 cinfo->src->bytes_in_buffer = 0;
562                 return;
563         }
564
565     cinfo->src->next_input_byte += num_bytes;
566     cinfo->src->bytes_in_buffer -= num_bytes;
567 }
568
569 static void JPEG_MemSrc (j_decompress_ptr cinfo, const unsigned char *buffer, size_t filesize)
570 {
571         cinfo->src = (struct jpeg_source_mgr *)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
572
573         cinfo->src->next_input_byte = buffer;
574         cinfo->src->bytes_in_buffer = filesize;
575
576         cinfo->src->init_source = JPEG_Noop;
577         cinfo->src->fill_input_buffer = JPEG_FillInputBuffer;
578         cinfo->src->skip_input_data = JPEG_SkipInputData;
579         cinfo->src->resync_to_restart = qjpeg_resync_to_restart; // use the default method
580         cinfo->src->term_source = JPEG_Noop;
581 }
582
583 static void JPEG_ErrorExit (j_common_ptr cinfo)
584 {
585         ((struct jpeg_decompress_struct*)cinfo)->err->output_message (cinfo);
586         longjmp(error_in_jpeg, 1);
587 }
588
589
590 /*
591 ====================
592 JPEG_LoadImage
593
594 Load a JPEG image into a BGRA buffer
595 ====================
596 */
597 unsigned char* JPEG_LoadImage_BGRA (const unsigned char *f, int filesize)
598 {
599         struct jpeg_decompress_struct cinfo;
600         struct jpeg_error_mgr jerr;
601         unsigned char *image_buffer = NULL, *scanline = NULL;
602         unsigned int line;
603
604         // No DLL = no JPEGs
605         if (!jpeg_dll)
606                 return NULL;
607
608         cinfo.err = qjpeg_std_error (&jerr);
609         qjpeg_create_decompress (&cinfo);
610         if(setjmp(error_in_jpeg))
611                 goto error_caught;
612         cinfo.err = qjpeg_std_error (&jerr);
613         cinfo.err->error_exit = JPEG_ErrorExit;
614         JPEG_MemSrc (&cinfo, f, filesize);
615         qjpeg_read_header (&cinfo, TRUE);
616         qjpeg_start_decompress (&cinfo);
617
618         image_width = cinfo.image_width;
619         image_height = cinfo.image_height;
620
621         if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
622         {
623                 Con_Printf("JPEG_LoadImage: invalid image size %ix%i\n", image_width, image_height);
624                 return NULL;
625         }
626
627         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
628         scanline = (unsigned char *)Mem_Alloc(tempmempool, image_width * cinfo.output_components);
629         if (!image_buffer || !scanline)
630         {
631                 if (image_buffer)
632                         Mem_Free (image_buffer);
633                 if (scanline)
634                         Mem_Free (scanline);
635
636                 Con_Printf("JPEG_LoadImage: not enough memory for %i by %i image\n", image_width, image_height);
637                 qjpeg_finish_decompress (&cinfo);
638                 qjpeg_destroy_decompress (&cinfo);
639                 return NULL;
640         }
641
642         // Decompress the image, line by line
643         line = 0;
644         while (cinfo.output_scanline < cinfo.output_height)
645         {
646                 unsigned char *buffer_ptr;
647                 int ind;
648
649                 qjpeg_read_scanlines (&cinfo, &scanline, 1);
650
651                 // Convert the image to BGRA
652                 switch (cinfo.output_components)
653                 {
654                         // RGB images
655                         case 3:
656                                 buffer_ptr = &image_buffer[image_width * line * 4];
657                                 for (ind = 0; ind < image_width * 3; ind += 3, buffer_ptr += 4)
658                                 {
659                                         buffer_ptr[2] = scanline[ind];
660                                         buffer_ptr[1] = scanline[ind + 1];
661                                         buffer_ptr[0] = scanline[ind + 2];
662                                         buffer_ptr[3] = 255;
663                                 }
664                                 break;
665
666                         // Greyscale images (default to it, just in case)
667                         case 1:
668                         default:
669                                 buffer_ptr = &image_buffer[image_width * line * 4];
670                                 for (ind = 0; ind < image_width; ind++, buffer_ptr += 4)
671                                 {
672                                         buffer_ptr[0] = scanline[ind];
673                                         buffer_ptr[1] = scanline[ind];
674                                         buffer_ptr[2] = scanline[ind];
675                                         buffer_ptr[3] = 255;
676                                 }
677                 }
678
679                 line++;
680         }
681         Mem_Free (scanline);
682
683         qjpeg_finish_decompress (&cinfo);
684         qjpeg_destroy_decompress (&cinfo);
685
686         return image_buffer;
687
688 error_caught:
689         if(scanline)
690                 Mem_Free (scanline);
691         if(image_buffer)
692                 Mem_Free (image_buffer);
693         qjpeg_destroy_decompress (&cinfo);
694         return NULL;
695 }
696
697
698 /*
699 =================================================================
700
701   JPEG compression
702
703 =================================================================
704 */
705
706 #define JPEG_OUTPUT_BUF_SIZE 4096
707 static void JPEG_InitDestination (j_compress_ptr cinfo)
708 {
709         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
710         dest->buffer = (unsigned char*)cinfo->mem->alloc_small ((j_common_ptr) cinfo, JPOOL_IMAGE, JPEG_OUTPUT_BUF_SIZE * sizeof(unsigned char));
711         dest->pub.next_output_byte = dest->buffer;
712         dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
713 }
714
715 static jboolean JPEG_EmptyOutputBuffer (j_compress_ptr cinfo)
716 {
717         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
718
719         if (FS_Write (dest->outfile, dest->buffer, JPEG_OUTPUT_BUF_SIZE) != (size_t) JPEG_OUTPUT_BUF_SIZE)
720                 longjmp(error_in_jpeg, 1);
721
722         dest->pub.next_output_byte = dest->buffer;
723         dest->pub.free_in_buffer = JPEG_OUTPUT_BUF_SIZE;
724         return true;
725 }
726
727 static void JPEG_TermDestination (j_compress_ptr cinfo)
728 {
729         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
730         size_t datacount = JPEG_OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
731
732         // Write any data remaining in the buffer
733         if (datacount > 0)
734                 if (FS_Write (dest->outfile, dest->buffer, datacount) != (fs_offset_t)datacount)
735                         longjmp(error_in_jpeg, 1);
736 }
737
738 static void JPEG_FileDest (j_compress_ptr cinfo, qfile_t* outfile)
739 {
740         my_dest_ptr dest;
741
742         // First time for this JPEG object?
743         if (cinfo->dest == NULL)
744                 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
745
746         dest = (my_dest_ptr)cinfo->dest;
747         dest->pub.init_destination = JPEG_InitDestination;
748         dest->pub.empty_output_buffer = JPEG_EmptyOutputBuffer;
749         dest->pub.term_destination = JPEG_TermDestination;
750         dest->outfile = outfile;
751 }
752
753 static void JPEG_Mem_InitDestination (j_compress_ptr cinfo)
754 {
755         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
756         dest->pub.next_output_byte = dest->buffer;
757         dest->pub.free_in_buffer = dest->bufsize;
758 }
759
760 static jboolean JPEG_Mem_EmptyOutputBuffer (j_compress_ptr cinfo)
761 {
762         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
763         jpeg_toolarge = true;
764         dest->pub.next_output_byte = dest->buffer;
765         dest->pub.free_in_buffer = dest->bufsize;
766         return true;
767 }
768
769 static void JPEG_Mem_TermDestination (j_compress_ptr cinfo)
770 {
771         my_dest_ptr dest = (my_dest_ptr)cinfo->dest;
772         dest->bufsize = dest->pub.next_output_byte - dest->buffer;
773 }
774 static void JPEG_MemDest (j_compress_ptr cinfo, void* buf, size_t bufsize)
775 {
776         my_dest_ptr dest;
777
778         // First time for this JPEG object?
779         if (cinfo->dest == NULL)
780                 cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr));
781
782         dest = (my_dest_ptr)cinfo->dest;
783         dest->pub.init_destination = JPEG_Mem_InitDestination;
784         dest->pub.empty_output_buffer = JPEG_Mem_EmptyOutputBuffer;
785         dest->pub.term_destination = JPEG_Mem_TermDestination;
786         dest->outfile = NULL;
787
788         dest->buffer = (unsigned char *) buf;
789         dest->bufsize = bufsize;
790 }
791
792
793 /*
794 ====================
795 JPEG_SaveImage_preflipped
796
797 Save a preflipped JPEG image to a file
798 ====================
799 */
800 qboolean JPEG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
801 {
802         struct jpeg_compress_struct cinfo;
803         struct jpeg_error_mgr jerr;
804         unsigned char *scanline;
805         unsigned int offset, linesize;
806         qfile_t* file;
807
808         // No DLL = no JPEGs
809         if (!jpeg_dll)
810         {
811                 Con_Print("You need the libjpeg library to save JPEG images\n");
812                 return false;
813         }
814
815         // Open the file
816         file = FS_OpenRealFile(filename, "wb", true);
817         if (!file)
818                 return false;
819
820         if(setjmp(error_in_jpeg))
821                 goto error_caught;
822         cinfo.err = qjpeg_std_error (&jerr);
823         cinfo.err->error_exit = JPEG_ErrorExit;
824
825         qjpeg_create_compress (&cinfo);
826         JPEG_FileDest (&cinfo, file);
827
828         // Set the parameters for compression
829         cinfo.image_width = width;
830         cinfo.image_height = height;
831         cinfo.in_color_space = JCS_RGB;
832         cinfo.input_components = 3;
833         qjpeg_set_defaults (&cinfo);
834         qjpeg_set_quality (&cinfo, (int)(scr_screenshot_jpeg_quality.value * 100), TRUE);
835         qjpeg_simple_progression (&cinfo);
836
837         // turn off subsampling (to make text look better)
838         cinfo.optimize_coding = 1;
839         cinfo.comp_info[0].h_samp_factor = 1;
840         cinfo.comp_info[0].v_samp_factor = 1;
841         cinfo.comp_info[1].h_samp_factor = 1;
842         cinfo.comp_info[1].v_samp_factor = 1;
843         cinfo.comp_info[2].h_samp_factor = 1;
844         cinfo.comp_info[2].v_samp_factor = 1;
845
846         qjpeg_start_compress (&cinfo, true);
847
848         // Compress each scanline
849         linesize = cinfo.image_width * 3;
850         offset = linesize * (cinfo.image_height - 1);
851         while (cinfo.next_scanline < cinfo.image_height)
852         {
853                 scanline = &data[offset - cinfo.next_scanline * linesize];
854
855                 qjpeg_write_scanlines (&cinfo, &scanline, 1);
856         }
857
858         qjpeg_finish_compress (&cinfo);
859         qjpeg_destroy_compress (&cinfo);
860
861         FS_Close (file);
862         return true;
863
864 error_caught:
865         qjpeg_destroy_compress (&cinfo);
866         FS_Close (file);
867         return false;
868 }
869
870 static size_t JPEG_try_SaveImage_to_Buffer (struct jpeg_compress_struct *cinfo, char *jpegbuf, size_t jpegsize, int quality, int width, int height, unsigned char *data)
871 {
872         unsigned char *scanline;
873         unsigned int linesize;
874
875         jpeg_toolarge = false;
876         JPEG_MemDest (cinfo, jpegbuf, jpegsize);
877
878         // Set the parameters for compression
879         cinfo->image_width = width;
880         cinfo->image_height = height;
881         cinfo->in_color_space = JCS_RGB;
882         cinfo->input_components = 3;
883         qjpeg_set_defaults (cinfo);
884         qjpeg_set_quality (cinfo, quality, FALSE);
885
886         cinfo->comp_info[0].h_samp_factor = 2;
887         cinfo->comp_info[0].v_samp_factor = 2;
888         cinfo->comp_info[1].h_samp_factor = 1;
889         cinfo->comp_info[1].v_samp_factor = 1;
890         cinfo->comp_info[2].h_samp_factor = 1;
891         cinfo->comp_info[2].v_samp_factor = 1;
892         cinfo->optimize_coding = 1;
893
894         qjpeg_start_compress (cinfo, true);
895
896         // Compress each scanline
897         linesize = width * 3;
898         while (cinfo->next_scanline < cinfo->image_height)
899         {
900                 scanline = &data[cinfo->next_scanline * linesize];
901
902                 qjpeg_write_scanlines (cinfo, &scanline, 1);
903         }
904
905         qjpeg_finish_compress (cinfo);
906
907         if(jpeg_toolarge)
908                 return 0;
909
910         return ((my_dest_ptr) cinfo->dest)->bufsize;
911 }
912
913 size_t JPEG_SaveImage_to_Buffer (char *jpegbuf, size_t jpegsize, int width, int height, unsigned char *data)
914 {
915         struct jpeg_compress_struct cinfo;
916         struct jpeg_error_mgr jerr;
917
918         int quality;
919         int quality_guess;
920         size_t result;
921
922         // No DLL = no JPEGs
923         if (!jpeg_dll)
924         {
925                 Con_Print("You need the libjpeg library to save JPEG images\n");
926                 return false;
927         }
928
929         if(setjmp(error_in_jpeg))
930                 goto error_caught;
931         cinfo.err = qjpeg_std_error (&jerr);
932         cinfo.err->error_exit = JPEG_ErrorExit;
933
934         qjpeg_create_compress (&cinfo);
935
936 #if 0
937         // used to get the formula below
938         {
939                 char buf[1048576];
940                 unsigned char *img;
941                 int i;
942
943                 img = Mem_Alloc(tempmempool, width * height * 3);
944                 for(i = 0; i < width * height * 3; ++i)
945                         img[i] = rand() & 0xFF;
946
947                 for(i = 0; i <= 100; ++i)
948                 {
949                         Con_Printf("! %d %d %d %d\n", width, height, i, (int) JPEG_try_SaveImage_to_Buffer(&cinfo, buf, sizeof(buf), i, width, height, img));
950                 }
951
952                 Mem_Free(img);
953         }
954 #endif
955
956         //quality_guess = (100 * jpegsize - 41000) / (width*height) + 2; // fits random data
957         quality_guess   = (256 * jpegsize - 81920) / (width*height) - 8; // fits Nexuiz's map pictures
958
959         quality_guess = bound(0, quality_guess, 100);
960         quality = bound(0, quality_guess + sv_writepicture_quality.integer, 100); // assume it can do 10 failed attempts
961
962         while(!(result = JPEG_try_SaveImage_to_Buffer(&cinfo, jpegbuf, jpegsize, quality, width, height, data)))
963         {
964                 --quality;
965                 if(quality < 0)
966                 {
967                         Con_Printf("couldn't write image at all, probably too big\n");
968                         return 0;
969                 }
970         }
971         qjpeg_destroy_compress (&cinfo);
972         Con_DPrintf("JPEG_SaveImage_to_Buffer: guessed quality/size %d/%d, actually got %d/%d\n", quality_guess, (int)jpegsize, quality, (int)result);
973
974         return result;
975
976 error_caught:
977         qjpeg_destroy_compress (&cinfo);
978         return 0;
979 }
980
981 typedef struct CompressedImageCacheItem
982 {
983         char imagename[MAX_QPATH];
984         size_t maxsize;
985         void *compressed;
986         size_t compressed_size;
987         struct CompressedImageCacheItem *next;
988 }
989 CompressedImageCacheItem;
990 #define COMPRESSEDIMAGECACHE_SIZE 4096
991 static CompressedImageCacheItem *CompressedImageCache[COMPRESSEDIMAGECACHE_SIZE];
992
993 static void CompressedImageCache_Add(const char *imagename, size_t maxsize, void *compressed, size_t compressed_size)
994 {
995         const char *hashkey = va("%s:%d", imagename, (int) maxsize);
996         int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
997         CompressedImageCacheItem *i;
998
999         if(strlen(imagename) >= MAX_QPATH)
1000                 return; // can't add this
1001         
1002         i = (CompressedImageCacheItem*) Z_Malloc(sizeof(CompressedImageCacheItem));
1003         strlcpy(i->imagename, imagename, sizeof(i->imagename));
1004         i->maxsize = maxsize;
1005         i->compressed = compressed;
1006         i->compressed_size = compressed_size;
1007         i->next = CompressedImageCache[hashindex];
1008         CompressedImageCache[hashindex] = i;
1009 }
1010
1011 static CompressedImageCacheItem *CompressedImageCache_Find(const char *imagename, size_t maxsize)
1012 {
1013         const char *hashkey = va("%s:%d", imagename, (int) maxsize);
1014         int hashindex = CRC_Block((unsigned char *) hashkey, strlen(hashkey)) % COMPRESSEDIMAGECACHE_SIZE;
1015         CompressedImageCacheItem *i = CompressedImageCache[hashindex];
1016
1017         while(i)
1018         {
1019                 if(i->maxsize == maxsize)
1020                         if(!strcmp(i->imagename, imagename))
1021                                 return i;
1022                 i = i->next;
1023         }
1024         return NULL;
1025 }
1026
1027 qboolean Image_Compress(const char *imagename, size_t maxsize, void **buf, size_t *size)
1028 {
1029         unsigned char *imagedata, *newimagedata;
1030         int maxPixelCount;
1031         int components[3] = {2, 1, 0};
1032         CompressedImageCacheItem *i;
1033
1034         JPEG_OpenLibrary (); // for now; LH had the idea of replacing this by a better format
1035
1036         // No DLL = no JPEGs
1037         if (!jpeg_dll)
1038         {
1039                 Con_Print("You need the libjpeg library to save JPEG images\n");
1040                 return false;
1041         }
1042
1043         i = CompressedImageCache_Find(imagename, maxsize);
1044         if(i)
1045         {
1046                 *size = i->compressed_size;
1047                 *buf = i->compressed;
1048         }
1049
1050         // load the image
1051         imagedata = loadimagepixelsbgra(imagename, true, false, false);
1052         if(!imagedata)
1053                 return false;
1054
1055         // find an appropriate size for somewhat okay compression
1056         if(maxsize <= 768)
1057                 maxPixelCount = 32 * 32;
1058         else if(maxsize <= 1024)
1059                 maxPixelCount = 64 * 64;
1060         else if(maxsize <= 4096)
1061                 maxPixelCount = 128 * 128;
1062         else
1063                 maxPixelCount = 256 * 256;
1064
1065         while(image_width * image_height > maxPixelCount)
1066         {
1067                 int one = 1;
1068                 Image_MipReduce32(imagedata, imagedata, &image_width, &image_height, &one, image_width/2, image_height/2, 1);
1069         }
1070
1071         newimagedata = (unsigned char *) Mem_Alloc(tempmempool, image_width * image_height * 3);
1072
1073         // convert the image from BGRA to RGB
1074         Image_CopyMux(newimagedata, imagedata, image_width, image_height, false, false, false, 3, 4, components);
1075         Mem_Free(imagedata);
1076
1077         // try to compress it to JPEG
1078         *buf = Z_Malloc(maxsize);
1079         *size = JPEG_SaveImage_to_Buffer((char *) *buf, maxsize, image_width, image_height, newimagedata);
1080         Mem_Free(newimagedata);
1081
1082         if(!*size)
1083         {
1084                 Z_Free(*buf);
1085                 *buf = NULL;
1086                 Con_Printf("could not compress image %s to %d bytes\n", imagename, (int)maxsize);
1087                 // return false;
1088                 // also cache failures!
1089         }
1090
1091         // store it in the cache
1092         CompressedImageCache_Add(imagename, maxsize, *buf, *size);
1093         return (*buf != NULL);
1094 }