1 /* -*- mode: C; c-file-style: "linux" -*- */
2 /* GdkPixbuf library - JPEG image loader
4 * Copyright (C) 1999 Michael Zucchi
5 * Copyright (C) 1999 The Free Software Foundation
7 * Progressive loading code Copyright (C) 1999 Red Hat, Inc.
9 * Authors: Michael Zucchi <zucchi@zedzone.mmc.com.au>
10 * Federico Mena-Quintero <federico@gimp.org>
11 * Michael Fulbright <drmike@redhat.com>
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2 of the License, or (at your option) any later version.
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with this library; if not, write to the
25 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 * Boston, MA 02111-1307, USA.
36 #include "gdk-pixbuf-private.h"
37 #include "gdk-pixbuf-io.h"
39 #ifndef HAVE_SIGSETJMP
40 #define sigjmp_buf jmp_buf
41 #define sigsetjmp(jb, x) setjmp(jb)
42 #define siglongjmp longjmp
46 /* we are a "source manager" as far as libjpeg is concerned */
47 #define JPEG_PROG_BUF_SIZE 65536
50 struct jpeg_source_mgr pub; /* public fields */
52 JOCTET buffer[JPEG_PROG_BUF_SIZE]; /* start of buffer */
53 long skip_next; /* number of bytes to skip next read */
57 typedef my_source_mgr * my_src_ptr;
59 /* error handler data */
60 struct error_handler_data {
61 struct jpeg_error_mgr pub;
62 sigjmp_buf setjmp_buffer;
66 /* progressive loader context */
68 ModuleSizeFunc size_func;
69 ModuleUpdatedNotifyFunc updated_func;
70 ModulePreparedNotifyFunc prepared_func;
74 guchar *dptr; /* current position in pixbuf */
76 gboolean did_prescan; /* are we in image data yet? */
77 gboolean got_header; /* have we loaded jpeg header? */
78 gboolean src_initialized;/* TRUE when jpeg lib initialized */
79 gboolean in_output; /* did we get suspended in an output pass? */
80 struct jpeg_decompress_struct cinfo;
81 struct error_handler_data jerr;
84 static GdkPixbuf *gdk_pixbuf__jpeg_image_load (FILE *f, GError **error);
85 static gpointer gdk_pixbuf__jpeg_image_begin_load (ModuleSizeFunc func0,
86 ModulePreparedNotifyFunc func1,
87 ModuleUpdatedNotifyFunc func2,
90 static gboolean gdk_pixbuf__jpeg_image_stop_load (gpointer context, GError **error);
91 static gboolean gdk_pixbuf__jpeg_image_load_increment(gpointer context,
92 const guchar *buf, guint size,
97 fatal_error_handler (j_common_ptr cinfo)
99 struct error_handler_data *errmgr;
100 char buffer[JMSG_LENGTH_MAX];
102 errmgr = (struct error_handler_data *) cinfo->err;
104 /* Create the message */
105 (* cinfo->err->format_message) (cinfo, buffer);
107 /* broken check for *error == NULL for robustness against
108 * crappy JPEG library
110 if (errmgr->error && *errmgr->error == NULL) {
111 g_set_error (errmgr->error,
113 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
114 _("Error interpreting JPEG image file (%s)"),
118 siglongjmp (errmgr->setjmp_buffer, 1);
120 g_assert_not_reached ();
124 output_message_handler (j_common_ptr cinfo)
126 /* This method keeps libjpeg from dumping crap to stderr */
131 /* explode gray image data from jpeg library into rgb components in pixbuf */
133 explode_gray_into_buf (struct jpeg_decompress_struct *cinfo,
139 g_return_if_fail (cinfo != NULL);
140 g_return_if_fail (cinfo->output_components == 1);
141 g_return_if_fail (cinfo->out_color_space == JCS_GRAYSCALE);
143 /* Expand grey->colour. Expand from the end of the
144 * memory down, so we can use the same buffer.
146 w = cinfo->output_width;
147 for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
150 from = lines[i] + w - 1;
151 to = lines[i] + (w - 1) * 3;
152 for (j = w - 1; j >= 0; j--) {
164 convert_cmyk_to_rgb (struct jpeg_decompress_struct *cinfo,
169 g_return_if_fail (cinfo != NULL);
170 g_return_if_fail (cinfo->output_components == 4);
171 g_return_if_fail (cinfo->out_color_space == JCS_CMYK);
173 for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
177 for (j = 0; j < cinfo->output_width; j++) {
183 if (cinfo->saw_Adobe_marker) {
189 p[0] = (255 - k)*(255 - c) / 255;
190 p[1] = (255 - k)*(255 - m) / 255;
191 p[2] = (255 - k)*(255 - y) / 255;
200 struct jpeg_source_mgr pub; /* public fields */
202 FILE * infile; /* source stream */
203 JOCTET * buffer; /* start of buffer */
204 boolean start_of_file; /* have we gotten any data yet? */
207 typedef stdio_source_mgr * stdio_src_ptr;
210 stdio_init_source (j_decompress_ptr cinfo)
212 stdio_src_ptr src = (stdio_src_ptr)cinfo->src;
213 src->start_of_file = FALSE;
217 stdio_fill_input_buffer (j_decompress_ptr cinfo)
219 stdio_src_ptr src = (stdio_src_ptr) cinfo->src;
222 nbytes = fread (src->buffer, 1, JPEG_PROG_BUF_SIZE, src->infile);
226 if (src->start_of_file) /* Treat empty input file as fatal error */
227 ERREXIT(cinfo, JERR_INPUT_EMPTY);
228 WARNMS(cinfo, JWRN_JPEG_EOF);
230 /* Insert a fake EOI marker */
231 src->buffer[0] = (JOCTET) 0xFF;
232 src->buffer[1] = (JOCTET) JPEG_EOI;
236 src->pub.next_input_byte = src->buffer;
237 src->pub.bytes_in_buffer = nbytes;
238 src->start_of_file = FALSE;
244 stdio_skip_input_data (j_decompress_ptr cinfo, long num_bytes)
246 stdio_src_ptr src = (stdio_src_ptr) cinfo->src;
249 while (num_bytes > (long) src->pub.bytes_in_buffer) {
250 num_bytes -= (long) src->pub.bytes_in_buffer;
251 (void)stdio_fill_input_buffer(cinfo);
253 src->pub.next_input_byte += (size_t) num_bytes;
254 src->pub.bytes_in_buffer -= (size_t) num_bytes;
259 stdio_term_source (j_decompress_ptr cinfo)
264 colorspace_name (const J_COLOR_SPACE jpeg_color_space)
266 switch (jpeg_color_space) {
267 case JCS_UNKNOWN: return "UNKNOWN";
268 case JCS_GRAYSCALE: return "GRAYSCALE";
269 case JCS_RGB: return "RGB";
270 case JCS_YCbCr: return "YCbCr";
271 case JCS_CMYK: return "CMYK";
272 case JCS_YCCK: return "YCCK";
273 default: return "invalid";
277 /* Shared library entry point */
279 gdk_pixbuf__jpeg_image_load (FILE *f, GError **error)
282 GdkPixbuf * volatile pixbuf = NULL;
284 guchar *lines[4]; /* Used to expand rows, via rec_outbuf_height,
285 * from the header file:
286 * " Usually rec_outbuf_height will be 1 or 2,
290 struct jpeg_decompress_struct cinfo;
291 struct error_handler_data jerr;
294 /* setup error handler */
295 cinfo.err = jpeg_std_error (&jerr.pub);
296 jerr.pub.error_exit = fatal_error_handler;
297 jerr.pub.output_message = output_message_handler;
301 if (sigsetjmp (jerr.setjmp_buffer, 1)) {
302 /* Whoops there was a jpeg error */
304 g_object_unref (pixbuf);
306 jpeg_destroy_decompress (&cinfo);
310 /* load header, setup */
311 jpeg_create_decompress (&cinfo);
313 cinfo.src = (struct jpeg_source_mgr *)
314 (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
315 sizeof (stdio_source_mgr));
316 src = (stdio_src_ptr) cinfo.src;
317 src->buffer = (JOCTET *)
318 (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
319 JPEG_PROG_BUF_SIZE * sizeof (JOCTET));
321 src->pub.init_source = stdio_init_source;
322 src->pub.fill_input_buffer = stdio_fill_input_buffer;
323 src->pub.skip_input_data = stdio_skip_input_data;
324 src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
325 src->pub.term_source = stdio_term_source;
327 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
328 src->pub.next_input_byte = NULL; /* until buffer loaded */
330 jpeg_read_header (&cinfo, TRUE);
331 jpeg_start_decompress (&cinfo);
332 cinfo.do_fancy_upsampling = FALSE;
333 cinfo.do_block_smoothing = FALSE;
335 pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
336 cinfo.out_color_components == 4 ? TRUE : FALSE,
337 8, cinfo.output_width, cinfo.output_height);
340 jpeg_destroy_decompress (&cinfo);
342 /* broken check for *error == NULL for robustness against
343 * crappy JPEG library
345 if (error && *error == NULL) {
348 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
349 _("Insufficient memory to load image, try exiting some applications to free memory"));
355 dptr = pixbuf->pixels;
357 /* decompress all the lines, a few at a time */
358 while (cinfo.output_scanline < cinfo.output_height) {
360 for (i = 0; i < cinfo.rec_outbuf_height; i++) {
362 dptr += pixbuf->rowstride;
365 jpeg_read_scanlines (&cinfo, lines, cinfo.rec_outbuf_height);
367 switch (cinfo.out_color_space) {
369 explode_gray_into_buf (&cinfo, lines);
375 convert_cmyk_to_rgb (&cinfo, lines);
378 g_object_unref (pixbuf);
379 if (error && *error == NULL) {
382 GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
383 _("Unsupported JPEG color space (%s)"),
384 colorspace_name (cinfo.out_color_space));
387 jpeg_destroy_decompress (&cinfo);
392 jpeg_finish_decompress (&cinfo);
393 jpeg_destroy_decompress (&cinfo);
399 /**** Progressive image loading handling *****/
401 /* these routines required because we are acting as a source manager for */
404 init_source (j_decompress_ptr cinfo)
406 my_src_ptr src = (my_src_ptr) cinfo->src;
413 term_source (j_decompress_ptr cinfo)
415 /* XXXX - probably should scream something has happened */
419 /* for progressive loading (called "I/O Suspension" by libjpeg docs) */
420 /* we do nothing except return "FALSE" */
422 fill_input_buffer (j_decompress_ptr cinfo)
429 skip_input_data (j_decompress_ptr cinfo, long num_bytes)
431 my_src_ptr src = (my_src_ptr) cinfo->src;
434 /* move as far as we can into current buffer */
435 /* then set skip_next to catch the rest */
437 num_can_do = MIN (src->pub.bytes_in_buffer, num_bytes);
438 src->pub.next_input_byte += (size_t) num_can_do;
439 src->pub.bytes_in_buffer -= (size_t) num_can_do;
441 src->skip_next = num_bytes - num_can_do;
447 * func - called when we have pixmap created (but no image data)
448 * user_data - passed as arg 1 to func
449 * return context (opaque to user)
453 gdk_pixbuf__jpeg_image_begin_load (ModuleSizeFunc size_func,
454 ModulePreparedNotifyFunc prepared_func,
455 ModuleUpdatedNotifyFunc updated_func,
459 JpegProgContext *context;
462 context = g_new0 (JpegProgContext, 1);
463 context->size_func = size_func;
464 context->prepared_func = prepared_func;
465 context->updated_func = updated_func;
466 context->user_data = user_data;
467 context->pixbuf = NULL;
468 context->got_header = FALSE;
469 context->did_prescan = FALSE;
470 context->src_initialized = FALSE;
471 context->in_output = FALSE;
473 /* create libjpeg structures */
474 jpeg_create_decompress (&context->cinfo);
476 context->cinfo.src = (struct jpeg_source_mgr *) g_try_malloc (sizeof (my_source_mgr));
477 if (!context->cinfo.src) {
480 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
481 _("Couldn't allocate memory for loading JPEG file"));
484 memset (context->cinfo.src, 0, sizeof (my_source_mgr));
486 src = (my_src_ptr) context->cinfo.src;
488 context->cinfo.err = jpeg_std_error (&context->jerr.pub);
489 context->jerr.pub.error_exit = fatal_error_handler;
490 context->jerr.pub.output_message = output_message_handler;
491 context->jerr.error = error;
493 src = (my_src_ptr) context->cinfo.src;
494 src->pub.init_source = init_source;
495 src->pub.fill_input_buffer = fill_input_buffer;
496 src->pub.skip_input_data = skip_input_data;
497 src->pub.resync_to_restart = jpeg_resync_to_restart;
498 src->pub.term_source = term_source;
499 src->pub.bytes_in_buffer = 0;
500 src->pub.next_input_byte = NULL;
502 context->jerr.error = NULL;
504 return (gpointer) context;
508 * context - returned from image_begin_load
510 * free context, unref gdk_pixbuf
513 gdk_pixbuf__jpeg_image_stop_load (gpointer data, GError **error)
515 JpegProgContext *context = (JpegProgContext *) data;
517 g_return_val_if_fail (context != NULL, TRUE);
519 /* FIXME this thing needs to report errors if
520 * we have unused image data
524 g_object_unref (context->pixbuf);
526 /* if we have an error? */
527 if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
528 jpeg_destroy_decompress (&context->cinfo);
530 jpeg_finish_decompress(&context->cinfo);
531 jpeg_destroy_decompress(&context->cinfo);
534 if (context->cinfo.src) {
535 my_src_ptr src = (my_src_ptr) context->cinfo.src;
549 * context - from image_begin_load
550 * buf - new image data
551 * size - length of new image data
553 * append image data onto inrecrementally built output image
556 gdk_pixbuf__jpeg_image_load_increment (gpointer data,
557 const guchar *buf, guint size,
560 JpegProgContext *context = (JpegProgContext *)data;
561 struct jpeg_decompress_struct *cinfo;
563 guint num_left, num_copy;
564 guint last_bytes_left;
570 g_return_val_if_fail (context != NULL, FALSE);
571 g_return_val_if_fail (buf != NULL, FALSE);
573 src = (my_src_ptr) context->cinfo.src;
575 cinfo = &context->cinfo;
577 context->jerr.error = error;
579 /* check for fatal error */
580 if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
584 /* skip over data if requested, handle unsigned int sizes cleanly */
585 /* only can happen if we've already called jpeg_get_header once */
586 if (context->src_initialized && src->skip_next) {
587 if (src->skip_next > size) {
588 src->skip_next -= size;
591 num_left = size - src->skip_next;
592 bufhd = buf + src->skip_next;
608 /* handle any data from caller we haven't processed yet */
610 if(src->pub.bytes_in_buffer &&
611 src->pub.next_input_byte != src->buffer)
612 memmove(src->buffer, src->pub.next_input_byte,
613 src->pub.bytes_in_buffer);
616 num_copy = MIN (JPEG_PROG_BUF_SIZE - src->pub.bytes_in_buffer,
619 memcpy(src->buffer + src->pub.bytes_in_buffer, bufhd,num_copy);
620 src->pub.next_input_byte = src->buffer;
621 src->pub.bytes_in_buffer += num_copy;
623 num_left -= num_copy;
625 /* did anything change from last pass, if not return */
627 last_bytes_left = src->pub.bytes_in_buffer;
629 } else if (src->pub.bytes_in_buffer == last_bytes_left)
632 last_bytes_left = src->pub.bytes_in_buffer;
635 /* should not go through twice and not pull bytes out of buf */
639 /* try to load jpeg header */
640 if (!context->got_header) {
643 rc = jpeg_read_header (cinfo, TRUE);
644 context->src_initialized = TRUE;
646 if (rc == JPEG_SUSPENDED)
649 context->got_header = TRUE;
651 width = cinfo->image_width;
652 height = cinfo->image_height;
653 (* context->size_func) (&width, &height, context->user_data);
654 for (cinfo->scale_denom = 2; cinfo->scale_denom <= 8; cinfo->scale_denom *= 2) {
655 jpeg_calc_output_dimensions (cinfo);
656 if (cinfo->output_width < width || cinfo->output_height < height) {
657 cinfo->scale_denom /= 2;
661 jpeg_calc_output_dimensions (cinfo);
663 context->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
664 cinfo->output_components == 4 ? TRUE : FALSE,
667 cinfo->output_height);
669 if (context->pixbuf == NULL) {
672 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
673 _("Couldn't allocate memory for loading JPEG file"));
677 /* Use pixbuf buffer to store decompressed data */
678 context->dptr = context->pixbuf->pixels;
680 /* Notify the client that we are ready to go */
681 (* context->prepared_func) (context->pixbuf,
685 } else if (!context->did_prescan) {
688 /* start decompression */
689 cinfo->buffered_image = TRUE;
690 rc = jpeg_start_decompress (cinfo);
691 cinfo->do_fancy_upsampling = FALSE;
692 cinfo->do_block_smoothing = FALSE;
694 if (rc == JPEG_SUSPENDED)
697 context->did_prescan = TRUE;
699 /* we're decompressing so feed jpeg lib scanlines */
705 /* keep going until we've done all passes */
706 while (!jpeg_input_complete (cinfo)) {
707 if (!context->in_output) {
708 if (jpeg_start_output (cinfo, cinfo->input_scan_number)) {
709 context->in_output = TRUE;
710 context->dptr = context->pixbuf->pixels;
715 /* keep going until we've done all scanlines */
716 while (cinfo->output_scanline < cinfo->output_height) {
718 rowptr = context->dptr;
719 for (i=0; i < cinfo->rec_outbuf_height; i++) {
721 rowptr += context->pixbuf->rowstride;
724 nlines = jpeg_read_scanlines (cinfo, lines,
725 cinfo->rec_outbuf_height);
729 switch (cinfo->out_color_space) {
731 explode_gray_into_buf (cinfo, lines);
737 convert_cmyk_to_rgb (cinfo, lines);
740 if (error && *error == NULL) {
743 GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
744 _("Unsupported JPEG color space (%s)"),
745 colorspace_name (cinfo->out_color_space));
751 context->dptr += nlines * context->pixbuf->rowstride;
753 /* send updated signal */
754 (* context->updated_func) (context->pixbuf,
756 cinfo->output_scanline-1,
761 if (cinfo->output_scanline >= cinfo->output_height &&
762 jpeg_finish_output (cinfo))
763 context->in_output = FALSE;
767 if (jpeg_input_complete (cinfo))
768 /* did entire image */
779 gdk_pixbuf__jpeg_image_save (FILE *f,
785 /* FIXME error handling is broken */
787 struct jpeg_compress_struct cinfo;
790 guchar *pixels = NULL;
793 volatile int quality = 75; /* default; must be between 0 and 100 */
797 struct error_handler_data jerr;
800 gchar **kiter = keys;
801 gchar **viter = values;
804 if (strcmp (*kiter, "quality") == 0) {
806 quality = strtol (*viter, &endptr, 10);
808 if (endptr == *viter) {
811 GDK_PIXBUF_ERROR_BAD_OPTION,
812 _("JPEG quality must be a value between 0 and 100; value '%s' could not be parsed."),
820 /* This is a user-visible error;
821 * lets people skip the range-checking
826 GDK_PIXBUF_ERROR_BAD_OPTION,
827 _("JPEG quality must be a value between 0 and 100; value '%d' is not allowed."),
833 g_warning ("Bad option name '%s' passed to JPEG saver",
843 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
845 w = gdk_pixbuf_get_width (pixbuf);
846 h = gdk_pixbuf_get_height (pixbuf);
848 /* no image data? abort */
849 pixels = gdk_pixbuf_get_pixels (pixbuf);
850 g_return_val_if_fail (pixels != NULL, FALSE);
852 /* allocate a small buffer to convert image data */
853 buf = g_try_malloc (w * 3 * sizeof (guchar));
857 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
858 _("Couldn't allocate memory for loading JPEG file"));
862 /* set up error handling */
863 jerr.pub.error_exit = fatal_error_handler;
864 jerr.pub.output_message = output_message_handler;
867 cinfo.err = jpeg_std_error (&(jerr.pub));
868 if (sigsetjmp (jerr.setjmp_buffer, 1)) {
869 jpeg_destroy_compress (&cinfo);
874 /* setup compress params */
875 jpeg_create_compress (&cinfo);
876 jpeg_stdio_dest (&cinfo, f);
877 cinfo.image_width = w;
878 cinfo.image_height = h;
879 cinfo.input_components = 3;
880 cinfo.in_color_space = JCS_RGB;
882 /* set up jepg compression parameters */
883 jpeg_set_defaults (&cinfo);
884 jpeg_set_quality (&cinfo, quality, TRUE);
885 jpeg_start_compress (&cinfo, TRUE);
886 /* get the start pointer */
888 /* go one scanline at a time... and save */
890 while (cinfo.next_scanline < cinfo.image_height) {
891 /* convert scanline from ARGB to RGB packed */
892 for (j = 0; j < w; j++)
893 memcpy (&(buf[j*3]), &(ptr[i*rowstride + j*3]), 3);
896 jbuf = (JSAMPROW *)(&buf);
897 jpeg_write_scanlines (&cinfo, jbuf, 1);
904 jpeg_finish_compress (&cinfo);
910 gdk_pixbuf__jpeg_fill_vtable (GdkPixbufModule *module)
912 module->load = gdk_pixbuf__jpeg_image_load;
913 module->begin_load = gdk_pixbuf__jpeg_image_begin_load;
914 module->stop_load = gdk_pixbuf__jpeg_image_stop_load;
915 module->load_increment = gdk_pixbuf__jpeg_image_load_increment;
916 module->save = gdk_pixbuf__jpeg_image_save;