]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-jpeg.c
Added first cut at progressive jpeg loading. Currently does not handle
[~andy/gtk] / gdk-pixbuf / io-jpeg.c
1 /* GdkPixbuf library - JPEG image loader
2  *
3  * Copyright (C) 1999 Michael Zucchi
4  * Copyright (C) 1999 The Free Software Foundation
5  * 
6  * Progressive loading code Copyright (C) 1999 Red Hat, Inc.
7  *
8  * Authors: Michael Zucchi <zucchi@zedzone.mmc.com.au>
9  *          Federico Mena-Quintero <federico@gimp.org>
10  *          Michael Fulbright <drmike@redhat.com>
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Library 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.
16  *
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  * Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library 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.
26  */
27
28
29 /*
30   Progressive file loading notes (10/29/199) <drmike@redhat.com>...
31
32   These are issues I know of and will be dealing with shortly:
33
34     -  Currently does not handle progressive jpegs - this
35        requires a change in the way image_load_increment () calls
36        libjpeg. Progressive jpegs are rarer but I will add this
37        support asap.
38
39     - gray images are not properly loaded
40
41     - error handling is not as good as it should be
42
43  */
44
45
46 #include <config.h>
47 #include <stdio.h>
48 #include <setjmp.h>
49 #include <jpeglib.h>
50 #include "gdk-pixbuf.h"
51 #include "gdk-pixbuf-io.h"
52
53 \f
54
55 /* we are a "source manager" as far as libjpeg is concerned */
56 typedef struct {
57         struct jpeg_source_mgr pub;   /* public fields */
58
59         JOCTET * buffer;              /* start of buffer */
60         gboolean start_of_file;       /* have we gotten any data yet? */
61         long  skip_next;              /* number of bytes to skip next read */
62         
63 } my_source_mgr;
64
65 typedef my_source_mgr * my_src_ptr;
66
67 /* error handler data */
68 struct error_handler_data {
69         struct jpeg_error_mgr pub;
70         sigjmp_buf setjmp_buffer;
71 };
72
73 /* progressive loader context */
74 typedef struct {
75         ModulePreparedNotifyFunc notify_func;
76         gpointer                 notify_user_data;
77
78         GdkPixbuf                *pixbuf;
79         guchar                   *dptr;   /* current position in pixbuf */
80
81         gboolean                 did_prescan;  /* are we in image data yet? */
82         gboolean                 got_header;  /* have we loaded jpeg header? */
83         gboolean                 src_initialized;/* TRUE when jpeg lib initialized */
84         struct jpeg_decompress_struct cinfo;
85         struct error_handler_data     jerr;
86 } JpegProgContext;
87
88 #define JPEG_PROG_BUF_SIZE 4096
89
90 GdkPixbuf *image_load (FILE *f);
91 gpointer image_begin_load (ModulePreparedNotifyFunc func, gpointer user_data);
92 void image_stop_load (gpointer context);
93 gboolean image_load_increment(gpointer context, guchar *buf, guint size);
94
95
96 static void
97 fatal_error_handler (j_common_ptr cinfo)
98 {
99         /* FIXME:
100          * We should somehow signal what error occurred to the caller so the
101          * caller can handle the error message */
102         struct error_handler_data *errmgr;
103
104         errmgr = (struct error_handler_data *) cinfo->err;
105         cinfo->err->output_message (cinfo);
106         siglongjmp (errmgr->setjmp_buffer, 1);
107         return;
108 }
109
110 /* Destroy notification function for the libart pixbuf */
111 static void
112 free_buffer (gpointer user_data, gpointer data)
113 {
114         free (data);
115 }
116
117
118 /* explode gray image data from jpeg library into rgb components in pixbuf */
119 static void
120 explode_gray_into_buf (struct jpeg_decompress_struct *cinfo,
121                        guchar **lines) 
122 {
123         gint i, j;
124         guint w;
125
126         g_return_if_fail (cinfo != NULL);
127         g_return_if_fail (cinfo->output_components == 1);
128
129         /* Expand grey->colour.  Expand from the end of the
130          * memory down, so we can use the same buffer.
131          */
132         w = cinfo->image_width;
133         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
134                 guchar *from, *to;
135                 
136                 from = lines[i] + w - 1;
137                 to = lines[i] + (w - 1) * 3;
138                 for (j = w - 1; j >= 0; j--) {
139                         to[0] = from[0];
140                         to[1] = from[1];
141                         to[2] = from[2];
142                         to -= 3;
143                         from--;
144                 }
145         }
146 }
147
148 /* Shared library entry point */
149 GdkPixbuf *
150 image_load (FILE *f)
151 {
152         int w, h, i;
153         guchar *pixels = NULL;
154         guchar *dptr;
155         guchar *lines[4]; /* Used to expand rows, via rec_outbuf_height, from the header file:
156                            * "* Usually rec_outbuf_height will be 1 or 2, at most 4."
157                            */
158         guchar **lptr;
159         struct jpeg_decompress_struct cinfo;
160         struct error_handler_data jerr;
161         GdkPixbuf *pixbuf;
162
163         /* setup error handler */
164         cinfo.err = jpeg_std_error (&jerr.pub);
165         jerr.pub.error_exit = fatal_error_handler;
166
167         if (sigsetjmp (jerr.setjmp_buffer, 1)) {
168                 /* Whoops there was a jpeg error */
169                 if (pixels)
170                         free (pixels);
171
172                 jpeg_destroy_decompress (&cinfo);
173                 return NULL;
174         }
175
176         /* load header, setup */
177         jpeg_create_decompress (&cinfo);
178         jpeg_stdio_src (&cinfo, f);
179         jpeg_read_header (&cinfo, TRUE);
180         jpeg_start_decompress (&cinfo);
181         cinfo.do_fancy_upsampling = FALSE;
182         cinfo.do_block_smoothing = FALSE;
183
184         w = cinfo.output_width;
185         h = cinfo.output_height;
186
187         pixels = malloc (h * w * 3);
188         if (!pixels) {
189                 jpeg_destroy_decompress (&cinfo);
190                 return NULL;
191         }
192
193         dptr = pixels;
194
195         /* decompress all the lines, a few at a time */
196
197         while (cinfo.output_scanline < cinfo.output_height) {
198                 lptr = lines;
199                 for (i = 0; i < cinfo.rec_outbuf_height; i++) {
200                         *lptr++ = dptr;
201                         dptr += w * 3;
202                 }
203
204                 jpeg_read_scanlines (&cinfo, lines, cinfo.rec_outbuf_height);
205
206                 if (cinfo.output_components == 1)
207                         explode_gray_into_buf (&cinfo, lines);
208         }
209
210         jpeg_finish_decompress (&cinfo);
211         jpeg_destroy_decompress (&cinfo);
212
213         return gdk_pixbuf_new_from_data (pixels, ART_PIX_RGB, FALSE,
214                                          w, h, w * 3,
215                                          free_buffer, NULL);
216
217         return pixbuf;
218 }
219
220
221 /**** Progressive image loading handling *****/
222
223 /* these routines required because we are acting as a source manager for */
224 /* libjpeg. */
225 static void
226 init_source (j_decompress_ptr cinfo)
227 {
228         my_src_ptr src = (my_src_ptr) cinfo->src;
229
230         src->start_of_file = TRUE;
231         src->skip_next = 0;
232 }
233
234
235 static void
236 term_source (j_decompress_ptr cinfo)
237 {
238         /* XXXX - probably should scream something has happened */
239 }
240
241
242 /* for progressive loading (called "I/O Suspension" by libjpeg docs) */
243 /* we do nothing except return "FALSE"                               */
244 static boolean
245 fill_input_buffer (j_decompress_ptr cinfo)
246 {
247         return FALSE;
248 }
249
250
251 static void
252 skip_input_data (j_decompress_ptr cinfo, long num_bytes)
253 {
254         my_src_ptr src = (my_src_ptr) cinfo->src;
255         long   num_can_do;
256
257         /* move as far as we can into current buffer */
258         /* then set skip_next to catch the rest      */
259         if (num_bytes > 0) {
260                 num_can_do = MIN (src->pub.bytes_in_buffer, num_bytes);
261                 src->pub.next_input_byte += (size_t) num_can_do;
262                 src->pub.bytes_in_buffer -= (size_t) num_can_do;
263
264                 src->skip_next = num_bytes - num_can_do;
265         }
266 }
267
268  
269 /* 
270  * func - called when we have pixmap created (but no image data)
271  * user_data - passed as arg 1 to func
272  * return context (opaque to user)
273  */
274
275 gpointer
276 image_begin_load (ModulePreparedNotifyFunc func, gpointer user_data)
277 {
278         JpegProgContext *context;
279         my_source_mgr   *src;
280
281         context = g_new (JpegProgContext, 1);
282         context->notify_func = func;
283         context->notify_user_data = user_data;
284         context->pixbuf = NULL;
285         context->got_header = FALSE;
286         context->did_prescan = FALSE;
287         context->src_initialized = FALSE;
288
289         /* create libjpeg structures */
290         jpeg_create_decompress (&context->cinfo);
291
292         context->cinfo.src = (struct jpeg_source_mgr *) g_new (my_source_mgr, 1);
293         src = (my_src_ptr) context->cinfo.src;
294         src->buffer = g_malloc (JPEG_PROG_BUF_SIZE);
295
296         context->cinfo.err = jpeg_std_error (&context->jerr.pub);
297
298         src = (my_src_ptr) context->cinfo.src;
299         src->pub.init_source = init_source;
300         src->pub.fill_input_buffer = fill_input_buffer;
301         src->pub.skip_input_data = skip_input_data;
302         src->pub.resync_to_restart = jpeg_resync_to_restart;
303         src->pub.term_source = term_source;
304         src->pub.bytes_in_buffer = 0;
305         src->pub.next_input_byte = NULL;
306
307         return (gpointer) context;
308 }
309
310 /*
311  * context - returned from image_begin_load
312  *
313  * free context, unref gdk_pixbuf
314  */
315 void
316 image_stop_load (gpointer data)
317 {
318         JpegProgContext *context = (JpegProgContext *) data;
319         g_return_if_fail (context != NULL);
320
321         /* XXXX - is this all I have to do to cleanup? */
322         if (context->pixbuf)
323                 gdk_pixbuf_unref (context->pixbuf);
324
325         if (context->cinfo.src) {
326                 my_src_ptr src = (my_src_ptr) context->cinfo.src;
327                 
328                 if (src->buffer)
329                         g_free (src->buffer);
330                 g_free (src);
331         }
332
333         jpeg_finish_decompress(&context->cinfo);
334         jpeg_destroy_decompress(&context->cinfo);
335
336         g_free (context);
337 }
338
339
340
341
342 /*
343  * context - from image_begin_load
344  * buf - new image data
345  * size - length of new image data
346  *
347  * append image data onto inrecrementally built output image
348  */
349 gboolean
350 image_load_increment (gpointer data, guchar *buf, guint size)
351 {
352         JpegProgContext *context = (JpegProgContext *)data;
353         struct jpeg_decompress_struct *cinfo;
354         my_src_ptr  src;
355         guint       num_left, num_copy;
356         guchar      *nextptr;
357
358         g_return_val_if_fail (context != NULL, FALSE);
359         g_return_val_if_fail (buf != NULL, FALSE);
360
361         src = (my_src_ptr) context->cinfo.src;
362         cinfo = &context->cinfo;
363
364         /* skip over data if requested, handle unsigned int sizes cleanly */
365         /* only can happen if we've already called jpeg_get_header once   */
366         if (context->src_initialized && src->skip_next) {
367                 if (src->skip_next > size) {
368                         src->skip_next -= size;
369                         return TRUE;
370                 } else {
371                         num_left = size - src->skip_next;
372                         src->skip_next = 0;
373                 }
374         } else {
375                 num_left = size;
376         }
377
378         while (num_left > 0) {
379                 /* copy as much data into buffer as possible */
380                 num_copy = MIN (JPEG_PROG_BUF_SIZE - src->pub.bytes_in_buffer,
381                                 size);
382
383                 if (num_copy == 0) 
384                         g_assert ("Buffer overflow!\n");
385
386                 nextptr = src->buffer + src->pub.bytes_in_buffer;
387                 memcpy (nextptr, buf, num_copy);
388                 
389                 if (src->pub.next_input_byte == NULL ||
390                     src->pub.bytes_in_buffer == 0)
391                         src->pub.next_input_byte = src->buffer;
392
393                 src->pub.bytes_in_buffer += num_copy;
394
395                 num_left -= num_copy;
396
397                 /* try to load jpeg header */
398                 /* XXXX - bad - assume we always have enough data */
399                 /*              to determine header info in first */
400                 /*              invocation of this function       */
401                 if (!context->got_header) {
402                         int rc;
403
404                         rc = jpeg_read_header (cinfo, TRUE);
405                         context->src_initialized = TRUE;
406                         if (rc == JPEG_SUSPENDED)
407                                 continue;
408
409                         context->got_header = TRUE;
410
411                         if (jpeg_has_multiple_scans (cinfo)) {
412                                 g_print ("io-jpeg.c: Does not currently "
413                                          "support progressive jpeg files.\n");
414                                 return FALSE;
415                         }
416
417                         context->pixbuf = gdk_pixbuf_new(ART_PIX_RGB, 
418                                                          /*have_alpha*/ FALSE,
419                                                          8, 
420                                                          cinfo->image_width,
421                                                          cinfo->image_height);
422
423                         if (context->pixbuf == NULL) {
424                                 /* Failed to allocate memory */
425                                 g_assert ("Couldn't allocate gdkpixbuf\n");
426                         }
427
428                         /* Use pixbuf pixel buffer - BUT NOT SURE */
429                         /* we handle rowstride correctly!!!!      */
430                         context->dptr = context->pixbuf->art_pixbuf->pixels;
431
432                         /* Notify the client that we are ready to go */
433
434                         if (context->notify_func)
435                                 (* context->notify_func) (context->pixbuf,
436                                                           context->notify_user_data);
437
438                         src->start_of_file = FALSE;
439                 } else if (!context->did_prescan) {
440                         int rc;
441
442                         /* start decompression */
443                         rc = jpeg_start_decompress (cinfo);
444                         cinfo->do_fancy_upsampling = FALSE;
445                         cinfo->do_block_smoothing = FALSE;
446
447                         if (rc == JPEG_SUSPENDED)
448                                 continue;
449
450                         context->did_prescan = TRUE;
451                 } else {
452                         /* we're decompressing so feed jpeg lib scanlines */
453                         guchar *lines[4];
454                         guchar **lptr;
455                         guchar *rowptr;
456                         gint   nlines, i;
457                         gint   start_scanline;
458
459                         /* THIS COULD BE BROKEN */
460                         /* Assumes rowstride of gdkpixbuf pixel buffer */
461                         /* is same as incoming jpeg data!              */
462
463                         while (cinfo->output_scanline < cinfo->output_height) {
464                                 start_scanline = cinfo->output_scanline;
465                                 lptr = lines;
466                                 rowptr = context->dptr;
467                                 for (i=0; i < cinfo->rec_outbuf_height; i++) {
468                                         *lptr++ = rowptr;
469                                         rowptr += cinfo->image_width * 3;
470                                 }
471                                 
472                                 nlines = jpeg_read_scanlines (cinfo, lines,
473                                                               cinfo->rec_outbuf_height);
474                                 if (nlines == 0)
475                                         break;
476
477                                 /* handle gray */
478                                 if (cinfo->output_components == 1)
479                                         explode_gray_into_buf (cinfo, lines);
480
481                                 context->dptr += nlines * cinfo->image_width * 3;
482 #ifdef DEBUG_JPEG_PROGRESSIVE
483                                 
484                                 if (start_scanline != cinfo->output_scanline)
485                                         g_print("jpeg: Input pass=%2d, next input scanline=%3d,"
486                                                 " emitted %3d - %3d\n",
487                                                 cinfo->input_scan_number, cinfo->input_iMCU_row * 16,
488                                                 start_scanline, cinfo->output_scanline - 1);
489                                 
490                                 
491                                 
492                                 g_print ("Scanline %d of %d - ", 
493                                          cinfo->output_scanline,
494                                          cinfo->output_height);
495 /*                      g_print ("rec_height %d -", cinfo->rec_outbuf_height); */
496                                 g_print ("Processed %d lines - bytes left = %d\n",
497                                          nlines, cinfo->src->bytes_in_buffer);
498 #endif
499                         }
500                 }
501         }
502
503         return TRUE;
504 }