]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-jpeg.c
Cleanups
[~andy/gtk] / gdk-pixbuf / io-jpeg.c
1 /* -*- mode: C; c-file-style: "linux" -*- */
2 /* GdkPixbuf library - JPEG image loader
3  *
4  * Copyright (C) 1999 Michael Zucchi
5  * Copyright (C) 1999 The Free Software Foundation
6  * 
7  * Progressive loading code Copyright (C) 1999 Red Hat, Inc.
8  *
9  * Authors: Michael Zucchi <zucchi@zedzone.mmc.com.au>
10  *          Federico Mena-Quintero <federico@gimp.org>
11  *          Michael Fulbright <drmike@redhat.com>
12  *
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.
17  *
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.
22  *
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.
27  */
28
29
30 #include <config.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <setjmp.h>
35 #include <jpeglib.h>
36 #include <jerror.h>
37 #include "gdk-pixbuf-private.h"
38 #include "gdk-pixbuf-io.h"
39
40 #ifndef HAVE_SIGSETJMP
41 #define sigjmp_buf jmp_buf
42 #define sigsetjmp(jb, x) setjmp(jb)
43 #define siglongjmp longjmp
44 #endif
45 \f
46
47 /* we are a "source manager" as far as libjpeg is concerned */
48 #define JPEG_PROG_BUF_SIZE 65536
49
50 typedef struct {
51         struct jpeg_source_mgr pub;   /* public fields */
52
53         JOCTET buffer[JPEG_PROG_BUF_SIZE];              /* start of buffer */
54         long  skip_next;              /* number of bytes to skip next read */
55         
56 } my_source_mgr;
57
58 typedef my_source_mgr * my_src_ptr;
59
60 /* error handler data */
61 struct error_handler_data {
62         struct jpeg_error_mgr pub;
63         sigjmp_buf setjmp_buffer;
64         GError **error;
65 };
66
67 /* progressive loader context */
68 typedef struct {
69         GdkPixbufModuleSizeFunc     size_func;
70         GdkPixbufModuleUpdatedFunc  updated_func;
71         GdkPixbufModulePreparedFunc prepared_func;
72         gpointer                    user_data;
73         
74         GdkPixbuf                *pixbuf;
75         guchar                   *dptr;   /* current position in pixbuf */
76
77         gboolean                 did_prescan;  /* are we in image data yet? */
78         gboolean                 got_header;  /* have we loaded jpeg header? */
79         gboolean                 src_initialized;/* TRUE when jpeg lib initialized */
80         gboolean                 in_output;   /* did we get suspended in an output pass? */
81         struct jpeg_decompress_struct cinfo;
82         struct error_handler_data     jerr;
83 } JpegProgContext;
84
85 static GdkPixbuf *gdk_pixbuf__jpeg_image_load (FILE *f, GError **error);
86 static gpointer gdk_pixbuf__jpeg_image_begin_load (GdkPixbufModuleSizeFunc           func0,
87                                                    GdkPixbufModulePreparedFunc func1, 
88                                                    GdkPixbufModuleUpdatedFunc func2,
89                                                    gpointer user_data,
90                                                    GError **error);
91 static gboolean gdk_pixbuf__jpeg_image_stop_load (gpointer context, GError **error);
92 static gboolean gdk_pixbuf__jpeg_image_load_increment(gpointer context,
93                                                       const guchar *buf, guint size,
94                                                       GError **error);
95
96
97 static void
98 fatal_error_handler (j_common_ptr cinfo)
99 {
100         struct error_handler_data *errmgr;
101         char buffer[JMSG_LENGTH_MAX];
102         
103         errmgr = (struct error_handler_data *) cinfo->err;
104         
105         /* Create the message */
106         (* cinfo->err->format_message) (cinfo, buffer);
107
108         /* broken check for *error == NULL for robustness against
109          * crappy JPEG library
110          */
111         if (errmgr->error && *errmgr->error == NULL) {
112                 g_set_error (errmgr->error,
113                              GDK_PIXBUF_ERROR,
114                              cinfo->err->msg_code == JERR_OUT_OF_MEMORY 
115                              ? GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY 
116                              : GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
117                              _("Error interpreting JPEG image file (%s)"),
118                              buffer);
119         }
120         
121         siglongjmp (errmgr->setjmp_buffer, 1);
122
123         g_assert_not_reached ();
124 }
125
126 static void
127 output_message_handler (j_common_ptr cinfo)
128 {
129   /* This method keeps libjpeg from dumping crap to stderr */
130
131   /* do nothing */
132 }
133
134 /* explode gray image data from jpeg library into rgb components in pixbuf */
135 static void
136 explode_gray_into_buf (struct jpeg_decompress_struct *cinfo,
137                        guchar **lines) 
138 {
139         gint i, j;
140         guint w;
141
142         g_return_if_fail (cinfo != NULL);
143         g_return_if_fail (cinfo->output_components == 1);
144         g_return_if_fail (cinfo->out_color_space == JCS_GRAYSCALE);
145
146         /* Expand grey->colour.  Expand from the end of the
147          * memory down, so we can use the same buffer.
148          */
149         w = cinfo->output_width;
150         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
151                 guchar *from, *to;
152                 
153                 from = lines[i] + w - 1;
154                 to = lines[i] + (w - 1) * 3;
155                 for (j = w - 1; j >= 0; j--) {
156                         to[0] = from[0];
157                         to[1] = from[0];
158                         to[2] = from[0];
159                         to -= 3;
160                         from--;
161                 }
162         }
163 }
164
165
166 static void
167 convert_cmyk_to_rgb (struct jpeg_decompress_struct *cinfo,
168                      guchar **lines) 
169 {
170         gint i, j;
171
172         g_return_if_fail (cinfo != NULL);
173         g_return_if_fail (cinfo->output_components == 4);
174         g_return_if_fail (cinfo->out_color_space == JCS_CMYK);
175
176         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
177                 guchar *p;
178                 
179                 p = lines[i];
180                 for (j = 0; j < cinfo->output_width; j++) {
181                         int c, m, y, k;
182                         c = p[0];
183                         m = p[1];
184                         y = p[2];
185                         k = p[3];
186                         if (cinfo->saw_Adobe_marker) {
187                                 p[0] = k*c / 255;
188                                 p[1] = k*m / 255;
189                                 p[2] = k*y / 255;
190                         }
191                         else {
192                                 p[0] = (255 - k)*(255 - c) / 255;
193                                 p[1] = (255 - k)*(255 - m) / 255;
194                                 p[2] = (255 - k)*(255 - y) / 255;
195                         }
196                         p[3] = 255;
197                         p += 4;
198                 }
199         }
200 }
201
202 typedef struct {
203   struct jpeg_source_mgr pub;   /* public fields */
204
205   FILE * infile;                /* source stream */
206   JOCTET * buffer;              /* start of buffer */
207   boolean start_of_file;        /* have we gotten any data yet? */
208 } stdio_source_mgr;
209
210 typedef stdio_source_mgr * stdio_src_ptr;
211
212 static void
213 stdio_init_source (j_decompress_ptr cinfo)
214 {
215   stdio_src_ptr src = (stdio_src_ptr)cinfo->src;
216   src->start_of_file = FALSE;
217 }
218
219 static boolean
220 stdio_fill_input_buffer (j_decompress_ptr cinfo)
221 {
222   stdio_src_ptr src = (stdio_src_ptr) cinfo->src;
223   size_t nbytes;
224
225   nbytes = fread (src->buffer, 1, JPEG_PROG_BUF_SIZE, src->infile);
226
227   if (nbytes <= 0) {
228 #if 0
229     if (src->start_of_file)     /* Treat empty input file as fatal error */
230       ERREXIT(cinfo, JERR_INPUT_EMPTY);
231     WARNMS(cinfo, JWRN_JPEG_EOF);
232 #endif
233     /* Insert a fake EOI marker */
234     src->buffer[0] = (JOCTET) 0xFF;
235     src->buffer[1] = (JOCTET) JPEG_EOI;
236     nbytes = 2;
237   }
238
239   src->pub.next_input_byte = src->buffer;
240   src->pub.bytes_in_buffer = nbytes;
241   src->start_of_file = FALSE;
242
243   return TRUE;
244 }
245
246 static void
247 stdio_skip_input_data (j_decompress_ptr cinfo, long num_bytes)
248 {
249   stdio_src_ptr src = (stdio_src_ptr) cinfo->src;
250
251   if (num_bytes > 0) {
252     while (num_bytes > (long) src->pub.bytes_in_buffer) {
253       num_bytes -= (long) src->pub.bytes_in_buffer;
254       (void)stdio_fill_input_buffer(cinfo);
255     }
256     src->pub.next_input_byte += (size_t) num_bytes;
257     src->pub.bytes_in_buffer -= (size_t) num_bytes;
258   }
259 }
260
261 static void
262 stdio_term_source (j_decompress_ptr cinfo)
263 {
264 }
265
266 static gchar *
267 colorspace_name (const J_COLOR_SPACE jpeg_color_space) 
268 {
269         switch (jpeg_color_space) {
270             case JCS_UNKNOWN: return "UNKNOWN"; 
271             case JCS_GRAYSCALE: return "GRAYSCALE"; 
272             case JCS_RGB: return "RGB"; 
273             case JCS_YCbCr: return "YCbCr"; 
274             case JCS_CMYK: return "CMYK"; 
275             case JCS_YCCK: return "YCCK";
276             default: return "invalid";
277         }
278 }
279
280 /* Shared library entry point */
281 static GdkPixbuf *
282 gdk_pixbuf__jpeg_image_load (FILE *f, GError **error)
283 {
284         gint i;
285         GdkPixbuf * volatile pixbuf = NULL;
286         guchar *dptr;
287         guchar *lines[4]; /* Used to expand rows, via rec_outbuf_height, 
288                            * from the header file: 
289                            * " Usually rec_outbuf_height will be 1 or 2, 
290                            * at most 4."
291                            */
292         guchar **lptr;
293         struct jpeg_decompress_struct cinfo;
294         struct error_handler_data jerr;
295         stdio_src_ptr src;
296
297         /* setup error handler */
298         cinfo.err = jpeg_std_error (&jerr.pub);
299         jerr.pub.error_exit = fatal_error_handler;
300         jerr.pub.output_message = output_message_handler;
301
302         jerr.error = error;
303         
304         if (sigsetjmp (jerr.setjmp_buffer, 1)) {
305                 /* Whoops there was a jpeg error */
306                 if (pixbuf)
307                         g_object_unref (pixbuf);
308
309                 jpeg_destroy_decompress (&cinfo);
310                 return NULL;
311         }
312
313         /* load header, setup */
314         jpeg_create_decompress (&cinfo);
315
316         cinfo.src = (struct jpeg_source_mgr *)
317           (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
318                                   sizeof (stdio_source_mgr));
319         src = (stdio_src_ptr) cinfo.src;
320         src->buffer = (JOCTET *)
321           (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
322                                       JPEG_PROG_BUF_SIZE * sizeof (JOCTET));
323
324         src->pub.init_source = stdio_init_source;
325         src->pub.fill_input_buffer = stdio_fill_input_buffer;
326         src->pub.skip_input_data = stdio_skip_input_data;
327         src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
328         src->pub.term_source = stdio_term_source;
329         src->infile = f;
330         src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
331         src->pub.next_input_byte = NULL; /* until buffer loaded */
332
333         jpeg_read_header (&cinfo, TRUE);
334         jpeg_start_decompress (&cinfo);
335         cinfo.do_fancy_upsampling = FALSE;
336         cinfo.do_block_smoothing = FALSE;
337
338         pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, 
339                                  cinfo.out_color_components == 4 ? TRUE : FALSE, 
340                                  8, cinfo.output_width, cinfo.output_height);
341               
342         if (!pixbuf) {
343                 jpeg_destroy_decompress (&cinfo);
344
345                 /* broken check for *error == NULL for robustness against
346                  * crappy JPEG library
347                  */
348                 if (error && *error == NULL) {
349                         g_set_error (error,
350                                      GDK_PIXBUF_ERROR,
351                                      GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
352                                      _("Insufficient memory to load image, try exiting some applications to free memory"));
353                 }
354                 
355                 return NULL;
356         }
357
358         dptr = pixbuf->pixels;
359
360         /* decompress all the lines, a few at a time */
361         while (cinfo.output_scanline < cinfo.output_height) {
362                 lptr = lines;
363                 for (i = 0; i < cinfo.rec_outbuf_height; i++) {
364                         *lptr++ = dptr;
365                         dptr += pixbuf->rowstride;
366                 }
367
368                 jpeg_read_scanlines (&cinfo, lines, cinfo.rec_outbuf_height);
369
370                 switch (cinfo.out_color_space) {
371                     case JCS_GRAYSCALE:
372                       explode_gray_into_buf (&cinfo, lines);
373                       break;
374                     case JCS_RGB:
375                       /* do nothing */
376                       break;
377                     case JCS_CMYK:
378                       convert_cmyk_to_rgb (&cinfo, lines);
379                       break;
380                     default:
381                       g_object_unref (pixbuf);
382                       if (error && *error == NULL) {
383                         g_set_error (error,
384                                      GDK_PIXBUF_ERROR,
385                                      GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
386                                      _("Unsupported JPEG color space (%s)"),
387                                      colorspace_name (cinfo.out_color_space)); 
388                       }
389                 
390                       jpeg_destroy_decompress (&cinfo);
391                       return NULL;
392                 }
393         }
394
395         jpeg_finish_decompress (&cinfo);
396         jpeg_destroy_decompress (&cinfo);
397
398         return pixbuf;
399 }
400
401
402 /**** Progressive image loading handling *****/
403
404 /* these routines required because we are acting as a source manager for */
405 /* libjpeg. */
406 static void
407 init_source (j_decompress_ptr cinfo)
408 {
409         my_src_ptr src = (my_src_ptr) cinfo->src;
410
411         src->skip_next = 0;
412 }
413
414
415 static void
416 term_source (j_decompress_ptr cinfo)
417 {
418         /* XXXX - probably should scream something has happened */
419 }
420
421
422 /* for progressive loading (called "I/O Suspension" by libjpeg docs) */
423 /* we do nothing except return "FALSE"                               */
424 static boolean
425 fill_input_buffer (j_decompress_ptr cinfo)
426 {
427         return FALSE;
428 }
429
430
431 static void
432 skip_input_data (j_decompress_ptr cinfo, long num_bytes)
433 {
434         my_src_ptr src = (my_src_ptr) cinfo->src;
435         long   num_can_do;
436
437         /* move as far as we can into current buffer */
438         /* then set skip_next to catch the rest      */
439         if (num_bytes > 0) {
440                 num_can_do = MIN (src->pub.bytes_in_buffer, num_bytes);
441                 src->pub.next_input_byte += (size_t) num_can_do;
442                 src->pub.bytes_in_buffer -= (size_t) num_can_do;
443
444                 src->skip_next = num_bytes - num_can_do;
445         }
446 }
447
448  
449 /* 
450  * func - called when we have pixmap created (but no image data)
451  * user_data - passed as arg 1 to func
452  * return context (opaque to user)
453  */
454
455 static gpointer
456 gdk_pixbuf__jpeg_image_begin_load (GdkPixbufModuleSizeFunc size_func,
457                                    GdkPixbufModulePreparedFunc prepared_func, 
458                                    GdkPixbufModuleUpdatedFunc updated_func,
459                                    gpointer user_data,
460                                    GError **error)
461 {
462         JpegProgContext *context;
463         my_source_mgr   *src;
464
465         context = g_new0 (JpegProgContext, 1);
466         context->size_func = size_func;
467         context->prepared_func = prepared_func;
468         context->updated_func  = updated_func;
469         context->user_data = user_data;
470         context->pixbuf = NULL;
471         context->got_header = FALSE;
472         context->did_prescan = FALSE;
473         context->src_initialized = FALSE;
474         context->in_output = FALSE;
475
476         /* create libjpeg structures */
477         jpeg_create_decompress (&context->cinfo);
478
479         context->cinfo.src = (struct jpeg_source_mgr *) g_try_malloc (sizeof (my_source_mgr));
480         if (!context->cinfo.src) {
481                 g_set_error (error,
482                              GDK_PIXBUF_ERROR,
483                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
484                              _("Couldn't allocate memory for loading JPEG file"));
485                 return NULL;
486         }
487         memset (context->cinfo.src, 0, sizeof (my_source_mgr));
488        
489         src = (my_src_ptr) context->cinfo.src;
490
491         context->cinfo.err = jpeg_std_error (&context->jerr.pub);
492         context->jerr.pub.error_exit = fatal_error_handler;
493         context->jerr.pub.output_message = output_message_handler;
494         context->jerr.error = error;
495         
496         src = (my_src_ptr) context->cinfo.src;
497         src->pub.init_source = init_source;
498         src->pub.fill_input_buffer = fill_input_buffer;
499         src->pub.skip_input_data = skip_input_data;
500         src->pub.resync_to_restart = jpeg_resync_to_restart;
501         src->pub.term_source = term_source;
502         src->pub.bytes_in_buffer = 0;
503         src->pub.next_input_byte = NULL;
504
505         context->jerr.error = NULL;
506         
507         return (gpointer) context;
508 }
509
510 /*
511  * context - returned from image_begin_load
512  *
513  * free context, unref gdk_pixbuf
514  */
515 static gboolean
516 gdk_pixbuf__jpeg_image_stop_load (gpointer data, GError **error)
517 {
518         JpegProgContext *context = (JpegProgContext *) data;
519
520         g_return_val_if_fail (context != NULL, TRUE);
521         
522         /* FIXME this thing needs to report errors if
523          * we have unused image data
524          */
525         
526         if (context->pixbuf)
527                 g_object_unref (context->pixbuf);
528         
529         /* if we have an error? */
530         if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
531                 jpeg_destroy_decompress (&context->cinfo);
532         } else {
533                 jpeg_finish_decompress(&context->cinfo);
534                 jpeg_destroy_decompress(&context->cinfo);
535         }
536
537         if (context->cinfo.src) {
538                 my_src_ptr src = (my_src_ptr) context->cinfo.src;
539                 
540                 g_free (src);
541         }
542
543         g_free (context);
544
545         return TRUE;
546 }
547
548
549 static gboolean
550 gdk_pixbuf__jpeg_image_load_lines (JpegProgContext  *context,
551                                    GError          **error)
552 {
553         struct jpeg_decompress_struct *cinfo = &context->cinfo;
554         guchar *lines[4];
555         guchar **lptr;
556         guchar *rowptr;
557         gint   nlines, i;
558
559         /* keep going until we've done all scanlines */
560         while (cinfo->output_scanline < cinfo->output_height) {
561                 lptr = lines;
562                 rowptr = context->dptr;
563                 for (i=0; i < cinfo->rec_outbuf_height; i++) {
564                         *lptr++ = rowptr;
565                         rowptr += context->pixbuf->rowstride;
566                 }
567
568                 nlines = jpeg_read_scanlines (cinfo, lines,
569                                               cinfo->rec_outbuf_height);
570                 if (nlines == 0)
571                         break;
572
573                 switch (cinfo->out_color_space) {
574                 case JCS_GRAYSCALE:
575                         explode_gray_into_buf (cinfo, lines);
576                         break;
577                 case JCS_RGB:
578                         /* do nothing */
579                         break;
580                 case JCS_CMYK:
581                         convert_cmyk_to_rgb (cinfo, lines);
582                         break;
583                 default:
584                         if (error && *error == NULL) {
585                                 g_set_error (error,
586                                              GDK_PIXBUF_ERROR,
587                                              GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
588                                              _("Unsupported JPEG color space (%s)"),
589                                              colorspace_name (cinfo->out_color_space));
590                         }
591
592                         return FALSE;
593                 }
594
595                 context->dptr += nlines * context->pixbuf->rowstride;
596
597                 /* send updated signal */
598                 if (context->updated_func)
599                         (* context->updated_func) (context->pixbuf,
600                                                    0,
601                                                    cinfo->output_scanline - 1,
602                                                    cinfo->image_width,
603                                                    nlines,
604                                                    context->user_data);
605         }
606
607         return TRUE;
608 }
609
610
611 /*
612  * context - from image_begin_load
613  * buf - new image data
614  * size - length of new image data
615  *
616  * append image data onto inrecrementally built output image
617  */
618 static gboolean
619 gdk_pixbuf__jpeg_image_load_increment (gpointer data,
620                                        const guchar *buf, guint size,
621                                        GError **error)
622 {
623         JpegProgContext *context = (JpegProgContext *)data;
624         struct jpeg_decompress_struct *cinfo;
625         my_src_ptr  src;
626         guint       num_left, num_copy;
627         guint       last_bytes_left;
628         guint       spinguard;
629         gboolean    first;
630         const guchar *bufhd;
631         gint        width, height;
632
633         g_return_val_if_fail (context != NULL, FALSE);
634         g_return_val_if_fail (buf != NULL, FALSE);
635
636         src = (my_src_ptr) context->cinfo.src;
637
638         cinfo = &context->cinfo;
639
640         context->jerr.error = error;
641         
642         /* check for fatal error */
643         if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
644                 return FALSE;
645         }
646
647         /* skip over data if requested, handle unsigned int sizes cleanly */
648         /* only can happen if we've already called jpeg_get_header once   */
649         if (context->src_initialized && src->skip_next) {
650                 if (src->skip_next > size) {
651                         src->skip_next -= size;
652                         return TRUE;
653                 } else {
654                         num_left = size - src->skip_next;
655                         bufhd = buf + src->skip_next;
656                         src->skip_next = 0;
657                 }
658         } else {
659                 num_left = size;
660                 bufhd = buf;
661         }
662
663         if (num_left == 0)
664                 return TRUE;
665
666         last_bytes_left = 0;
667         spinguard = 0;
668         first = TRUE;
669         while (TRUE) {
670
671                 /* handle any data from caller we haven't processed yet */
672                 if (num_left > 0) {
673                         if(src->pub.bytes_in_buffer && 
674                            src->pub.next_input_byte != src->buffer)
675                                 memmove(src->buffer, src->pub.next_input_byte,
676                                         src->pub.bytes_in_buffer);
677
678
679                         num_copy = MIN (JPEG_PROG_BUF_SIZE - src->pub.bytes_in_buffer,
680                                         num_left);
681
682                         memcpy(src->buffer + src->pub.bytes_in_buffer, bufhd,num_copy);
683                         src->pub.next_input_byte = src->buffer;
684                         src->pub.bytes_in_buffer += num_copy;
685                         bufhd += num_copy;
686                         num_left -= num_copy;
687                 } else {
688                 /* did anything change from last pass, if not return */
689                         if (first) {
690                                 last_bytes_left = src->pub.bytes_in_buffer;
691                                 first = FALSE;
692                         } else if (src->pub.bytes_in_buffer == last_bytes_left)
693                                 spinguard++;
694                         else
695                                 last_bytes_left = src->pub.bytes_in_buffer;
696                 }
697
698                 /* should not go through twice and not pull bytes out of buf */
699                 if (spinguard > 2)
700                         return TRUE;
701
702                 /* try to load jpeg header */
703                 if (!context->got_header) {
704                         int rc;
705                         
706                         rc = jpeg_read_header (cinfo, TRUE);
707                         context->src_initialized = TRUE;
708                         
709                         if (rc == JPEG_SUSPENDED)
710                                 continue;
711                         
712                         context->got_header = TRUE;
713                         
714                         width = cinfo->image_width;
715                         height = cinfo->image_height;
716                         if (context->size_func) {
717                                 (* context->size_func) (&width, &height, context->user_data);
718                                 if (width == 0 || height == 0)
719                                         return FALSE;
720                         }
721                         
722                         for (cinfo->scale_denom = 2; cinfo->scale_denom <= 8; cinfo->scale_denom *= 2) {
723                                 jpeg_calc_output_dimensions (cinfo);
724                                 if (cinfo->output_width < width || cinfo->output_height < height) {
725                                         cinfo->scale_denom /= 2;
726                                         break;
727                                 }
728                         }
729                         jpeg_calc_output_dimensions (cinfo);
730                         
731                         context->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, 
732                                                           cinfo->output_components == 4 ? TRUE : FALSE,
733                                                           8, 
734                                                           cinfo->output_width,
735                                                           cinfo->output_height);
736
737                         if (context->pixbuf == NULL) {
738                                 g_set_error (error,
739                                              GDK_PIXBUF_ERROR,
740                                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
741                                              _("Couldn't allocate memory for loading JPEG file"));
742                                 return FALSE;
743                         }
744                         
745                         /* Use pixbuf buffer to store decompressed data */
746                         context->dptr = context->pixbuf->pixels;
747                         
748                         /* Notify the client that we are ready to go */
749                         if (context->prepared_func)
750                                 (* context->prepared_func) (context->pixbuf,
751                                                             NULL,
752                                                             context->user_data);
753                         
754                 } else if (!context->did_prescan) {
755                         int rc;                 
756                         
757                         /* start decompression */
758                         cinfo->buffered_image = cinfo->progressive_mode;
759                         rc = jpeg_start_decompress (cinfo);
760                         cinfo->do_fancy_upsampling = FALSE;
761                         cinfo->do_block_smoothing = FALSE;
762
763                         if (rc == JPEG_SUSPENDED)
764                                 continue;
765
766                         context->did_prescan = TRUE;
767                 } else if (!cinfo->buffered_image) {
768                         /* we're decompressing unbuffered so
769                          * simply get scanline by scanline from jpeg lib
770                          */
771                         if (! gdk_pixbuf__jpeg_image_load_lines (context,
772                                                                  error))
773                                 return FALSE;
774
775                         if (cinfo->output_scanline >= cinfo->output_height)
776                                 return TRUE;
777                 } else {
778                         /* we're decompressing buffered (progressive)
779                          * so feed jpeg lib scanlines
780                          */
781
782                         /* keep going until we've done all passes */
783                         while (!jpeg_input_complete (cinfo)) {
784                                 if (!context->in_output) {
785                                         if (jpeg_start_output (cinfo, cinfo->input_scan_number)) {
786                                                 context->in_output = TRUE;
787                                                 context->dptr = context->pixbuf->pixels;
788                                         }
789                                         else
790                                                 break;
791                                 }
792
793                                 /* get scanlines from jpeg lib */
794                                 if (! gdk_pixbuf__jpeg_image_load_lines (context,
795                                                                          error))
796                                         return FALSE;
797
798                                 if (cinfo->output_scanline >= cinfo->output_height &&
799                                     jpeg_finish_output (cinfo))
800                                         context->in_output = FALSE;
801                                 else
802                                         break;
803                         }
804                         if (jpeg_input_complete (cinfo))
805                                 /* did entire image */
806                                 return TRUE;
807                         else
808                                 continue;
809                 }
810         }
811 }
812
813 /* Save */
814
815 #define TO_FUNCTION_BUF_SIZE 4096
816
817 typedef struct {
818         struct jpeg_destination_mgr pub;
819         JOCTET             *buffer;
820         GdkPixbufSaveFunc   save_func;
821         gpointer            user_data;
822         GError            **error;
823 } ToFunctionDestinationManager;
824
825 void
826 to_callback_init (j_compress_ptr cinfo)
827 {
828         ToFunctionDestinationManager *destmgr;
829
830         destmgr = (ToFunctionDestinationManager*) cinfo->dest;
831         destmgr->pub.next_output_byte = destmgr->buffer;
832         destmgr->pub.free_in_buffer = TO_FUNCTION_BUF_SIZE;
833 }
834
835 static void
836 to_callback_do_write (j_compress_ptr cinfo, gsize length)
837 {
838         ToFunctionDestinationManager *destmgr;
839
840         destmgr = (ToFunctionDestinationManager*) cinfo->dest;
841         if (!destmgr->save_func (destmgr->buffer,
842                                  length,
843                                  destmgr->error,
844                                  destmgr->user_data)) {
845                 struct error_handler_data *errmgr;
846         
847                 errmgr = (struct error_handler_data *) cinfo->err;
848                 /* Use a default error message if the callback didn't set one,
849                  * which it should have.
850                  */
851                 if (errmgr->error && *errmgr->error == NULL) {
852                         g_set_error (errmgr->error,
853                                      GDK_PIXBUF_ERROR,
854                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
855                                      "write function failed");
856                 }
857                 siglongjmp (errmgr->setjmp_buffer, 1);
858                 g_assert_not_reached ();
859         }
860 }
861
862 static boolean
863 to_callback_empty_output_buffer (j_compress_ptr cinfo)
864 {
865         ToFunctionDestinationManager *destmgr;
866
867         destmgr = (ToFunctionDestinationManager*) cinfo->dest;
868         to_callback_do_write (cinfo, TO_FUNCTION_BUF_SIZE);
869         destmgr->pub.next_output_byte = destmgr->buffer;
870         destmgr->pub.free_in_buffer = TO_FUNCTION_BUF_SIZE;
871         return TRUE;
872 }
873
874 void
875 to_callback_terminate (j_compress_ptr cinfo)
876 {
877         ToFunctionDestinationManager *destmgr;
878
879         destmgr = (ToFunctionDestinationManager*) cinfo->dest;
880         to_callback_do_write (cinfo, TO_FUNCTION_BUF_SIZE - destmgr->pub.free_in_buffer);
881 }
882
883 static gboolean
884 real_save_jpeg (GdkPixbuf          *pixbuf,
885                 gchar             **keys,
886                 gchar             **values,
887                 GError            **error,
888                 gboolean            to_callback,
889                 FILE               *f,
890                 GdkPixbufSaveFunc   save_func,
891                 gpointer            user_data)
892 {
893         /* FIXME error handling is broken */
894         
895        struct jpeg_compress_struct cinfo;
896        guchar *buf = NULL;
897        guchar *ptr;
898        guchar *pixels = NULL;
899        JSAMPROW *jbuf;
900        int y = 0;
901        volatile int quality = 75; /* default; must be between 0 and 100 */
902        int i, j;
903        int w, h = 0;
904        int rowstride = 0;
905        int n_channels;
906        struct error_handler_data jerr;
907        ToFunctionDestinationManager to_callback_destmgr;
908
909        to_callback_destmgr.buffer = NULL;
910
911        if (keys && *keys) {
912                gchar **kiter = keys;
913                gchar **viter = values;
914
915                while (*kiter) {
916                        if (strcmp (*kiter, "quality") == 0) {
917                                char *endptr = NULL;
918                                quality = strtol (*viter, &endptr, 10);
919
920                                if (endptr == *viter) {
921                                        g_set_error (error,
922                                                     GDK_PIXBUF_ERROR,
923                                                     GDK_PIXBUF_ERROR_BAD_OPTION,
924                                                     _("JPEG quality must be a value between 0 and 100; value '%s' could not be parsed."),
925                                                     *viter);
926
927                                        return FALSE;
928                                }
929                                
930                                if (quality < 0 ||
931                                    quality > 100) {
932                                        /* This is a user-visible error;
933                                         * lets people skip the range-checking
934                                         * in their app.
935                                         */
936                                        g_set_error (error,
937                                                     GDK_PIXBUF_ERROR,
938                                                     GDK_PIXBUF_ERROR_BAD_OPTION,
939                                                     _("JPEG quality must be a value between 0 and 100; value '%d' is not allowed."),
940                                                     quality);
941
942                                        return FALSE;
943                                }
944                        } else {
945                                g_warning ("Bad option name '%s' passed to JPEG saver",
946                                           *kiter);
947                                return FALSE;
948                        }
949                
950                        ++kiter;
951                        ++viter;
952                }
953        }
954        
955        rowstride = gdk_pixbuf_get_rowstride (pixbuf);
956        n_channels = gdk_pixbuf_get_n_channels (pixbuf);
957
958        w = gdk_pixbuf_get_width (pixbuf);
959        h = gdk_pixbuf_get_height (pixbuf);
960
961        /* no image data? abort */
962        pixels = gdk_pixbuf_get_pixels (pixbuf);
963        g_return_val_if_fail (pixels != NULL, FALSE);
964
965        /* Allocate a small buffer to convert image data,
966         * and a larger buffer if doing to_callback save.
967         */
968        buf = g_try_malloc (w * 3 * sizeof (guchar));
969        if (!buf) {
970                g_set_error (error,
971                             GDK_PIXBUF_ERROR,
972                             GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
973                             _("Couldn't allocate memory for loading JPEG file"));
974                return FALSE;
975        }
976        if (to_callback) {
977                to_callback_destmgr.buffer = g_try_malloc (TO_FUNCTION_BUF_SIZE);
978                if (!to_callback_destmgr.buffer) {
979                        g_set_error (error,
980                                     GDK_PIXBUF_ERROR,
981                                     GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
982                                     _("Couldn't allocate memory for loading JPEG file"));
983                        return FALSE;
984                }
985        }
986
987        /* set up error handling */
988        jerr.pub.error_exit = fatal_error_handler;
989        jerr.pub.output_message = output_message_handler;
990        jerr.error = error;
991        
992        cinfo.err = jpeg_std_error (&(jerr.pub));
993        if (sigsetjmp (jerr.setjmp_buffer, 1)) {
994                jpeg_destroy_compress (&cinfo);
995                g_free (buf);
996                g_free (to_callback_destmgr.buffer);
997                return FALSE;
998        }
999
1000        /* setup compress params */
1001        jpeg_create_compress (&cinfo);
1002        if (to_callback) {
1003                to_callback_destmgr.pub.init_destination    = to_callback_init;
1004                to_callback_destmgr.pub.empty_output_buffer = to_callback_empty_output_buffer;
1005                to_callback_destmgr.pub.term_destination    = to_callback_terminate;
1006                to_callback_destmgr.error = error;
1007                to_callback_destmgr.save_func = save_func;
1008                to_callback_destmgr.user_data = user_data;
1009                cinfo.dest = (struct jpeg_destination_mgr*) &to_callback_destmgr;
1010        } else {
1011                jpeg_stdio_dest (&cinfo, f);
1012        }
1013        cinfo.image_width      = w;
1014        cinfo.image_height     = h;
1015        cinfo.input_components = 3; 
1016        cinfo.in_color_space   = JCS_RGB;
1017
1018        /* set up jepg compression parameters */
1019        jpeg_set_defaults (&cinfo);
1020        jpeg_set_quality (&cinfo, quality, TRUE);
1021        jpeg_start_compress (&cinfo, TRUE);
1022        /* get the start pointer */
1023        ptr = pixels;
1024        /* go one scanline at a time... and save */
1025        i = 0;
1026        while (cinfo.next_scanline < cinfo.image_height) {
1027                /* convert scanline from ARGB to RGB packed */
1028                for (j = 0; j < w; j++)
1029                        memcpy (&(buf[j*3]), &(ptr[i*rowstride + j*n_channels]), 3);
1030
1031                /* write scanline */
1032                jbuf = (JSAMPROW *)(&buf);
1033                jpeg_write_scanlines (&cinfo, jbuf, 1);
1034                i++;
1035                y++;
1036
1037        }
1038        
1039        /* finish off */
1040        jpeg_finish_compress (&cinfo);
1041        jpeg_destroy_compress(&cinfo);
1042        g_free (buf);
1043        g_free (to_callback_destmgr.buffer);
1044        return TRUE;
1045 }
1046
1047 static gboolean
1048 gdk_pixbuf__jpeg_image_save (FILE          *f, 
1049                              GdkPixbuf     *pixbuf, 
1050                              gchar        **keys,
1051                              gchar        **values,
1052                              GError       **error)
1053 {
1054         return real_save_jpeg (pixbuf, keys, values, error,
1055                                FALSE, f, NULL, NULL);
1056 }
1057
1058 static gboolean
1059 gdk_pixbuf__jpeg_image_save_to_callback (GdkPixbufSaveFunc   save_func,
1060                                          gpointer            user_data,
1061                                          GdkPixbuf          *pixbuf, 
1062                                          gchar             **keys,
1063                                          gchar             **values,
1064                                          GError            **error)
1065 {
1066         return real_save_jpeg (pixbuf, keys, values, error,
1067                                TRUE, NULL, save_func, user_data);
1068 }
1069
1070 void
1071 MODULE_ENTRY (jpeg, fill_vtable) (GdkPixbufModule *module)
1072 {
1073         module->load = gdk_pixbuf__jpeg_image_load;
1074         module->begin_load = gdk_pixbuf__jpeg_image_begin_load;
1075         module->stop_load = gdk_pixbuf__jpeg_image_stop_load;
1076         module->load_increment = gdk_pixbuf__jpeg_image_load_increment;
1077         module->save = gdk_pixbuf__jpeg_image_save;
1078         module->save_to_callback = gdk_pixbuf__jpeg_image_save_to_callback;
1079 }
1080
1081 void
1082 MODULE_ENTRY (jpeg, fill_info) (GdkPixbufFormat *info)
1083 {
1084         static GdkPixbufModulePattern signature[] = {
1085                 { "\xff\xd8", NULL, 100 },
1086                 { NULL, NULL, 0 }
1087         };
1088         static gchar * mime_types[] = {
1089                 "image/jpeg",
1090                 NULL
1091         };
1092         static gchar * extensions[] = {
1093                 "jpeg",
1094                 "jpe",
1095                 "jpg",
1096                 NULL
1097         };
1098
1099         info->name = "jpeg";
1100         info->signature = signature;
1101         info->description = N_("The JPEG image format");
1102         info->mime_types = mime_types;
1103         info->extensions = extensions;
1104         info->flags = GDK_PIXBUF_FORMAT_WRITABLE | GDK_PIXBUF_FORMAT_THREADSAFE;
1105         info->license = "LGPL";
1106 }