1 #ifdef __GNUG__
2 #pragma implementation "imagjpg.h"
3 #endif
4 
5 // For compilers that support precompilation, includes "wx.h".
6 #include "wx/wxprec.h"
7 
8 #if !wxCHECK_VERSION(2,9,0)
9 
10 #ifdef __BORLANDC__
11 #pragma hdrstop
12 #endif
13 
14 #include "wx/defs.h"
15 
16 #if wxUSE_IMAGE && wxUSE_LIBJPEG
17 
18 #include "imagjpg.h"
19 #include "wx/log.h"
20 #include "wx/app.h"
21 #include "wx/intl.h"
22 #include "wx/bitmap.h"
23 #include "wx/module.h"
24 
25 // A hack based on one from tif_jpeg.c to overcome the problem on Windows
26 // of rpcndr.h defining boolean with a different type to the jpeg headers.
27 //
28 // This hack is only necessary for an external jpeg library, the builtin one
29 // usually used on Windows doesn't use the type boolean, so always works.
30 //
31 #ifdef wxHACK_BOOLEAN
32     #define HAVE_BOOLEAN
33     #define boolean wxHACK_BOOLEAN
34 #endif
35 
36 extern "C"
37 {
38     #if defined(__WXMSW__)
39         #define XMD_H
40     #endif
41     #include "jpeglib.h"
42 }
43 
44 #ifndef HAVE_WXJPEG_BOOLEAN
45 typedef boolean wxjpeg_boolean;
46 #endif
47 
48 #include "wx/filefn.h"
49 #include "wx/wfstream.h"
50 
51 // For memcpy
52 #include <string.h>
53 // For JPEG library error handling
54 #include <setjmp.h>
55 
56 #ifdef __SALFORDC__
57 #undef FAR
58 #endif
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 // wxJPGHandler
80 //-----------------------------------------------------------------------------
81 
82 IMPLEMENT_DYNAMIC_CLASS(wxJPGHandler,wxImageHandler)
83 
84 #if wxUSE_STREAMS
85 
86 //------------- JPEG Data Source Manager
87 
88 #define JPEG_IO_BUFFER_SIZE   2048
89 
90 typedef struct {
91     struct jpeg_source_mgr pub;   /* public fields */
92 
93     JOCTET* buffer;               /* start of buffer */
94     wxInputStream *stream;
95 } wx_source_mgr;
96 
97 typedef wx_source_mgr * wx_src_ptr;
98 
99 extern "C"
100 {
101 
wx_init_source1(j_decompress_ptr WXUNUSED (cinfo))102 CPP_METHODDEF(void) wx_init_source1 ( j_decompress_ptr WXUNUSED(cinfo) )
103 {
104 }
105 
wx_fill_input_buffer1(j_decompress_ptr cinfo)106 CPP_METHODDEF(wxjpeg_boolean) wx_fill_input_buffer1 ( 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 
wx_skip_input_data1(j_decompress_ptr cinfo,long num_bytes)123 CPP_METHODDEF(void) wx_skip_input_data1 ( 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 
wx_term_source1(j_decompress_ptr cinfo)139 CPP_METHODDEF(void) wx_term_source1 ( 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 
151 struct wx_error_mgr : public 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 
wx_error_exit1(j_common_ptr cinfo)160 CPP_METHODDEF(void) wx_error_exit1 (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  */
wx_ignore_message1(j_common_ptr WXUNUSED (cinfo))179 CPP_METHODDEF(void) wx_ignore_message1 (j_common_ptr WXUNUSED(cinfo))
180 {
181 }
182 
wx_jpeg_io_src(j_decompress_ptr cinfo,wxInputStream & infile)183 void 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_source1;
199     src->pub.fill_input_buffer = wx_fill_input_buffer1;
200     src->pub.skip_input_data = wx_skip_input_data1;
201     src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
202     src->pub.term_source = wx_term_source1;
203 }
204 
205 } // extern "C"
206 
wx_cmyk_to_rgb(unsigned char * rgb,const unsigned char * cmyk)207 static 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 
LoadFile(wxImage * image,wxInputStream & stream,bool verbose,int WXUNUSED (index))229 bool wxJPGHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int WXUNUSED(index) )
230 {
231     wxCHECK_MSG( image, false, wxT("NULL image pointer") );
232 
233     struct jpeg_decompress_struct cinfo;
234     wx_error_mgr jerr;
235     unsigned char *ptr;
236 
237     // save this before calling Destroy()
238     const unsigned maxWidth = image->GetOptionInt(wxT("max_width")),
239                    maxHeight = image->GetOptionInt(wxT("max_height"));
240     image->Destroy();
241 
242     cinfo.err = jpeg_std_error( &jerr );
243     jerr.error_exit = wx_error_exit1;
244 
245     if (!verbose)
246         cinfo.err->output_message = wx_ignore_message1;
247 
248     /* Establish the setjmp return context for wx_error_exit to use. */
249     if (setjmp(jerr.setjmp_buffer)) {
250       /* If we get here, the JPEG code has signaled an error.
251        * We need to clean up the JPEG object, close the input file, and return.
252        */
253       if (verbose)
254       {
255         wxLogError(_("JPEG: Couldn't load - file is probably corrupted."));
256       }
257       (cinfo.src->term_source)(&cinfo);
258       jpeg_destroy_decompress(&cinfo);
259       if (image->Ok()) image->Destroy();
260       return false;
261     }
262 
263     jpeg_create_decompress( &cinfo );
264     wx_jpeg_io_src( &cinfo, stream );
265     jpeg_read_header( &cinfo, TRUE );
266 
267     int bytesPerPixel;
268     if ((cinfo.out_color_space == JCS_CMYK) || (cinfo.out_color_space == JCS_YCCK))
269     {
270         cinfo.out_color_space = JCS_CMYK;
271         bytesPerPixel = 4;
272     }
273     else // all the rest is treated as RGB
274     {
275         cinfo.out_color_space = JCS_RGB;
276         bytesPerPixel = 3;
277     }
278 
279     // scale the picture to fit in the specified max size if necessary
280     if ( maxWidth > 0 || maxHeight > 0 )
281     {
282         unsigned& scale = cinfo.scale_denom;
283         while ( (maxWidth && (cinfo.image_width / scale > maxWidth)) ||
284                     (maxHeight && (cinfo.image_height / scale > maxHeight)) )
285         {
286             scale *= 2;
287         }
288     }
289 
290     jpeg_start_decompress( &cinfo );
291 
292     image->Create( cinfo.output_width, cinfo.output_height );
293     if (!image->Ok()) {
294         jpeg_finish_decompress( &cinfo );
295         jpeg_destroy_decompress( &cinfo );
296         return false;
297     }
298     image->SetMask( false );
299     ptr = image->GetData();
300 
301     unsigned stride = cinfo.output_width * bytesPerPixel;
302     JSAMPARRAY tempbuf = (*cinfo.mem->alloc_sarray)
303                             ((j_common_ptr) &cinfo, JPOOL_IMAGE, stride, 1 );
304 
305     while ( cinfo.output_scanline < cinfo.output_height )
306     {
307         jpeg_read_scanlines( &cinfo, tempbuf, 1 );
308         if (cinfo.out_color_space == JCS_RGB)
309         {
310             memcpy( ptr, tempbuf[0], stride );
311             ptr += stride;
312         }
313         else // CMYK
314         {
315             const unsigned char* inptr = (const unsigned char*) tempbuf[0];
316             for (size_t i = 0; i < cinfo.output_width; i++)
317             {
318                 wx_cmyk_to_rgb(ptr, inptr);
319                 ptr += 3;
320                 inptr += 4;
321             }
322         }
323     }
324 
325     // set up resolution if available: it's part of optional JFIF APP0 chunk
326     if ( cinfo.saw_JFIF_marker )
327     {
328         image->SetOption(wxIMAGE_OPTION_RESOLUTIONX, cinfo.X_density);
329         image->SetOption(wxIMAGE_OPTION_RESOLUTIONY, cinfo.Y_density);
330 
331         // we use the same values for this option as libjpeg so we don't need
332         // any conversion here
333         image->SetOption(wxIMAGE_OPTION_RESOLUTIONUNIT, cinfo.density_unit);
334     }
335 
336     jpeg_finish_decompress( &cinfo );
337     jpeg_destroy_decompress( &cinfo );
338     return true;
339 }
340 
341 typedef struct {
342     struct jpeg_destination_mgr pub;
343 
344     wxOutputStream *stream;
345     JOCTET * buffer;
346 } wx_destination_mgr;
347 
348 typedef wx_destination_mgr * wx_dest_ptr;
349 
350 #define OUTPUT_BUF_SIZE  4096    /* choose an efficiently fwrite'able size */
351 
352 extern "C"
353 {
354 
wx_init_destination1(j_compress_ptr cinfo)355 CPP_METHODDEF(void) wx_init_destination1 (j_compress_ptr cinfo)
356 {
357     wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
358 
359     /* Allocate the output buffer --- it will be released when done with image */
360     dest->buffer = (JOCTET *)
361         (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
362         OUTPUT_BUF_SIZE * sizeof(JOCTET));
363     dest->pub.next_output_byte = dest->buffer;
364     dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
365 }
366 
wx_empty_output_buffer1(j_compress_ptr cinfo)367 CPP_METHODDEF(wxjpeg_boolean) wx_empty_output_buffer1 (j_compress_ptr cinfo)
368 {
369     wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
370 
371     dest->stream->Write(dest->buffer, OUTPUT_BUF_SIZE);
372     dest->pub.next_output_byte = dest->buffer;
373     dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
374     return TRUE;
375 }
376 
wx_term_destination1(j_compress_ptr cinfo)377 CPP_METHODDEF(void) wx_term_destination1 (j_compress_ptr cinfo)
378 {
379     wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
380     size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
381     /* Write any data remaining in the buffer */
382     if (datacount > 0)
383         dest->stream->Write(dest->buffer, datacount);
384 }
385 
wx_jpeg_io_dest(j_compress_ptr cinfo,wxOutputStream & outfile)386 GLOBAL(void) wx_jpeg_io_dest (j_compress_ptr cinfo, wxOutputStream& outfile)
387 {
388     wx_dest_ptr dest;
389 
390     if (cinfo->dest == NULL) {    /* first time for this JPEG object? */
391         cinfo->dest = (struct jpeg_destination_mgr *)
392             (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
393             sizeof(wx_destination_mgr));
394     }
395 
396     dest = (wx_dest_ptr) cinfo->dest;
397     dest->pub.init_destination = wx_init_destination1;
398     dest->pub.empty_output_buffer = wx_empty_output_buffer1;
399     dest->pub.term_destination = wx_term_destination1;
400     dest->stream = &outfile;
401 }
402 
403 } // extern "C"
404 
SaveFile(wxImage * image,wxOutputStream & stream,bool verbose)405 bool wxJPGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
406 {
407     struct jpeg_compress_struct cinfo;
408     wx_error_mgr jerr;
409     JSAMPROW row_pointer[1];    /* pointer to JSAMPLE row[s] */
410     JSAMPLE *image_buffer;
411     int stride;                /* physical row width in image buffer */
412 
413     cinfo.err = jpeg_std_error(&jerr);
414     jerr.error_exit = wx_error_exit1;
415 
416     if (!verbose)
417         cinfo.err->output_message = wx_ignore_message1;
418 
419     /* Establish the setjmp return context for wx_error_exit to use. */
420     if (setjmp(jerr.setjmp_buffer))
421     {
422         /* If we get here, the JPEG code has signaled an error.
423          * We need to clean up the JPEG object, close the input file, and return.
424          */
425          if (verbose)
426          {
427             wxLogError(_("JPEG: Couldn't save image."));
428          }
429          jpeg_destroy_compress(&cinfo);
430          return false;
431     }
432 
433     jpeg_create_compress(&cinfo);
434     wx_jpeg_io_dest(&cinfo, stream);
435 
436     cinfo.image_width = image->GetWidth();
437     cinfo.image_height = image->GetHeight();
438     cinfo.input_components = 3;
439     cinfo.in_color_space = JCS_RGB;
440     jpeg_set_defaults(&cinfo);
441 
442     // TODO: 3rd parameter is force_baseline, what value should this be?
443     // Code says: "If force_baseline is TRUE, the computed quantization table entries
444     // are limited to 1..255 for JPEG baseline compatibility."
445     // 'Quality' is a number between 0 (terrible) and 100 (very good).
446     // The default (in jcparam.c, jpeg_set_defaults) is 75,
447     // and force_baseline is TRUE.
448     if (image->HasOption(wxIMAGE_OPTION_QUALITY))
449         jpeg_set_quality(&cinfo, image->GetOptionInt(wxIMAGE_OPTION_QUALITY), TRUE);
450 
451 #if wxCHECK_VERSION(2,9,0)
452     // set the resolution fields in the output file
453     int resX, resY;
454     wxImageResolution res = GetResolutionFromOptions(*image, &resX, &resY);
455     if ( res != wxIMAGE_RESOLUTION_NONE )
456     {
457         cinfo.X_density = resX;
458         cinfo.Y_density = resY;
459 
460         // it so happens that wxIMAGE_RESOLUTION_INCHES/CM values are the same
461         // ones as used by libjpeg, so we can assign them directly
462         cinfo.density_unit = res;
463     }
464 #endif
465 
466     jpeg_start_compress(&cinfo, TRUE);
467 
468     stride = cinfo.image_width * 3;    /* JSAMPLEs per row in image_buffer */
469     image_buffer = image->GetData();
470     while (cinfo.next_scanline < cinfo.image_height) {
471         row_pointer[0] = &image_buffer[cinfo.next_scanline * stride];
472         jpeg_write_scanlines( &cinfo, row_pointer, 1 );
473     }
474     jpeg_finish_compress(&cinfo);
475     jpeg_destroy_compress(&cinfo);
476 
477     return true;
478 }
479 
480 #ifdef __VISUALC__
481     #pragma warning(default:4611)
482 #endif /* VC++ */
483 
DoCanRead(wxInputStream & stream)484 bool wxJPGHandler::DoCanRead( wxInputStream& stream )
485 {
486     unsigned char hdr[2];
487 
488     if ( !stream.Read(hdr, WXSIZEOF(hdr)) )     // it's ok to modify the stream position here
489         return false;
490 
491     return hdr[0] == 0xFF && hdr[1] == 0xD8;
492 }
493 
494 #endif   // wxUSE_STREAMS
495 
496 #endif   // wxUSE_LIBJPEG
497 
498 /// Load image
LoadImageFile(wxImage & img,wxInputStream & stream,long type,int index)499 bool LoadImageFile(wxImage& img, wxInputStream& stream, long type, int index)
500 {
501     wxImageHandler *handler;
502 
503     if ( type == wxBITMAP_TYPE_ANY )
504     {
505         wxList &list = wxImage::GetHandlers();
506         for ( wxList::Node* node = list.GetFirst(); node; node = node->GetNext() )
507         {
508              handler=(wxImageHandler*)node->GetData();
509              if ( handler->CanRead(stream) )
510                  return handler->LoadFile(&img, stream, true/*verbose*/, index);
511         }
512         wxLogWarning( _("No handler found for image type.") );
513         return false;
514     }
515 
516     handler = wxImage::FindHandler(type);
517     if (handler == 0)
518     {
519         wxLogWarning( _("No image handler for type %d defined."), type );
520         return false;
521     }
522 
523     return handler->LoadFile(&img, stream, true/*verbose*/, index);
524 }
525 
LoadImageFile(wxImage & img,const wxString & filename,long type,int index)526 bool LoadImageFile(wxImage& img, const wxString& filename, long type, int index)
527 {
528 #if wxUSE_STREAMS
529     if (wxFileExists(filename))
530     {
531         wxFileInputStream stream(filename);
532         wxBufferedInputStream bstream( stream );
533         return LoadImageFile(img, bstream, type, index);
534     }
535     else
536     {
537         wxLogError( _("Can't load image from file '%s': file does not exist."), filename.c_str() );
538         return false;
539     }
540 #else // !wxUSE_STREAMS
541     return false;
542 #endif // wxUSE_STREAMS
543 }
544 #endif // !wxCHECK_VERSION(2,9,0)
545