1 /* GdkPixbuf library - JPEG image loader
3 * Copyright (C) 1999 Michael Zucchi
4 * Copyright (C) 1999 The Free Software Foundation
6 * Progressive loading code Copyright (C) 1999 Red Hat, Inc.
8 * Authors: Michael Zucchi <zucchi@zedzone.mmc.com.au>
9 * Federico Mena-Quintero <federico@gimp.org>
10 * Michael Fulbright <drmike@redhat.com>
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the
24 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 * Boston, MA 02111-1307, USA.
35 #include "gdk-pixbuf-private.h"
36 #include "gdk-pixbuf-io.h"
38 #ifndef HAVE_SIGSETJMP
39 #define sigjmp_buf jmp_buf
40 #define sigsetjmp(jb, x) setjmp(jb)
41 #define siglongjmp longjmp
45 /* we are a "source manager" as far as libjpeg is concerned */
46 #define JPEG_PROG_BUF_SIZE 65536
49 struct jpeg_source_mgr pub; /* public fields */
51 JOCTET buffer[JPEG_PROG_BUF_SIZE]; /* start of buffer */
52 long skip_next; /* number of bytes to skip next read */
56 typedef my_source_mgr * my_src_ptr;
58 /* error handler data */
59 struct error_handler_data {
60 struct jpeg_error_mgr pub;
61 sigjmp_buf setjmp_buffer;
65 /* progressive loader context */
67 ModuleUpdatedNotifyFunc updated_func;
68 ModulePreparedNotifyFunc prepared_func;
72 guchar *dptr; /* current position in pixbuf */
74 gboolean did_prescan; /* are we in image data yet? */
75 gboolean got_header; /* have we loaded jpeg header? */
76 gboolean src_initialized;/* TRUE when jpeg lib initialized */
77 gboolean in_output; /* did we get suspended in an output pass? */
78 struct jpeg_decompress_struct cinfo;
79 struct error_handler_data jerr;
82 static GdkPixbuf *gdk_pixbuf__jpeg_image_load (FILE *f, GError **error);
83 static gpointer gdk_pixbuf__jpeg_image_begin_load (ModulePreparedNotifyFunc func,
84 ModuleUpdatedNotifyFunc func2,
87 static gboolean gdk_pixbuf__jpeg_image_stop_load (gpointer context, GError **error);
88 static gboolean gdk_pixbuf__jpeg_image_load_increment(gpointer context,
89 const guchar *buf, guint size,
94 fatal_error_handler (j_common_ptr cinfo)
96 struct error_handler_data *errmgr;
97 char buffer[JMSG_LENGTH_MAX];
99 errmgr = (struct error_handler_data *) cinfo->err;
101 /* Create the message */
102 (* cinfo->err->format_message) (cinfo, buffer);
104 /* broken check for *error == NULL for robustness against
105 * crappy JPEG library
107 if (errmgr->error && *errmgr->error == NULL) {
108 g_set_error (errmgr->error,
110 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
111 _("Error interpreting JPEG image file (%s)"),
115 siglongjmp (errmgr->setjmp_buffer, 1);
117 g_assert_not_reached ();
121 output_message_handler (j_common_ptr cinfo)
123 /* This method keeps libjpeg from dumping crap to stderr */
128 /* explode gray image data from jpeg library into rgb components in pixbuf */
130 explode_gray_into_buf (struct jpeg_decompress_struct *cinfo,
136 g_return_if_fail (cinfo != NULL);
137 g_return_if_fail (cinfo->output_components == 1);
139 /* Expand grey->colour. Expand from the end of the
140 * memory down, so we can use the same buffer.
142 w = cinfo->image_width;
143 for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
146 from = lines[i] + w - 1;
147 to = lines[i] + (w - 1) * 3;
148 for (j = w - 1; j >= 0; j--) {
159 struct jpeg_source_mgr pub; /* public fields */
161 FILE * infile; /* source stream */
162 JOCTET * buffer; /* start of buffer */
163 boolean start_of_file; /* have we gotten any data yet? */
166 typedef stdio_source_mgr * stdio_src_ptr;
169 stdio_init_source (j_decompress_ptr cinfo)
171 stdio_src_ptr src = (stdio_src_ptr)cinfo->src;
172 src->start_of_file = FALSE;
176 stdio_fill_input_buffer (j_decompress_ptr cinfo)
178 stdio_src_ptr src = (stdio_src_ptr) cinfo->src;
181 nbytes = fread (src->buffer, 1, JPEG_PROG_BUF_SIZE, src->infile);
185 if (src->start_of_file) /* Treat empty input file as fatal error */
186 ERREXIT(cinfo, JERR_INPUT_EMPTY);
187 WARNMS(cinfo, JWRN_JPEG_EOF);
189 /* Insert a fake EOI marker */
190 src->buffer[0] = (JOCTET) 0xFF;
191 src->buffer[1] = (JOCTET) JPEG_EOI;
195 src->pub.next_input_byte = src->buffer;
196 src->pub.bytes_in_buffer = nbytes;
197 src->start_of_file = FALSE;
203 stdio_skip_input_data (j_decompress_ptr cinfo, long num_bytes)
205 stdio_src_ptr src = (stdio_src_ptr) cinfo->src;
208 while (num_bytes > (long) src->pub.bytes_in_buffer) {
209 num_bytes -= (long) src->pub.bytes_in_buffer;
210 (void)stdio_fill_input_buffer(cinfo);
212 src->pub.next_input_byte += (size_t) num_bytes;
213 src->pub.bytes_in_buffer -= (size_t) num_bytes;
218 stdio_term_source (j_decompress_ptr cinfo)
222 /* Shared library entry point */
224 gdk_pixbuf__jpeg_image_load (FILE *f, GError **error)
227 GdkPixbuf * volatile pixbuf = NULL;
229 guchar *lines[4]; /* Used to expand rows, via rec_outbuf_height,
230 * from the header file:
231 * " Usually rec_outbuf_height will be 1 or 2,
235 struct jpeg_decompress_struct cinfo;
236 struct error_handler_data jerr;
239 /* setup error handler */
240 cinfo.err = jpeg_std_error (&jerr.pub);
241 jerr.pub.error_exit = fatal_error_handler;
242 jerr.pub.output_message = output_message_handler;
246 if (sigsetjmp (jerr.setjmp_buffer, 1)) {
247 /* Whoops there was a jpeg error */
249 g_object_unref (pixbuf);
251 jpeg_destroy_decompress (&cinfo);
255 /* load header, setup */
256 jpeg_create_decompress (&cinfo);
258 cinfo.src = (struct jpeg_source_mgr *)
259 (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
260 sizeof (stdio_source_mgr));
261 src = (stdio_src_ptr) cinfo.src;
262 src->buffer = (JOCTET *)
263 (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
264 JPEG_PROG_BUF_SIZE * sizeof (JOCTET));
266 src->pub.init_source = stdio_init_source;
267 src->pub.fill_input_buffer = stdio_fill_input_buffer;
268 src->pub.skip_input_data = stdio_skip_input_data;
269 src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
270 src->pub.term_source = stdio_term_source;
272 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
273 src->pub.next_input_byte = NULL; /* until buffer loaded */
275 jpeg_read_header (&cinfo, TRUE);
276 jpeg_start_decompress (&cinfo);
277 cinfo.do_fancy_upsampling = FALSE;
278 cinfo.do_block_smoothing = FALSE;
280 pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, FALSE, 8, cinfo.output_width, cinfo.output_height);
283 jpeg_destroy_decompress (&cinfo);
285 /* broken check for *error == NULL for robustness against
286 * crappy JPEG library
288 if (error && *error == NULL) {
291 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
292 _("Insufficient memory to load image, try exiting some applications to free memory"));
298 dptr = pixbuf->pixels;
300 /* decompress all the lines, a few at a time */
302 while (cinfo.output_scanline < cinfo.output_height) {
304 for (i = 0; i < cinfo.rec_outbuf_height; i++) {
306 dptr += pixbuf->rowstride;
309 jpeg_read_scanlines (&cinfo, lines, cinfo.rec_outbuf_height);
311 if (cinfo.output_components == 1)
312 explode_gray_into_buf (&cinfo, lines);
315 jpeg_finish_decompress (&cinfo);
316 jpeg_destroy_decompress (&cinfo);
322 /**** Progressive image loading handling *****/
324 /* these routines required because we are acting as a source manager for */
327 init_source (j_decompress_ptr cinfo)
329 my_src_ptr src = (my_src_ptr) cinfo->src;
336 term_source (j_decompress_ptr cinfo)
338 /* XXXX - probably should scream something has happened */
342 /* for progressive loading (called "I/O Suspension" by libjpeg docs) */
343 /* we do nothing except return "FALSE" */
345 fill_input_buffer (j_decompress_ptr cinfo)
352 skip_input_data (j_decompress_ptr cinfo, long num_bytes)
354 my_src_ptr src = (my_src_ptr) cinfo->src;
357 /* move as far as we can into current buffer */
358 /* then set skip_next to catch the rest */
360 num_can_do = MIN (src->pub.bytes_in_buffer, num_bytes);
361 src->pub.next_input_byte += (size_t) num_can_do;
362 src->pub.bytes_in_buffer -= (size_t) num_can_do;
364 src->skip_next = num_bytes - num_can_do;
370 * func - called when we have pixmap created (but no image data)
371 * user_data - passed as arg 1 to func
372 * return context (opaque to user)
376 gdk_pixbuf__jpeg_image_begin_load (ModulePreparedNotifyFunc prepared_func,
377 ModuleUpdatedNotifyFunc updated_func,
381 JpegProgContext *context;
384 context = g_new0 (JpegProgContext, 1);
385 context->prepared_func = prepared_func;
386 context->updated_func = updated_func;
387 context->user_data = user_data;
388 context->pixbuf = NULL;
389 context->got_header = FALSE;
390 context->did_prescan = FALSE;
391 context->src_initialized = FALSE;
392 context->in_output = FALSE;
394 /* create libjpeg structures */
395 jpeg_create_decompress (&context->cinfo);
397 context->cinfo.src = (struct jpeg_source_mgr *) g_try_malloc (sizeof (my_source_mgr));
398 if (!context->cinfo.src) {
401 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
402 _("Couldn't allocate memory for loading JPEG file"));
405 memset (context->cinfo.src, 0, sizeof (my_source_mgr));
407 src = (my_src_ptr) context->cinfo.src;
409 context->cinfo.err = jpeg_std_error (&context->jerr.pub);
410 context->jerr.pub.error_exit = fatal_error_handler;
411 context->jerr.pub.output_message = output_message_handler;
412 context->jerr.error = error;
414 src = (my_src_ptr) context->cinfo.src;
415 src->pub.init_source = init_source;
416 src->pub.fill_input_buffer = fill_input_buffer;
417 src->pub.skip_input_data = skip_input_data;
418 src->pub.resync_to_restart = jpeg_resync_to_restart;
419 src->pub.term_source = term_source;
420 src->pub.bytes_in_buffer = 0;
421 src->pub.next_input_byte = NULL;
423 context->jerr.error = NULL;
425 return (gpointer) context;
429 * context - returned from image_begin_load
431 * free context, unref gdk_pixbuf
434 gdk_pixbuf__jpeg_image_stop_load (gpointer data, GError **error)
436 JpegProgContext *context = (JpegProgContext *) data;
438 g_return_val_if_fail (context != NULL, TRUE);
440 /* FIXME this thing needs to report errors if
441 * we have unused image data
445 g_object_unref (context->pixbuf);
447 /* if we have an error? */
448 if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
449 jpeg_destroy_decompress (&context->cinfo);
451 jpeg_finish_decompress(&context->cinfo);
452 jpeg_destroy_decompress(&context->cinfo);
455 if (context->cinfo.src) {
456 my_src_ptr src = (my_src_ptr) context->cinfo.src;
470 * context - from image_begin_load
471 * buf - new image data
472 * size - length of new image data
474 * append image data onto inrecrementally built output image
477 gdk_pixbuf__jpeg_image_load_increment (gpointer data,
478 const guchar *buf, guint size,
481 JpegProgContext *context = (JpegProgContext *)data;
482 struct jpeg_decompress_struct *cinfo;
484 guint num_left, num_copy;
485 guint last_bytes_left;
490 g_return_val_if_fail (context != NULL, FALSE);
491 g_return_val_if_fail (buf != NULL, FALSE);
493 src = (my_src_ptr) context->cinfo.src;
495 cinfo = &context->cinfo;
497 context->jerr.error = error;
499 /* XXXXXXX (drmike) - loop(s) below need to be recoded now I
500 * have a grasp of what the flow needs to be!
503 /* check for fatal error */
504 if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
508 /* skip over data if requested, handle unsigned int sizes cleanly */
509 /* only can happen if we've already called jpeg_get_header once */
510 if (context->src_initialized && src->skip_next) {
511 if (src->skip_next > size) {
512 src->skip_next -= size;
515 num_left = size - src->skip_next;
516 bufhd = buf + src->skip_next;
532 /* handle any data from caller we haven't processed yet */
534 if(src->pub.bytes_in_buffer &&
535 src->pub.next_input_byte != src->buffer)
536 memmove(src->buffer, src->pub.next_input_byte,
537 src->pub.bytes_in_buffer);
540 num_copy = MIN (JPEG_PROG_BUF_SIZE - src->pub.bytes_in_buffer,
543 memcpy(src->buffer + src->pub.bytes_in_buffer, bufhd,num_copy);
544 src->pub.next_input_byte = src->buffer;
545 src->pub.bytes_in_buffer += num_copy;
547 num_left -= num_copy;
549 /* did anything change from last pass, if not return */
551 last_bytes_left = src->pub.bytes_in_buffer;
553 } else if (src->pub.bytes_in_buffer == last_bytes_left)
556 last_bytes_left = src->pub.bytes_in_buffer;
559 /* should not go through twice and not pull bytes out of buf */
563 /* try to load jpeg header */
564 if (!context->got_header) {
567 rc = jpeg_read_header (cinfo, TRUE);
568 context->src_initialized = TRUE;
570 if (rc == JPEG_SUSPENDED)
573 context->got_header = TRUE;
575 context->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB,
579 cinfo->image_height);
581 if (context->pixbuf == NULL) {
584 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
585 _("Couldn't allocate memory for loading JPEG file"));
589 /* Use pixbuf buffer to store decompressed data */
590 context->dptr = context->pixbuf->pixels;
592 /* Notify the client that we are ready to go */
593 (* context->prepared_func) (context->pixbuf,
597 } else if (!context->did_prescan) {
600 /* start decompression */
601 cinfo->buffered_image = TRUE;
602 rc = jpeg_start_decompress (cinfo);
603 cinfo->do_fancy_upsampling = FALSE;
604 cinfo->do_block_smoothing = FALSE;
606 if (rc == JPEG_SUSPENDED)
609 context->did_prescan = TRUE;
611 /* we're decompressing so feed jpeg lib scanlines */
617 /* keep going until we've done all passes */
618 while (!jpeg_input_complete (cinfo)) {
619 if (!context->in_output) {
620 if (jpeg_start_output (cinfo, cinfo->input_scan_number)) {
621 context->in_output = TRUE;
622 context->dptr = context->pixbuf->pixels;
627 /* keep going until we've done all scanlines */
628 while (cinfo->output_scanline < cinfo->output_height) {
630 rowptr = context->dptr;
631 for (i=0; i < cinfo->rec_outbuf_height; i++) {
633 rowptr += context->pixbuf->rowstride;
636 nlines = jpeg_read_scanlines (cinfo, lines,
637 cinfo->rec_outbuf_height);
642 if (cinfo->output_components == 1)
643 explode_gray_into_buf (cinfo, lines);
645 context->dptr += nlines * context->pixbuf->rowstride;
647 /* send updated signal */
648 (* context->updated_func) (context->pixbuf,
650 cinfo->output_scanline-1,
655 if (cinfo->output_scanline >= cinfo->output_height &&
656 jpeg_finish_output (cinfo))
657 context->in_output = FALSE;
661 if (jpeg_input_complete (cinfo))
662 /* did entire image */
673 gdk_pixbuf__jpeg_image_save (FILE *f,
679 /* FIXME error handling is broken */
681 struct jpeg_compress_struct cinfo;
684 guchar *pixels = NULL;
687 volatile int quality = 75; /* default; must be between 0 and 100 */
691 struct error_handler_data jerr;
694 gchar **kiter = keys;
695 gchar **viter = values;
698 if (strcmp (*kiter, "quality") == 0) {
700 quality = strtol (*viter, &endptr, 10);
702 if (endptr == *viter) {
705 GDK_PIXBUF_ERROR_BAD_OPTION,
706 _("JPEG quality must be a value between 0 and 100; value '%s' could not be parsed."),
714 /* This is a user-visible error;
715 * lets people skip the range-checking
720 GDK_PIXBUF_ERROR_BAD_OPTION,
721 _("JPEG quality must be a value between 0 and 100; value '%d' is not allowed."),
727 g_warning ("Bad option name '%s' passed to JPEG saver",
737 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
739 w = gdk_pixbuf_get_width (pixbuf);
740 h = gdk_pixbuf_get_height (pixbuf);
742 /* no image data? abort */
743 pixels = gdk_pixbuf_get_pixels (pixbuf);
744 g_return_val_if_fail (pixels != NULL, FALSE);
746 /* allocate a small buffer to convert image data */
747 buf = g_try_malloc (w * 3 * sizeof (guchar));
751 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
752 _("Couldn't allocate memory for loading JPEG file"));
756 /* set up error handling */
757 jerr.pub.error_exit = fatal_error_handler;
758 jerr.pub.output_message = output_message_handler;
761 cinfo.err = jpeg_std_error (&(jerr.pub));
762 if (sigsetjmp (jerr.setjmp_buffer, 1)) {
763 jpeg_destroy_compress (&cinfo);
768 /* setup compress params */
769 jpeg_create_compress (&cinfo);
770 jpeg_stdio_dest (&cinfo, f);
771 cinfo.image_width = w;
772 cinfo.image_height = h;
773 cinfo.input_components = 3;
774 cinfo.in_color_space = JCS_RGB;
776 /* set up jepg compression parameters */
777 jpeg_set_defaults (&cinfo);
778 jpeg_set_quality (&cinfo, quality, TRUE);
779 jpeg_start_compress (&cinfo, TRUE);
780 /* get the start pointer */
782 /* go one scanline at a time... and save */
784 while (cinfo.next_scanline < cinfo.image_height) {
785 /* convert scanline from ARGB to RGB packed */
786 for (j = 0; j < w; j++)
787 memcpy (&(buf[j*3]), &(ptr[i*rowstride + j*3]), 3);
790 jbuf = (JSAMPROW *)(&buf);
791 jpeg_write_scanlines (&cinfo, jbuf, 1);
798 jpeg_finish_compress (&cinfo);
804 gdk_pixbuf__jpeg_fill_vtable (GdkPixbufModule *module)
806 module->load = gdk_pixbuf__jpeg_image_load;
807 module->begin_load = gdk_pixbuf__jpeg_image_begin_load;
808 module->stop_load = gdk_pixbuf__jpeg_image_stop_load;
809 module->load_increment = gdk_pixbuf__jpeg_image_load_increment;
810 module->save = gdk_pixbuf__jpeg_image_save;