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