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