]> git.saurik.com Git - wxWidgets.git/blob - src/common/imagjpeg.cpp
reSWIGged
[wxWidgets.git] / src / common / imagjpeg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagjpeg.cpp
3 // Purpose: wxImage JPEG handler
4 // Author: Vaclav Slavik
5 // RCS-ID: $Id$
6 // Copyright: (c) Vaclav Slavik
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #ifdef __BORLANDC__
14 #pragma hdrstop
15 #endif
16
17 #if wxUSE_IMAGE && wxUSE_LIBJPEG
18
19 #include "wx/imagjpeg.h"
20
21 #ifndef WX_PRECOMP
22 #include "wx/log.h"
23 #include "wx/app.h"
24 #include "wx/intl.h"
25 #include "wx/bitmap.h"
26 #include "wx/module.h"
27 #endif
28
29 extern "C"
30 {
31 #if defined(__WXMSW__)
32 #define XMD_H
33 #endif
34 #include "jpeglib.h"
35 }
36
37 #ifndef HAVE_WXJPEG_BOOLEAN
38 typedef boolean wxjpeg_boolean;
39 #endif
40
41 #include "wx/filefn.h"
42 #include "wx/wfstream.h"
43
44 // For memcpy
45 #include <string.h>
46 // For JPEG library error handling
47 #include <setjmp.h>
48
49 #ifdef __SALFORDC__
50 #undef FAR
51 #endif
52
53 // ----------------------------------------------------------------------------
54 // types
55 // ----------------------------------------------------------------------------
56
57 // the standard definition of METHODDEF(type) from jmorecfg.h is "static type"
58 // which means that we can't declare the method functions as extern "C" - the
59 // compiler (rightfully) complains about the multiple storage classes in
60 // declaration
61 //
62 // so we only add extern "C" when using our own, modified, jmorecfg.h - and use
63 // whatever we have in the system headers if this is what we use hoping that it
64 // should be ok (can't do anything else)
65 #ifdef JPEG_METHOD_LINKAGE
66 #define CPP_METHODDEF(type) extern "C" METHODDEF(type)
67 #else // not using our jmorecfg.h header
68 #define CPP_METHODDEF(type) METHODDEF(type)
69 #endif
70
71 //-----------------------------------------------------------------------------
72 // wxJPEGHandler
73 //-----------------------------------------------------------------------------
74
75 IMPLEMENT_DYNAMIC_CLASS(wxJPEGHandler,wxImageHandler)
76
77 #if wxUSE_STREAMS
78
79 //------------- JPEG Data Source Manager
80
81 #define JPEG_IO_BUFFER_SIZE 2048
82
83 typedef struct {
84 struct jpeg_source_mgr pub; /* public fields */
85
86 JOCTET* buffer; /* start of buffer */
87 wxInputStream *stream;
88 } wx_source_mgr;
89
90 typedef wx_source_mgr * wx_src_ptr;
91
92 CPP_METHODDEF(void) wx_init_source ( j_decompress_ptr WXUNUSED(cinfo) )
93 {
94 }
95
96 CPP_METHODDEF(wxjpeg_boolean) wx_fill_input_buffer ( j_decompress_ptr cinfo )
97 {
98 wx_src_ptr src = (wx_src_ptr) cinfo->src;
99
100 src->pub.next_input_byte = src->buffer;
101 src->pub.bytes_in_buffer = src->stream->Read(src->buffer, JPEG_IO_BUFFER_SIZE).LastRead();
102
103 if (src->pub.bytes_in_buffer == 0) // check for end-of-stream
104 {
105 // Insert a fake EOI marker
106 src->buffer[0] = 0xFF;
107 src->buffer[1] = JPEG_EOI;
108 src->pub.bytes_in_buffer = 2;
109 }
110 return TRUE;
111 }
112
113 CPP_METHODDEF(void) wx_skip_input_data ( j_decompress_ptr cinfo, long num_bytes )
114 {
115 if (num_bytes > 0)
116 {
117 wx_src_ptr src = (wx_src_ptr) cinfo->src;
118
119 while (num_bytes > (long)src->pub.bytes_in_buffer)
120 {
121 num_bytes -= (long) src->pub.bytes_in_buffer;
122 src->pub.fill_input_buffer(cinfo);
123 }
124 src->pub.next_input_byte += (size_t) num_bytes;
125 src->pub.bytes_in_buffer -= (size_t) num_bytes;
126 }
127 }
128
129 CPP_METHODDEF(void) wx_term_source ( j_decompress_ptr cinfo )
130 {
131 wx_src_ptr src = (wx_src_ptr) cinfo->src;
132
133 if (src->pub.bytes_in_buffer > 0)
134 src->stream->SeekI(-(long)src->pub.bytes_in_buffer, wxFromCurrent);
135 delete[] src->buffer;
136 }
137
138
139 // JPEG error manager:
140
141 struct wx_error_mgr {
142 struct jpeg_error_mgr pub; /* "public" fields */
143
144 jmp_buf setjmp_buffer; /* for return to caller */
145 };
146
147 typedef struct wx_error_mgr * wx_error_ptr;
148
149 /*
150 * Here's the routine that will replace the standard error_exit method:
151 */
152
153 CPP_METHODDEF(void) wx_error_exit (j_common_ptr cinfo)
154 {
155 /* cinfo->err really points to a wx_error_mgr struct, so coerce pointer */
156 wx_error_ptr myerr = (wx_error_ptr) cinfo->err;
157
158 /* Always display the message. */
159 /* We could postpone this until after returning, if we chose. */
160 (*cinfo->err->output_message) (cinfo);
161
162 /* Return control to the setjmp point */
163 longjmp(myerr->setjmp_buffer, 1);
164 }
165
166 /*
167 * This will replace the standard output_message method when the user
168 * wants us to be silent (verbose==false). We must have such method instead of
169 * simply using NULL for cinfo->err->output_message because it's called
170 * unconditionally from within libjpeg when there's "garbage input".
171 */
172 CPP_METHODDEF(void) wx_ignore_message (j_common_ptr WXUNUSED(cinfo))
173 {
174 }
175
176 void wx_jpeg_io_src( j_decompress_ptr cinfo, wxInputStream& infile )
177 {
178 wx_src_ptr src;
179
180 if (cinfo->src == NULL) { /* first time for this JPEG object? */
181 cinfo->src = (struct jpeg_source_mgr *)
182 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
183 sizeof(wx_source_mgr));
184 }
185 src = (wx_src_ptr) cinfo->src;
186 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
187 src->buffer = new JOCTET[JPEG_IO_BUFFER_SIZE];
188 src->pub.next_input_byte = NULL; /* until buffer loaded */
189 src->stream = &infile;
190
191 src->pub.init_source = wx_init_source;
192 src->pub.fill_input_buffer = wx_fill_input_buffer;
193 src->pub.skip_input_data = wx_skip_input_data;
194 src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
195 src->pub.term_source = wx_term_source;
196 }
197
198 static inline void wx_cmyk_to_rgb(unsigned char* rgb, const unsigned char* cmyk)
199 {
200 register int k = 255 - cmyk[3];
201 register int k2 = cmyk[3];
202 register int c;
203
204 c = k + k2 * (255 - cmyk[0]) / 255;
205 rgb[0] = (unsigned char)((c > 255) ? 0 : (255 - c));
206
207 c = k + k2 * (255 - cmyk[1]) / 255;
208 rgb[1] = (unsigned char)((c > 255) ? 0 : (255 - c));
209
210 c = k + k2 * (255 - cmyk[2]) / 255;
211 rgb[2] = (unsigned char)((c > 255) ? 0 : (255 - c));
212 }
213
214 // temporarily disable the warning C4611 (interaction between '_setjmp' and
215 // C++ object destruction is non-portable) - I don't see any dtors here
216 #ifdef __VISUALC__
217 #pragma warning(disable:4611)
218 #endif /* VC++ */
219
220 bool wxJPEGHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int WXUNUSED(index) )
221 {
222 struct jpeg_decompress_struct cinfo;
223 struct wx_error_mgr jerr;
224 unsigned char *ptr;
225
226 image->Destroy();
227 cinfo.err = jpeg_std_error( &jerr.pub );
228 jerr.pub.error_exit = wx_error_exit;
229
230 if (!verbose)
231 cinfo.err->output_message = wx_ignore_message;
232
233 /* Establish the setjmp return context for wx_error_exit to use. */
234 if (setjmp(jerr.setjmp_buffer)) {
235 /* If we get here, the JPEG code has signaled an error.
236 * We need to clean up the JPEG object, close the input file, and return.
237 */
238 if (verbose)
239 wxLogError(_("JPEG: Couldn't load - file is probably corrupted."));
240 (cinfo.src->term_source)(&cinfo);
241 jpeg_destroy_decompress(&cinfo);
242 if (image->Ok()) image->Destroy();
243 return false;
244 }
245
246 jpeg_create_decompress( &cinfo );
247 wx_jpeg_io_src( &cinfo, stream );
248 jpeg_read_header( &cinfo, TRUE );
249
250 int bytesPerPixel;
251 if ((cinfo.out_color_space == JCS_CMYK) || (cinfo.out_color_space == JCS_YCCK))
252 {
253 cinfo.out_color_space = JCS_CMYK;
254 bytesPerPixel = 4;
255 }
256 else // all the rest is treated as RGB
257 {
258 cinfo.out_color_space = JCS_RGB;
259 bytesPerPixel = 3;
260 }
261
262 jpeg_start_decompress( &cinfo );
263
264 image->Create( cinfo.image_width, cinfo.image_height );
265 if (!image->Ok()) {
266 jpeg_finish_decompress( &cinfo );
267 jpeg_destroy_decompress( &cinfo );
268 return false;
269 }
270 image->SetMask( false );
271 ptr = image->GetData();
272
273 unsigned stride = cinfo.output_width * bytesPerPixel;
274 JSAMPARRAY tempbuf = (*cinfo.mem->alloc_sarray)
275 ((j_common_ptr) &cinfo, JPOOL_IMAGE, stride, 1 );
276
277 while ( cinfo.output_scanline < cinfo.output_height )
278 {
279 jpeg_read_scanlines( &cinfo, tempbuf, 1 );
280 if (cinfo.out_color_space == JCS_RGB)
281 {
282 memcpy( ptr, tempbuf[0], stride );
283 ptr += stride;
284 }
285 else // CMYK
286 {
287 const unsigned char* inptr = (const unsigned char*) tempbuf[0];
288 for (size_t i = 0; i < cinfo.output_width; i++)
289 {
290 wx_cmyk_to_rgb(ptr, inptr);
291 ptr += 3;
292 inptr += 4;
293 }
294 }
295 }
296
297 jpeg_finish_decompress( &cinfo );
298 jpeg_destroy_decompress( &cinfo );
299 return true;
300 }
301
302 typedef struct {
303 struct jpeg_destination_mgr pub;
304
305 wxOutputStream *stream;
306 JOCTET * buffer;
307 } wx_destination_mgr;
308
309 typedef wx_destination_mgr * wx_dest_ptr;
310
311 #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
312
313 CPP_METHODDEF(void) wx_init_destination (j_compress_ptr cinfo)
314 {
315 wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
316
317 /* Allocate the output buffer --- it will be released when done with image */
318 dest->buffer = (JOCTET *)
319 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
320 OUTPUT_BUF_SIZE * sizeof(JOCTET));
321 dest->pub.next_output_byte = dest->buffer;
322 dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
323 }
324
325 CPP_METHODDEF(wxjpeg_boolean) wx_empty_output_buffer (j_compress_ptr cinfo)
326 {
327 wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
328
329 dest->stream->Write(dest->buffer, OUTPUT_BUF_SIZE);
330 dest->pub.next_output_byte = dest->buffer;
331 dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
332 return TRUE;
333 }
334
335 CPP_METHODDEF(void) wx_term_destination (j_compress_ptr cinfo)
336 {
337 wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
338 size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
339 /* Write any data remaining in the buffer */
340 if (datacount > 0)
341 dest->stream->Write(dest->buffer, datacount);
342 }
343
344 GLOBAL(void) wx_jpeg_io_dest (j_compress_ptr cinfo, wxOutputStream& outfile)
345 {
346 wx_dest_ptr dest;
347
348 if (cinfo->dest == NULL) { /* first time for this JPEG object? */
349 cinfo->dest = (struct jpeg_destination_mgr *)
350 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
351 sizeof(wx_destination_mgr));
352 }
353
354 dest = (wx_dest_ptr) cinfo->dest;
355 dest->pub.init_destination = wx_init_destination;
356 dest->pub.empty_output_buffer = wx_empty_output_buffer;
357 dest->pub.term_destination = wx_term_destination;
358 dest->stream = &outfile;
359 }
360
361 bool wxJPEGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
362 {
363 struct jpeg_compress_struct cinfo;
364 struct wx_error_mgr jerr;
365 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
366 JSAMPLE *image_buffer;
367 int stride; /* physical row width in image buffer */
368
369 cinfo.err = jpeg_std_error(&jerr.pub);
370 jerr.pub.error_exit = wx_error_exit;
371
372 if (!verbose)
373 cinfo.err->output_message = wx_ignore_message;
374
375 /* Establish the setjmp return context for wx_error_exit to use. */
376 if (setjmp(jerr.setjmp_buffer))
377 {
378 /* If we get here, the JPEG code has signaled an error.
379 * We need to clean up the JPEG object, close the input file, and return.
380 */
381 if (verbose)
382 wxLogError(_("JPEG: Couldn't save image."));
383 jpeg_destroy_compress(&cinfo);
384 return false;
385 }
386
387 jpeg_create_compress(&cinfo);
388 wx_jpeg_io_dest(&cinfo, stream);
389
390 cinfo.image_width = image->GetWidth();
391 cinfo.image_height = image->GetHeight();
392 cinfo.input_components = 3;
393 cinfo.in_color_space = JCS_RGB;
394 jpeg_set_defaults(&cinfo);
395
396 // TODO: 3rd parameter is force_baseline, what value should this be?
397 // Code says: "If force_baseline is TRUE, the computed quantization table entries
398 // are limited to 1..255 for JPEG baseline compatibility."
399 // 'Quality' is a number between 0 (terrible) and 100 (very good).
400 // The default (in jcparam.c, jpeg_set_defaults) is 75,
401 // and force_baseline is TRUE.
402 if (image->HasOption(wxIMAGE_OPTION_QUALITY))
403 jpeg_set_quality(&cinfo, image->GetOptionInt(wxIMAGE_OPTION_QUALITY), TRUE);
404
405 // set the resolution fields in the output file
406 UINT16 resX,
407 resY;
408 if ( image->HasOption(wxIMAGE_OPTION_RESOLUTIONX) &&
409 image->HasOption(wxIMAGE_OPTION_RESOLUTIONY) )
410 {
411 resX = (UINT16)image->GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX);
412 resY = (UINT16)image->GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY);
413 }
414 else if ( image->HasOption(wxIMAGE_OPTION_RESOLUTION) )
415 {
416 resX =
417 resY = (UINT16)image->GetOptionInt(wxIMAGE_OPTION_RESOLUTION);
418 }
419 else
420 {
421 resX =
422 resY = 0;
423 }
424
425 if ( resX && resY )
426 {
427 cinfo.X_density = resX;
428 cinfo.Y_density = resY;
429 }
430
431 // sets the resolution unit field in the output file
432 // wxIMAGE_RESOLUTION_INCHES for inches
433 // wxIMAGE_RESOLUTION_CM for centimeters
434 if ( image->HasOption(wxIMAGE_OPTION_RESOLUTIONUNIT) )
435 {
436 cinfo.density_unit = (UINT8)image->GetOptionInt(wxIMAGE_OPTION_RESOLUTIONUNIT);
437 }
438
439 jpeg_start_compress(&cinfo, TRUE);
440
441 stride = cinfo.image_width * 3; /* JSAMPLEs per row in image_buffer */
442 image_buffer = image->GetData();
443 while (cinfo.next_scanline < cinfo.image_height) {
444 row_pointer[0] = &image_buffer[cinfo.next_scanline * stride];
445 jpeg_write_scanlines( &cinfo, row_pointer, 1 );
446 }
447 jpeg_finish_compress(&cinfo);
448 jpeg_destroy_compress(&cinfo);
449
450 return true;
451 }
452
453 #ifdef __VISUALC__
454 #pragma warning(default:4611)
455 #endif /* VC++ */
456
457 bool wxJPEGHandler::DoCanRead( wxInputStream& stream )
458 {
459 unsigned char hdr[2];
460
461 if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
462 return false;
463
464 return hdr[0] == 0xFF && hdr[1] == 0xD8;
465 }
466
467 #endif // wxUSE_STREAMS
468
469 #endif // wxUSE_LIBJPEG