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