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 "jpeg.h"
38
39 #include <setjmp.h>
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <string.h>
43
44 extern "C" {
45 #include "radiant_jpeglib.h"
46 #include "jpeg6/jerror.h"
47 }
48
49 #include "ifilesystem.h"
50
51 #include "imagelib.h"
52
53 typedef unsigned char byte;
54
55 /* Expanded data source object for stdio input */
56
57 typedef struct {
58 struct jpeg_source_mgr pub; /* public fields */
59
60 int src_size;
61 JOCTET * src_buffer;
62
63 JOCTET * buffer; /* start of buffer */
64 boolean start_of_file; /* have we gotten any data yet? */
65 } my_source_mgr;
66
67 typedef my_source_mgr * my_src_ptr;
68
69 #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
70
71
72 /*
73 * Initialize source --- called by jpeg_read_header
74 * before any data is actually read.
75 */
76
my_init_source(j_decompress_ptr cinfo)77 static void my_init_source (j_decompress_ptr cinfo)
78 {
79 my_src_ptr src = (my_src_ptr) cinfo->src;
80
81 /* We reset the empty-input-file flag for each image,
82 * but we don't clear the input buffer.
83 * This is correct behavior for reading a series of images from one source.
84 */
85 src->start_of_file = TRUE;
86 }
87
88
89 /*
90 * Fill the input buffer --- called whenever buffer is emptied.
91 *
92 * In typical applications, this should read fresh data into the buffer
93 * (ignoring the current state of next_input_byte & bytes_in_buffer),
94 * reset the pointer & count to the start of the buffer, and return TRUE
95 * indicating that the buffer has been reloaded. It is not necessary to
96 * fill the buffer entirely, only to obtain at least one more byte.
97 *
98 * There is no such thing as an EOF return. If the end of the file has been
99 * reached, the routine has a choice of ERREXIT() or inserting fake data into
100 * the buffer. In most cases, generating a warning message and inserting a
101 * fake EOI marker is the best course of action --- this will allow the
102 * decompressor to output however much of the image is there. However,
103 * the resulting error message is misleading if the real problem is an empty
104 * input file, so we handle that case specially.
105 *
106 * In applications that need to be able to suspend compression due to input
107 * not being available yet, a FALSE return indicates that no more data can be
108 * obtained right now, but more may be forthcoming later. In this situation,
109 * the decompressor will return to its caller (with an indication of the
110 * number of scanlines it has read, if any). The application should resume
111 * decompression after it has loaded more data into the input buffer. Note
112 * that there are substantial restrictions on the use of suspension --- see
113 * the documentation.
114 *
115 * When suspending, the decompressor will back up to a convenient restart point
116 * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
117 * indicate where the restart point will be if the current call returns FALSE.
118 * Data beyond this point must be rescanned after resumption, so move it to
119 * the front of the buffer rather than discarding it.
120 */
121
my_fill_input_buffer(j_decompress_ptr cinfo)122 static boolean my_fill_input_buffer (j_decompress_ptr cinfo)
123 {
124 my_src_ptr src = (my_src_ptr) cinfo->src;
125 size_t nbytes;
126
127 if (src->src_size > INPUT_BUF_SIZE)
128 nbytes = INPUT_BUF_SIZE;
129 else
130 nbytes = src->src_size;
131
132 memcpy (src->buffer, src->src_buffer, nbytes);
133 src->src_buffer += nbytes;
134 src->src_size -= nbytes;
135
136 if (nbytes <= 0) {
137 if (src->start_of_file) /* Treat empty input file as fatal error */
138 ERREXIT(cinfo, JERR_INPUT_EMPTY);
139 WARNMS(cinfo, JWRN_JPEG_EOF);
140 /* Insert a fake EOI marker */
141 src->buffer[0] = (JOCTET) 0xFF;
142 src->buffer[1] = (JOCTET) JPEG_EOI;
143 nbytes = 2;
144 }
145
146 src->pub.next_input_byte = src->buffer;
147 src->pub.bytes_in_buffer = nbytes;
148 src->start_of_file = FALSE;
149
150 return TRUE;
151 }
152
153
154 /*
155 * Skip data --- used to skip over a potentially large amount of
156 * uninteresting data (such as an APPn marker).
157 *
158 * Writers of suspendable-input applications must note that skip_input_data
159 * is not granted the right to give a suspension return. If the skip extends
160 * beyond the data currently in the buffer, the buffer can be marked empty so
161 * that the next read will cause a fill_input_buffer call that can suspend.
162 * Arranging for additional bytes to be discarded before reloading the input
163 * buffer is the application writer's problem.
164 */
165
my_skip_input_data(j_decompress_ptr cinfo,long num_bytes)166 static void my_skip_input_data (j_decompress_ptr cinfo, long num_bytes)
167 {
168 my_src_ptr src = (my_src_ptr) cinfo->src;
169
170 /* Just a dumb implementation for now. Could use fseek() except
171 * it doesn't work on pipes. Not clear that being smart is worth
172 * any trouble anyway --- large skips are infrequent.
173 */
174 if (num_bytes > 0) {
175 while (num_bytes > (long) src->pub.bytes_in_buffer) {
176 num_bytes -= (long) src->pub.bytes_in_buffer;
177 (void) my_fill_input_buffer(cinfo);
178 /* note we assume that fill_input_buffer will never return FALSE,
179 * so suspension need not be handled.
180 */
181 }
182 src->pub.next_input_byte += (size_t) num_bytes;
183 src->pub.bytes_in_buffer -= (size_t) num_bytes;
184 }
185 }
186
187
188 /*
189 * An additional method that can be provided by data source modules is the
190 * resync_to_restart method for error recovery in the presence of RST markers.
191 * For the moment, this source module just uses the default resync method
192 * provided by the JPEG library. That method assumes that no backtracking
193 * is possible.
194 */
195
196
197 /*
198 * Terminate source --- called by jpeg_finish_decompress
199 * after all data has been read. Often a no-op.
200 *
201 * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
202 * application must deal with any cleanup that should happen even
203 * for error exit.
204 */
205
my_term_source(j_decompress_ptr cinfo)206 static void my_term_source (j_decompress_ptr cinfo)
207 {
208 /* no work necessary here */
209 }
210
211
212 /*
213 * Prepare for input from a stdio stream.
214 * The caller must have already opened the stream, and is responsible
215 * for closing it after finishing decompression.
216 */
217
jpeg_buffer_src(j_decompress_ptr cinfo,void * buffer,int bufsize)218 static void jpeg_buffer_src (j_decompress_ptr cinfo, void* buffer, int bufsize)
219 {
220 my_src_ptr src;
221
222 /* The source object and input buffer are made permanent so that a series
223 * of JPEG images can be read from the same file by calling jpeg_stdio_src
224 * only before the first one. (If we discarded the buffer at the end of
225 * one image, we'd likely lose the start of the next one.)
226 * This makes it unsafe to use this manager and a different source
227 * manager serially with the same JPEG object. Caveat programmer.
228 */
229 if (cinfo->src == NULL) { /* first time for this JPEG object? */
230 cinfo->src = (struct jpeg_source_mgr *)
231 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
232 sizeof (my_source_mgr));
233 src = (my_src_ptr) cinfo->src;
234 src->buffer = (JOCTET *)
235 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
236 INPUT_BUF_SIZE * sizeof (JOCTET));
237 }
238
239 src = (my_src_ptr) cinfo->src;
240 src->pub.init_source = my_init_source;
241 src->pub.fill_input_buffer = my_fill_input_buffer;
242 src->pub.skip_input_data = my_skip_input_data;
243 src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
244 src->pub.term_source = my_term_source;
245 src->src_buffer = (JOCTET *)buffer;
246 src->src_size = bufsize;
247 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
248 src->pub.next_input_byte = NULL; /* until buffer loaded */
249 }
250
251 // =============================================================================
252
253 static char errormsg[JMSG_LENGTH_MAX];
254
255 typedef struct my_jpeg_error_mgr
256 {
257 struct jpeg_error_mgr pub; // "public" fields
258 jmp_buf setjmp_buffer; // for return to caller
259 } bt_jpeg_error_mgr;
260
my_jpeg_error_exit(j_common_ptr cinfo)261 static void my_jpeg_error_exit (j_common_ptr cinfo)
262 {
263 my_jpeg_error_mgr* myerr = (bt_jpeg_error_mgr*) cinfo->err;
264
265 (*cinfo->err->format_message) (cinfo, errormsg);
266
267 longjmp (myerr->setjmp_buffer, 1);
268 }
269
270 // stash a scanline
j_putRGBScanline(unsigned char * jpegline,int widthPix,unsigned char * outBuf,int row)271 static void j_putRGBScanline (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
272 {
273 int offset = row * widthPix * 4;
274 int count;
275
276 for (count = 0; count < widthPix; count++)
277 {
278 unsigned char iRed, iBlu, iGrn;
279 unsigned char *oRed, *oBlu, *oGrn, *oAlp;
280
281 iRed = *(jpegline + count * 3 + 0);
282 iGrn = *(jpegline + count * 3 + 1);
283 iBlu = *(jpegline + count * 3 + 2);
284
285 oRed = outBuf + offset + count * 4 + 0;
286 oGrn = outBuf + offset + count * 4 + 1;
287 oBlu = outBuf + offset + count * 4 + 2;
288 oAlp = outBuf + offset + count * 4 + 3;
289
290 *oRed = iRed;
291 *oGrn = iGrn;
292 *oBlu = iBlu;
293 *oAlp = 255;
294 }
295 }
296
297 // stash a scanline
j_putRGBAScanline(unsigned char * jpegline,int widthPix,unsigned char * outBuf,int row)298 static void j_putRGBAScanline (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
299 {
300 int offset = row * widthPix * 4;
301 int count;
302
303 for (count = 0; count < widthPix; count++)
304 {
305 unsigned char iRed, iBlu, iGrn, iAlp;
306 unsigned char *oRed, *oBlu, *oGrn, *oAlp;
307
308 iRed = *(jpegline + count * 4 + 0);
309 iGrn = *(jpegline + count * 4 + 1);
310 iBlu = *(jpegline + count * 4 + 2);
311 iAlp = *(jpegline + count * 4 + 3);
312
313 oRed = outBuf + offset + count * 4 + 0;
314 oGrn = outBuf + offset + count * 4 + 1;
315 oBlu = outBuf + offset + count * 4 + 2;
316 oAlp = outBuf + offset + count * 4 + 3;
317
318 *oRed = iRed;
319 *oGrn = iGrn;
320 *oBlu = iBlu;
321
322 //!\todo fix jpeglib, it leaves alpha channel uninitialised
323 #if 1
324 *oAlp = 255;
325 #else
326 *oAlp = iAlp;
327 #endif
328 }
329 }
330
331 // stash a gray scanline
j_putGrayScanlineToRGB(unsigned char * jpegline,int widthPix,unsigned char * outBuf,int row)332 static void j_putGrayScanlineToRGB (unsigned char* jpegline, int widthPix, unsigned char* outBuf, int row)
333 {
334 int offset = row * widthPix * 4;
335 int count;
336
337 for (count = 0; count < widthPix; count++)
338 {
339 unsigned char iGray;
340 unsigned char *oRed, *oBlu, *oGrn, *oAlp;
341
342 // get our grayscale value
343 iGray = *(jpegline + count);
344
345 oRed = outBuf + offset + count * 4;
346 oGrn = outBuf + offset + count * 4 + 1;
347 oBlu = outBuf + offset + count * 4 + 2;
348 oAlp = outBuf + offset + count * 4 + 3;
349
350 *oRed = iGray;
351 *oGrn = iGray;
352 *oBlu = iGray;
353 *oAlp = 255;
354 }
355 }
356
LoadJPGBuff_(const void * src_buffer,int src_size)357 static Image* LoadJPGBuff_(const void *src_buffer, int src_size)
358 {
359 struct jpeg_decompress_struct cinfo;
360 struct my_jpeg_error_mgr jerr;
361
362 cinfo.err = jpeg_std_error (&jerr.pub);
363 jerr.pub.error_exit = my_jpeg_error_exit;
364
365 if (setjmp (jerr.setjmp_buffer)) //< TODO: use c++ exceptions instead of setjmp/longjmp to handle errors
366 {
367 globalErrorStream() << "WARNING: JPEG library error: " << errormsg << "\n";
368 jpeg_destroy_decompress (&cinfo);
369 return 0;
370 }
371
372 jpeg_create_decompress (&cinfo);
373 jpeg_buffer_src (&cinfo, const_cast<void*>(src_buffer), src_size);
374 jpeg_read_header (&cinfo, TRUE);
375 jpeg_start_decompress (&cinfo);
376
377 int row_stride = cinfo.output_width * cinfo.output_components;
378
379 RGBAImage* image = new RGBAImage(cinfo.output_width, cinfo.output_height);
380
381 JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
382
383 while (cinfo.output_scanline < cinfo.output_height)
384 {
385 jpeg_read_scanlines (&cinfo, buffer, 1);
386
387 if (cinfo.out_color_components == 4)
388 j_putRGBAScanline (buffer[0], cinfo.output_width, image->getRGBAPixels(), cinfo.output_scanline-1);
389 else if (cinfo.out_color_components == 3)
390 j_putRGBScanline (buffer[0], cinfo.output_width, image->getRGBAPixels(), cinfo.output_scanline-1);
391 else if (cinfo.out_color_components == 1)
392 j_putGrayScanlineToRGB (buffer[0], cinfo.output_width, image->getRGBAPixels(), cinfo.output_scanline-1);
393 }
394
395 jpeg_finish_decompress (&cinfo);
396 jpeg_destroy_decompress (&cinfo);
397
398 return image;
399 }
400
LoadJPG(ArchiveFile & file)401 Image* LoadJPG(ArchiveFile& file)
402 {
403 ScopedArchiveBuffer buffer(file);
404 return LoadJPGBuff_(buffer.buffer, static_cast<int>(buffer.length));
405 }
406
407