]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - plugins/image/jpeg.cpp
67a76541358cb2bd3b2c08d19794ff81e19d4225
[xonotic/netradiant.git] / plugins / image / jpeg.cpp
1 /*
2 Copyright (c) 2001, Loki software, inc.
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification, 
6 are permitted provided that the following conditions are met:
7
8 Redistributions of source code must retain the above copyright notice, this list 
9 of conditions and the following disclaimer.
10
11 Redistributions in binary form must reproduce the above copyright notice, this
12 list of conditions and the following disclaimer in the documentation and/or
13 other materials provided with the distribution.
14
15 Neither the name of Loki software nor the names of its contributors may be used 
16 to endorse or promote products derived from this software without specific prior 
17 written permission. 
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' 
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
22 DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY 
23 DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
24 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
25 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
26 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
27 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
28 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
29 */
30
31 //
32 // Functions to load JPEG files from a buffer, based on jdatasrc.c
33 //
34 // Leonardo Zide (leo@lokigames.com)
35 //
36
37 #include <setjmp.h>
38 #include <stdlib.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <glib.h>
42
43 extern "C" {
44 #include "radiant_jpeglib.h"
45 #include "jpeg6/jerror.h"
46 }
47
48 #include "image.h"
49
50 /* Expanded data source object for stdio input */
51
52 typedef struct {
53   struct jpeg_source_mgr pub;   /* public fields */
54
55   int src_size;
56   JOCTET * src_buffer;
57
58   JOCTET * buffer;              /* start of buffer */
59   boolean start_of_file;        /* have we gotten any data yet? */
60 } my_source_mgr;
61
62 typedef my_source_mgr * my_src_ptr;
63
64 #define INPUT_BUF_SIZE  4096    /* choose an efficiently fread'able size */
65
66
67 /*
68  * Initialize source --- called by jpeg_read_header
69  * before any data is actually read.
70  */
71
72 static void my_init_source (j_decompress_ptr cinfo)
73 {
74   my_src_ptr src = (my_src_ptr) cinfo->src;
75
76   /* We reset the empty-input-file flag for each image,
77    * but we don't clear the input buffer.
78    * This is correct behavior for reading a series of images from one source.
79    */
80   src->start_of_file = TRUE;
81 }
82
83
84 /*
85  * Fill the input buffer --- called whenever buffer is emptied.
86  *
87  * In typical applications, this should read fresh data into the buffer
88  * (ignoring the current state of next_input_byte & bytes_in_buffer),
89  * reset the pointer & count to the start of the buffer, and return TRUE
90  * indicating that the buffer has been reloaded.  It is not necessary to
91  * fill the buffer entirely, only to obtain at least one more byte.
92  *
93  * There is no such thing as an EOF return.  If the end of the file has been
94  * reached, the routine has a choice of ERREXIT() or inserting fake data into
95  * the buffer.  In most cases, generating a warning message and inserting a
96  * fake EOI marker is the best course of action --- this will allow the
97  * decompressor to output however much of the image is there.  However,
98  * the resulting error message is misleading if the real problem is an empty
99  * input file, so we handle that case specially.
100  *
101  * In applications that need to be able to suspend compression due to input
102  * not being available yet, a FALSE return indicates that no more data can be
103  * obtained right now, but more may be forthcoming later.  In this situation,
104  * the decompressor will return to its caller (with an indication of the
105  * number of scanlines it has read, if any).  The application should resume
106  * decompression after it has loaded more data into the input buffer.  Note
107  * that there are substantial restrictions on the use of suspension --- see
108  * the documentation.
109  *
110  * When suspending, the decompressor will back up to a convenient restart point
111  * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
112  * indicate where the restart point will be if the current call returns FALSE.
113  * Data beyond this point must be rescanned after resumption, so move it to
114  * the front of the buffer rather than discarding it.
115  */
116
117 static boolean my_fill_input_buffer (j_decompress_ptr cinfo)
118 {
119   my_src_ptr src = (my_src_ptr) cinfo->src;
120   size_t nbytes;
121
122   if (src->src_size > INPUT_BUF_SIZE)
123     nbytes = INPUT_BUF_SIZE;
124   else
125     nbytes = src->src_size;
126
127   memcpy (src->buffer, src->src_buffer, nbytes);
128   src->src_buffer += nbytes;
129   src->src_size -= nbytes;
130
131   if (nbytes <= 0) {
132     if (src->start_of_file)     /* Treat empty input file as fatal error */
133       ERREXIT(cinfo, JERR_INPUT_EMPTY);
134     WARNMS(cinfo, JWRN_JPEG_EOF);
135     /* Insert a fake EOI marker */
136     src->buffer[0] = (JOCTET) 0xFF;
137     src->buffer[1] = (JOCTET) JPEG_EOI;
138     nbytes = 2;
139   }
140
141   src->pub.next_input_byte = src->buffer;
142   src->pub.bytes_in_buffer = nbytes;
143   src->start_of_file = FALSE;
144
145   return TRUE;
146 }
147
148
149 /*
150  * Skip data --- used to skip over a potentially large amount of
151  * uninteresting data (such as an APPn marker).
152  *
153  * Writers of suspendable-input applications must note that skip_input_data
154  * is not granted the right to give a suspension return.  If the skip extends
155  * beyond the data currently in the buffer, the buffer can be marked empty so
156  * that the next read will cause a fill_input_buffer call that can suspend.
157  * Arranging for additional bytes to be discarded before reloading the input
158  * buffer is the application writer's problem.
159  */
160
161 static void my_skip_input_data (j_decompress_ptr cinfo, long num_bytes)
162 {
163   my_src_ptr src = (my_src_ptr) cinfo->src;
164
165   /* Just a dumb implementation for now.  Could use fseek() except
166    * it doesn't work on pipes.  Not clear that being smart is worth
167    * any trouble anyway --- large skips are infrequent.
168    */
169   if (num_bytes > 0) {
170     while (num_bytes > (long) src->pub.bytes_in_buffer) {
171       num_bytes -= (long) src->pub.bytes_in_buffer;
172       (void) my_fill_input_buffer(cinfo);
173       /* note we assume that fill_input_buffer will never return FALSE,
174        * so suspension need not be handled.
175        */
176     }
177     src->pub.next_input_byte += (size_t) num_bytes;
178     src->pub.bytes_in_buffer -= (size_t) num_bytes;
179   }
180 }
181
182
183 /*
184  * An additional method that can be provided by data source modules is the
185  * resync_to_restart method for error recovery in the presence of RST markers.
186  * For the moment, this source module just uses the default resync method
187  * provided by the JPEG library.  That method assumes that no backtracking
188  * is possible.
189  */
190
191
192 /*
193  * Terminate source --- called by jpeg_finish_decompress
194  * after all data has been read.  Often a no-op.
195  *
196  * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
197  * application must deal with any cleanup that should happen even
198  * for error exit.
199  */
200
201 static void my_term_source (j_decompress_ptr cinfo)
202 {
203   /* no work necessary here */
204 }
205
206
207 /*
208  * Prepare for input from a stdio stream.
209  * The caller must have already opened the stream, and is responsible
210  * for closing it after finishing decompression.
211  */
212
213 static void jpeg_buffer_src (j_decompress_ptr cinfo, void* buffer, int bufsize)
214 {
215   my_src_ptr src;
216
217   /* The source object and input buffer are made permanent so that a series
218    * of JPEG images can be read from the same file by calling jpeg_stdio_src
219    * only before the first one.  (If we discarded the buffer at the end of
220    * one image, we'd likely lose the start of the next one.)
221    * This makes it unsafe to use this manager and a different source
222    * manager serially with the same JPEG object.  Caveat programmer.
223    */
224   if (cinfo->src == NULL) {     /* first time for this JPEG object? */
225     cinfo->src = (struct jpeg_source_mgr *)
226       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
227                                   sizeof (my_source_mgr));
228     src = (my_src_ptr) cinfo->src;
229     src->buffer = (JOCTET *)
230       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
231                                   INPUT_BUF_SIZE * sizeof (JOCTET));
232   }
233
234   src = (my_src_ptr) cinfo->src;
235   src->pub.init_source = my_init_source;
236   src->pub.fill_input_buffer = my_fill_input_buffer;
237   src->pub.skip_input_data = my_skip_input_data;
238   src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
239   src->pub.term_source = my_term_source;
240   src->src_buffer = (JOCTET *)buffer;
241   src->src_size = bufsize;
242   src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
243   src->pub.next_input_byte = NULL; /* until buffer loaded */
244 }
245
246 // =============================================================================
247
248 static char errormsg[JMSG_LENGTH_MAX];
249
250 typedef struct my_jpeg_error_mgr
251 {
252   struct jpeg_error_mgr pub;  // "public" fields
253   jmp_buf setjmp_buffer;      // for return to caller 
254 } bt_jpeg_error_mgr;
255
256 static void my_jpeg_error_exit (j_common_ptr cinfo)
257 {
258   my_jpeg_error_mgr* myerr = (bt_jpeg_error_mgr*) cinfo->err;
259
260   (*cinfo->err->format_message) (cinfo, errormsg);
261
262   longjmp (myerr->setjmp_buffer, 1);
263 }
264
265 // stash a scanline
266 static void j_putRGBScanline (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
267 {
268   int offset = row * widthPix * 4;
269   int count;
270
271   for (count = 0; count < widthPix; count++) 
272   {
273     unsigned char iRed, iBlu, iGrn;
274     unsigned char *oRed, *oBlu, *oGrn, *oAlp;
275
276     iRed = *(jpegline + count * 3 + 0);
277     iGrn = *(jpegline + count * 3 + 1);
278     iBlu = *(jpegline + count * 3 + 2);
279
280     oRed = outBuf + offset + count * 4 + 0;
281     oGrn = outBuf + offset + count * 4 + 1;
282     oBlu = outBuf + offset + count * 4 + 2;
283     oAlp = outBuf + offset + count * 4 + 3;
284
285     *oRed = iRed;
286     *oGrn = iGrn;
287     *oBlu = iBlu;
288     *oAlp = 255;
289   }
290 }
291
292 // stash a scanline
293 static void j_putRGBAScanline (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
294 {
295   int offset = row * widthPix * 4;
296   int count;
297
298   for (count = 0; count < widthPix; count++) 
299   {
300     unsigned char iRed, iBlu, iGrn, iAlp;
301     unsigned char *oRed, *oBlu, *oGrn, *oAlp;
302
303     iRed = *(jpegline + count * 4 + 0);
304     iGrn = *(jpegline + count * 4 + 1);
305     iBlu = *(jpegline + count * 4 + 2);
306                 iAlp = *(jpegline + count * 4 + 3);
307
308     oRed = outBuf + offset + count * 4 + 0;
309     oGrn = outBuf + offset + count * 4 + 1;
310     oBlu = outBuf + offset + count * 4 + 2;
311     oAlp = outBuf + offset + count * 4 + 3;
312
313     *oRed = iRed;
314     *oGrn = iGrn;
315     *oBlu = iBlu;
316         // ydnar: see bug 900
317     *oAlp = 255;        //%     iAlp;
318   }
319 }
320
321 // stash a gray scanline
322 static void j_putGrayScanlineToRGB (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
323 {
324   int offset = row * widthPix * 4;
325   int count;
326
327   for (count = 0; count < widthPix; count++) 
328   {
329     unsigned char iGray;
330     unsigned char *oRed, *oBlu, *oGrn, *oAlp;
331
332     // get our grayscale value
333     iGray = *(jpegline + count);
334
335     oRed = outBuf + offset + count * 4;
336     oGrn = outBuf + offset + count * 4 + 1;
337     oBlu = outBuf + offset + count * 4 + 2;
338     oAlp = outBuf + offset + count * 4 + 3;
339
340     *oRed = iGray;
341     *oGrn = iGray;
342     *oBlu = iGray;
343     *oAlp = 255;
344   }
345 }
346
347 static int _LoadJPGBuff (void *src_buffer, int src_size, unsigned char **pic, int *width, int *height) 
348 {
349   struct jpeg_decompress_struct cinfo;
350   struct my_jpeg_error_mgr jerr;
351   JSAMPARRAY buffer;
352   int row_stride, size;
353
354   cinfo.err = jpeg_std_error (&jerr.pub);
355   jerr.pub.error_exit = my_jpeg_error_exit;
356
357   if (setjmp (jerr.setjmp_buffer))
358   {
359     *pic = (unsigned char*)errormsg;
360     jpeg_destroy_decompress (&cinfo);
361     return -1;
362   }
363
364   jpeg_create_decompress (&cinfo);
365   jpeg_buffer_src (&cinfo, src_buffer, src_size);
366   jpeg_read_header (&cinfo, TRUE);
367   jpeg_start_decompress (&cinfo);
368
369   row_stride = cinfo.output_width * cinfo.output_components;
370
371   size = cinfo.output_width * cinfo.output_height * 4;
372   *width = cinfo.output_width;
373   *height = cinfo.output_height;
374   *pic = (unsigned char*) (g_malloc (size+1));
375   memset (*pic, 0, size+1);
376
377   buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
378
379   while (cinfo.output_scanline < cinfo.output_height)
380   {
381     jpeg_read_scanlines (&cinfo, buffer, 1);
382
383     if (cinfo.out_color_components == 4)
384       j_putRGBAScanline (buffer[0], cinfo.output_width, *pic, cinfo.output_scanline-1);
385     else if (cinfo.out_color_components == 3)
386       j_putRGBScanline (buffer[0], cinfo.output_width, *pic, cinfo.output_scanline-1);
387     else if (cinfo.out_color_components == 1)
388       j_putGrayScanlineToRGB (buffer[0], cinfo.output_width, *pic, cinfo.output_scanline-1);
389   }
390
391   jpeg_finish_decompress (&cinfo);
392   jpeg_destroy_decompress (&cinfo);
393
394   return 0;
395 }
396
397 void LoadJPG (const char *filename, unsigned char **pic, int *width, int *height)
398 {
399   unsigned char *fbuffer = NULL;
400   int nLen = vfsLoadFile ((char *)filename, (void **)&fbuffer, 0 );
401   if (nLen == -1)
402     return;
403
404   if (_LoadJPGBuff (fbuffer, nLen, pic, width, height) != 0)
405   {
406     g_FuncTable.m_pfnSysPrintf( "WARNING: JPEG library failed to load %s because %s\n", filename, *pic );
407     *pic = NULL;
408   }
409
410   vfsFreeFile (fbuffer);
411 }