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