Elric's changes:
[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 "jpeg.h"
27
28 // LordHavoc: Elric's jpeg structs conflict with Linux ones (mainly on the definition of boolean being qbyte instead of int)
29 #ifdef WIN32
30 typedef qbyte boolean;
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 #define JPEG_LIB_VERSION  62  // Version 6b
43
44 typedef void *j_common_ptr;
45 typedef struct jpeg_decompress_struct *j_decompress_ptr;
46 typedef enum {JPEG_DUMMY1} J_COLOR_SPACE;
47 typedef enum {JPEG_DUMMY2} J_DCT_METHOD;
48 typedef enum {JPEG_DUMMY3} J_DITHER_MODE;
49 typedef unsigned int JDIMENSION;
50
51 #define JPOOL_PERMANENT 0
52
53 #define JPEG_EOI        0xD9  // EOI marker code
54
55 #define JMSG_STR_PARM_MAX  80
56
57 #define DCTSIZE2 64
58 #define NUM_QUANT_TBLS 4
59 #define NUM_HUFF_TBLS 4
60 #define NUM_ARITH_TBLS 16
61 #define MAX_COMPS_IN_SCAN 4
62 #define D_MAX_BLOCKS_IN_MCU 10
63
64 struct jpeg_memory_mgr
65 {
66   void* (*alloc_small) (j_common_ptr cinfo, int pool_id, size_t sizeofobject);
67   void (*alloc_large) ();
68   void (*alloc_sarray) ();
69   void (*alloc_barray) ();
70   void (*request_virt_sarray) ();
71   void (*request_virt_barray) ();
72   void (*realize_virt_arrays) ();
73   void (*access_virt_sarray) ();
74   void (*access_virt_barray) ();
75   void (*free_pool) ();
76   void (*self_destruct) ();
77
78   long max_memory_to_use;
79   long max_alloc_chunk;
80 };
81
82 struct jpeg_error_mgr
83 {
84         void (*error_exit) (j_common_ptr cinfo);
85         void (*emit_message) (j_common_ptr cinfo, int msg_level);
86         void (*output_message) (j_common_ptr cinfo);
87         void (*format_message) (j_common_ptr cinfo, char * buffer);
88         void (*reset_error_mgr) (j_common_ptr cinfo);
89         int msg_code;
90         union {
91                 int i[8];
92                 char s[JMSG_STR_PARM_MAX];
93         } msg_parm;
94         int trace_level;
95         long num_warnings;
96         const char * const * jpeg_message_table;
97         int last_jpeg_message;
98         const char * const * addon_message_table;
99         int first_addon_message;
100         int last_addon_message;
101 };
102
103 struct jpeg_source_mgr
104 {
105         const qbyte *next_input_byte;
106         size_t bytes_in_buffer;
107
108         void (*init_source) (j_decompress_ptr cinfo);
109         qbyte (*fill_input_buffer) (j_decompress_ptr cinfo);
110         void (*skip_input_data) (j_decompress_ptr cinfo, long num_bytes);
111         qbyte (*resync_to_restart) (j_decompress_ptr cinfo, int desired);
112         void (*term_source) (j_decompress_ptr cinfo);
113 };
114
115 struct jpeg_decompress_struct
116 {
117         struct jpeg_error_mgr *err;             // USED
118         struct jpeg_memory_mgr *mem;    // USED
119
120         void *progress;
121         void *client_data;
122         qbyte is_decompressor;
123         int global_state;
124
125         struct jpeg_source_mgr *src;    // USED
126         JDIMENSION image_width;                 // USED
127         JDIMENSION image_height;                // USED
128
129         int num_components;
130         J_COLOR_SPACE jpeg_color_space;
131         J_COLOR_SPACE out_color_space;
132         unsigned int scale_num, scale_denom;
133         double output_gamma;
134         qbyte buffered_image;
135         qbyte raw_data_out;
136         J_DCT_METHOD dct_method;
137         qbyte do_fancy_upsampling;
138         qbyte do_block_smoothing;
139         qbyte quantize_colors;
140         J_DITHER_MODE dither_mode;
141         qbyte two_pass_quantize;
142         int desired_number_of_colors;
143         qbyte enable_1pass_quant;
144         qbyte enable_external_quant;
145         qbyte enable_2pass_quant;
146         JDIMENSION output_width;
147
148         JDIMENSION output_height;       // USED
149
150         int out_color_components;
151
152         int output_components;          // USED
153
154         int rec_outbuf_height;
155         int actual_number_of_colors;
156         void *colormap;
157
158         JDIMENSION output_scanline;     // USED
159
160         int input_scan_number;
161         JDIMENSION input_iMCU_row;
162         int output_scan_number;
163         JDIMENSION output_iMCU_row;
164         int (*coef_bits)[DCTSIZE2];
165         void *quant_tbl_ptrs[NUM_QUANT_TBLS];
166         void *dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
167         void *ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
168         int data_precision;
169         void *comp_info;
170         qbyte progressive_mode;
171         qbyte arith_code;
172         qbyte arith_dc_L[NUM_ARITH_TBLS];
173         qbyte arith_dc_U[NUM_ARITH_TBLS];
174         qbyte arith_ac_K[NUM_ARITH_TBLS];
175         unsigned int restart_interval;
176         qbyte saw_JFIF_marker;
177         qbyte JFIF_major_version;
178         qbyte JFIF_minor_version;
179         qbyte density_unit;
180         unsigned short X_density;
181         unsigned short Y_density;
182         qbyte saw_Adobe_marker;
183         qbyte Adobe_transform;
184         qbyte CCIR601_sampling;
185         void *marker_list;
186         int max_h_samp_factor;
187         int max_v_samp_factor;
188         int min_DCT_scaled_size;
189         JDIMENSION total_iMCU_rows;
190         void *sample_range_limit;
191         int comps_in_scan;
192         void *cur_comp_info[MAX_COMPS_IN_SCAN];
193         JDIMENSION MCUs_per_row;
194         JDIMENSION MCU_rows_in_scan;
195         int blocks_in_MCU;
196         int MCU_membership[D_MAX_BLOCKS_IN_MCU];
197         int Ss, Se, Ah, Al;
198         int unread_marker;
199         void *master;
200         void *main;
201         void *coef;
202         void *post;
203         void *inputctl;
204         void *marker;
205         void *entropy;
206         void *idct;
207         void *upsample;
208         void *cconvert;
209         void *cquantize;
210 };
211 #else
212 #include <jpeglib.h>
213 #endif
214
215
216 /*
217 =================================================================
218
219   DarkPlaces definitions
220
221 =================================================================
222 */
223
224 // Functions exported from libjpeg
225 static void (*qjpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize);
226 static void (*qjpeg_destroy_decompress) (j_decompress_ptr cinfo);
227 static boolean (*qjpeg_finish_decompress) (j_decompress_ptr cinfo);
228 static boolean (*qjpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired);
229 static int (*qjpeg_read_header) (j_decompress_ptr cinfo, qbyte require_image);
230 static JDIMENSION (*qjpeg_read_scanlines) (j_decompress_ptr cinfo, qbyte** scanlines, JDIMENSION max_lines);
231 static boolean (*qjpeg_start_decompress) (j_decompress_ptr cinfo);
232 static struct jpeg_error_mgr* (*qjpeg_std_error) (struct jpeg_error_mgr *err);
233
234 static dllfunction_t jpegfuncs[] =
235 {
236         {"jpeg_CreateDecompress",       (void **) &qjpeg_CreateDecompress},
237         {"jpeg_destroy_decompress",     (void **) &qjpeg_destroy_decompress},
238         {"jpeg_finish_decompress",      (void **) &qjpeg_finish_decompress},
239         {"jpeg_resync_to_restart",      (void **) &qjpeg_resync_to_restart},
240         {"jpeg_read_header",            (void **) &qjpeg_read_header},
241         {"jpeg_read_scanlines",         (void **) &qjpeg_read_scanlines},
242         {"jpeg_start_decompress",       (void **) &qjpeg_start_decompress},
243         {"jpeg_std_error",                      (void **) &qjpeg_std_error},
244         {NULL, NULL}
245 };
246
247 // Handle for JPEG DLL
248 static dllhandle_t jpeg_dll = NULL;
249
250
251 /*
252 =================================================================
253
254   DLL load & unload
255
256 =================================================================
257 */
258
259 /*
260 ====================
261 JPEG_OpenLibrary
262
263 Try to load the JPEG DLL
264 ====================
265 */
266 qboolean JPEG_OpenLibrary (void)
267 {
268         const char* dllname;
269         const dllfunction_t *func;
270
271         // Already loaded?
272         if (jpeg_dll)
273                 return true;
274
275 #ifdef WIN32
276         dllname = "libjpeg.dll";
277 #else
278         dllname = "libjpeg.so.62";
279 #endif
280
281         // Initializations
282         for (func = jpegfuncs; func && func->name != NULL; func++)
283                 *func->funcvariable = NULL;
284
285         // Load the DLL
286         if (! (jpeg_dll = Sys_LoadLibrary (dllname)))
287         {
288                 Con_Printf("Can't find %s. JPEG support disabled\n", dllname);
289                 return false;
290         }
291
292         // Get the function adresses
293         for (func = jpegfuncs; func && func->name != NULL; func++)
294                 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (jpeg_dll, func->name)))
295                 {
296                         Con_Printf("missing function \"%s\" - broken JPEG library!\n", func->name);
297                         JPEG_CloseLibrary ();
298                         return false;
299                 }
300
301         return true;
302 }
303
304
305 /*
306 ====================
307 JPEG_CloseLibrary
308
309 Unload the JPEG DLL
310 ====================
311 */
312 void JPEG_CloseLibrary (void)
313 {
314         if (!jpeg_dll)
315                 return;
316
317         Sys_UnloadLibrary (jpeg_dll);
318         jpeg_dll = NULL;
319 }
320
321
322 /*
323 =================================================================
324
325   Functions for handling JPEG images
326
327 =================================================================
328 */
329
330 static qbyte jpeg_eoi_marker [2] = {0xFF, JPEG_EOI};
331
332 static void JPEG_Noop (j_decompress_ptr cinfo) {}
333
334 static boolean JPEG_FillInputBuffer (j_decompress_ptr cinfo)
335 {
336     // Insert a fake EOI marker
337     cinfo->src->next_input_byte = jpeg_eoi_marker;
338     cinfo->src->bytes_in_buffer = 2;
339
340         return TRUE;
341 }
342
343 static void JPEG_SkipInputData (j_decompress_ptr cinfo, long num_bytes)
344 {
345     if (cinfo->src->bytes_in_buffer <= (unsigned long)num_bytes)
346         {
347                 cinfo->src->bytes_in_buffer = 0;
348                 return;
349         }
350
351     cinfo->src->next_input_byte += num_bytes;
352     cinfo->src->bytes_in_buffer -= num_bytes;
353 }
354
355 static void JPEG_MemSrc (j_decompress_ptr cinfo, qbyte *buffer)
356 {
357         cinfo->src = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
358
359         cinfo->src->next_input_byte = buffer;
360         cinfo->src->bytes_in_buffer = com_filesize;
361
362         cinfo->src->init_source = JPEG_Noop;
363         cinfo->src->fill_input_buffer = JPEG_FillInputBuffer;
364         cinfo->src->skip_input_data = JPEG_SkipInputData;
365         cinfo->src->resync_to_restart = qjpeg_resync_to_restart; // use the default method
366         cinfo->src->term_source = JPEG_Noop;
367 }
368
369
370 /*
371 ====================
372 JPEG_LoadImage
373
374 Load a JPEG image into a RGBA buffer
375 ====================
376 */
377 qbyte* JPEG_LoadImage (qbyte *f, int matchwidth, int matchheight)
378 {
379         struct jpeg_decompress_struct cinfo;
380         struct jpeg_error_mgr jerr;
381         qbyte *image_rgba, *scanline;
382         unsigned int line;
383
384         // No DLL = no JPEGs
385         if (!jpeg_dll)
386                 return NULL;
387
388         cinfo.err = qjpeg_std_error (&jerr);
389         qjpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, (size_t) sizeof(struct jpeg_decompress_struct));
390         JPEG_MemSrc (&cinfo, f);
391         qjpeg_read_header (&cinfo, TRUE);
392         qjpeg_start_decompress (&cinfo);
393
394         image_width = cinfo.image_width;
395         image_height = cinfo.image_height;
396
397         if ((matchwidth && image_width != matchwidth) || (matchheight && image_height != matchheight))
398         {
399                 qjpeg_finish_decompress (&cinfo);
400                 qjpeg_destroy_decompress (&cinfo);
401                 return NULL;
402         }
403
404         image_rgba = Mem_Alloc(tempmempool, image_width * image_height * 4);
405         scanline = Mem_Alloc(tempmempool, image_width * cinfo.output_components);
406         if (!image_rgba || !scanline)
407         {
408                 if (!image_rgba)
409                         Mem_Free (image_rgba);
410
411                 Con_Printf("JPEG_LoadImage: not enough memory for %i by %i image\n", image_width, image_height);
412                 qjpeg_finish_decompress (&cinfo);
413                 qjpeg_destroy_decompress (&cinfo);
414                 return NULL;
415         }
416
417         // Decompress the image, line by line
418         line = 0;
419         while (cinfo.output_scanline < cinfo.output_height)
420         {
421                 qbyte *buffer_ptr;
422                 int ind;
423
424                 qjpeg_read_scanlines (&cinfo, &scanline, 1);
425
426                 // Convert the image to RGBA
427                 switch (cinfo.output_components)
428                 {
429                         // RGB images
430                         case 3:
431                                 buffer_ptr = &image_rgba[image_width * line * 4];
432                                 for (ind = 0; ind < image_width * 3; ind += 3, buffer_ptr += 4)
433                                 {
434                                         buffer_ptr[0] = scanline[ind];
435                                         buffer_ptr[1] = scanline[ind + 1];
436                                         buffer_ptr[2] = scanline[ind + 2];
437                                         buffer_ptr[3] = 255;
438                                 }
439                                 break;
440
441                         // Greyscale images (default to it, just in case)
442                         case 1:
443                         default:
444                                 buffer_ptr = &image_rgba[image_width * line * 4];
445                                 for (ind = 0; ind < image_width; ind++, buffer_ptr += 4)
446                                 {
447                                         buffer_ptr[0] = scanline[ind];
448                                         buffer_ptr[1] = scanline[ind];
449                                         buffer_ptr[2] = scanline[ind];
450                                         buffer_ptr[3] = 255;
451                                 }
452                 }
453
454                 line++;
455         }
456         Mem_Free (scanline);
457
458         qjpeg_finish_decompress (&cinfo);
459         qjpeg_destroy_decompress (&cinfo);
460
461         return image_rgba;
462 }