]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-jpeg.c
make the symlink. Does not work for srcdir != buildir != . Beats me why; I
[~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 (11/03/1999) <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     - error handling is not as good as it should be
40
41  */
42
43
44 #include <config.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <setjmp.h>
49 #include <jpeglib.h>
50 #include "gdk-pixbuf/gdk-pixbuf.h"
51 #include "gdk-pixbuf/gdk-pixbuf-io.h"
52
53 \f
54
55 /* we are a "source manager" as far as libjpeg is concerned */
56 #define JPEG_PROG_BUF_SIZE 4096
57
58 typedef struct {
59         struct jpeg_source_mgr pub;   /* public fields */
60
61         JOCTET buffer[JPEG_PROG_BUF_SIZE];              /* start of buffer */
62         long  skip_next;              /* number of bytes to skip next read */
63
64 } my_source_mgr;
65
66 typedef my_source_mgr * my_src_ptr;
67
68 /* error handler data */
69 struct error_handler_data {
70         struct jpeg_error_mgr pub;
71         sigjmp_buf setjmp_buffer;
72 };
73
74 /* progressive loader context */
75 typedef struct {
76         ModuleUpdatedNotifyFunc  updated_func;
77         ModulePreparedNotifyFunc prepared_func;
78         gpointer                 user_data;
79         
80         GdkPixbuf                *pixbuf;
81         guchar                   *dptr;   /* current position in pixbuf */
82
83         gboolean                 did_prescan;  /* are we in image data yet? */
84         gboolean                 got_header;  /* have we loaded jpeg header? */
85         gboolean                 src_initialized;/* TRUE when jpeg lib initialized */
86         struct jpeg_decompress_struct cinfo;
87         struct error_handler_data     jerr;
88 } JpegProgContext;
89
90 GdkPixbuf *image_load (FILE *f);
91 gpointer image_begin_load (ModulePreparedNotifyFunc func, 
92                            ModuleUpdatedNotifyFunc func2, gpointer user_data);
93 void image_stop_load (gpointer context);
94 gboolean image_load_increment(gpointer context, guchar *buf, guint size);
95
96
97 static void
98 fatal_error_handler (j_common_ptr cinfo)
99 {
100         /* FIXME:
101          * We should somehow signal what error occurred to the caller so the
102          * caller can handle the error message */
103         struct error_handler_data *errmgr;
104
105         errmgr = (struct error_handler_data *) cinfo->err;
106         cinfo->err->output_message (cinfo);
107         siglongjmp (errmgr->setjmp_buffer, 1);
108         return;
109 }
110
111 /* Destroy notification function for the libart pixbuf */
112 static void
113 free_buffer (gpointer user_data, gpointer data)
114 {
115         free (data);
116 }
117
118
119 /* explode gray image data from jpeg library into rgb components in pixbuf */
120 static void
121 explode_gray_into_buf (struct jpeg_decompress_struct *cinfo,
122                        guchar **lines) 
123 {
124         gint i, j;
125         guint w;
126
127         g_return_if_fail (cinfo != NULL);
128         g_return_if_fail (cinfo->output_components == 1);
129
130         /* Expand grey->colour.  Expand from the end of the
131          * memory down, so we can use the same buffer.
132          */
133         w = cinfo->image_width;
134         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
135                 guchar *from, *to;
136                 
137                 from = lines[i] + w - 1;
138                 to = lines[i] + (w - 1) * 3;
139                 for (j = w - 1; j >= 0; j--) {
140                         to[0] = from[0];
141                         to[1] = from[0];
142                         to[2] = from[0];
143                         to -= 3;
144                         from--;
145                 }
146         }
147 }
148
149 /* Shared library entry point */
150 GdkPixbuf *
151 image_load (FILE *f)
152 {
153         gint w, h, i;
154         guchar *pixels = NULL;
155         guchar *dptr;
156         guchar *lines[4]; /* Used to expand rows, via rec_outbuf_height, 
157                            * from the header file: 
158                            * " Usually rec_outbuf_height will be 1 or 2, 
159                            * at most 4."
160                            */
161         guchar **lptr;
162         struct jpeg_decompress_struct cinfo;
163         struct error_handler_data jerr;
164
165         /* setup error handler */
166         cinfo.err = jpeg_std_error (&jerr.pub);
167         jerr.pub.error_exit = fatal_error_handler;
168
169         if (sigsetjmp (jerr.setjmp_buffer, 1)) {
170                 /* Whoops there was a jpeg error */
171                 if (pixels)
172                         free (pixels);
173
174                 jpeg_destroy_decompress (&cinfo);
175                 return NULL;
176         }
177
178         /* load header, setup */
179         jpeg_create_decompress (&cinfo);
180         jpeg_stdio_src (&cinfo, f);
181         jpeg_read_header (&cinfo, TRUE);
182         jpeg_start_decompress (&cinfo);
183         cinfo.do_fancy_upsampling = FALSE;
184         cinfo.do_block_smoothing = FALSE;
185
186         w = cinfo.output_width;
187         h = cinfo.output_height;
188
189         pixels = g_malloc (h * w * 3);
190         if (!pixels) {
191                 jpeg_destroy_decompress (&cinfo);
192                 return NULL;
193         }
194
195         dptr = pixels;
196
197         /* decompress all the lines, a few at a time */
198
199         while (cinfo.output_scanline < cinfo.output_height) {
200                 lptr = lines;
201                 for (i = 0; i < cinfo.rec_outbuf_height; i++) {
202                         *lptr++ = dptr;
203                         dptr += w * 3;
204                 }
205
206                 jpeg_read_scanlines (&cinfo, lines, cinfo.rec_outbuf_height);
207
208                 if (cinfo.output_components == 1)
209                         explode_gray_into_buf (&cinfo, lines);
210         }
211
212         jpeg_finish_decompress (&cinfo);
213         jpeg_destroy_decompress (&cinfo);
214
215         return gdk_pixbuf_new_from_data (pixels, ART_PIX_RGB, FALSE,
216                                          w, h, w * 3,
217                                          free_buffer, NULL);
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->skip_next = 0;
231 }
232
233
234 static void
235 term_source (j_decompress_ptr cinfo)
236 {
237         /* XXXX - probably should scream something has happened */
238 }
239
240
241 /* for progressive loading (called "I/O Suspension" by libjpeg docs) */
242 /* we do nothing except return "FALSE"                               */
243 static boolean
244 fill_input_buffer (j_decompress_ptr cinfo)
245 {
246         return FALSE;
247 }
248
249
250 static void
251 skip_input_data (j_decompress_ptr cinfo, long num_bytes)
252 {
253         my_src_ptr src = (my_src_ptr) cinfo->src;
254         long   num_can_do;
255
256         /* move as far as we can into current buffer */
257         /* then set skip_next to catch the rest      */
258         if (num_bytes > 0) {
259                 num_can_do = MIN (src->pub.bytes_in_buffer, num_bytes);
260                 src->pub.next_input_byte += (size_t) num_can_do;
261                 src->pub.bytes_in_buffer -= (size_t) num_can_do;
262
263                 src->skip_next = num_bytes - num_can_do;
264         }
265 }
266
267  
268 /* 
269  * func - called when we have pixmap created (but no image data)
270  * user_data - passed as arg 1 to func
271  * return context (opaque to user)
272  */
273
274 gpointer
275 image_begin_load (ModulePreparedNotifyFunc prepared_func, 
276                   ModuleUpdatedNotifyFunc  updated_func,
277                   gpointer user_data)
278 {
279         JpegProgContext *context;
280         my_source_mgr   *src;
281
282         context = g_new0 (JpegProgContext, 1);
283         context->prepared_func = prepared_func;
284         context->updated_func  = updated_func;
285         context->user_data = user_data;
286         context->pixbuf = NULL;
287         context->got_header = FALSE;
288         context->did_prescan = FALSE;
289         context->src_initialized = FALSE;
290
291         /* create libjpeg structures */
292         jpeg_create_decompress (&context->cinfo);
293
294         context->cinfo.src = (struct jpeg_source_mgr *) g_new0 (my_source_mgr, 1);
295         src = (my_src_ptr) context->cinfo.src;
296
297         context->cinfo.err = jpeg_std_error (&context->jerr.pub);
298
299         src = (my_src_ptr) context->cinfo.src;
300         src->pub.init_source = init_source;
301         src->pub.fill_input_buffer = fill_input_buffer;
302         src->pub.skip_input_data = skip_input_data;
303         src->pub.resync_to_restart = jpeg_resync_to_restart;
304         src->pub.term_source = term_source;
305         src->pub.bytes_in_buffer = 0;
306         src->pub.next_input_byte = NULL;
307
308         return (gpointer) context;
309 }
310
311 /*
312  * context - returned from image_begin_load
313  *
314  * free context, unref gdk_pixbuf
315  */
316 void
317 image_stop_load (gpointer data)
318 {
319         JpegProgContext *context = (JpegProgContext *) data;
320
321         g_return_if_fail (context != NULL);
322
323         if (context->pixbuf)
324                 gdk_pixbuf_unref (context->pixbuf);
325
326         jpeg_finish_decompress(&context->cinfo);
327         jpeg_destroy_decompress(&context->cinfo);
328
329         if (context->cinfo.src) {
330                 my_src_ptr src = (my_src_ptr) context->cinfo.src;
331                 
332                 g_free (src);
333         }
334
335         g_free (context);
336 }
337
338
339
340
341 /*
342  * context - from image_begin_load
343  * buf - new image data
344  * size - length of new image data
345  *
346  * append image data onto inrecrementally built output image
347  */
348 gboolean
349 image_load_increment (gpointer data, guchar *buf, guint size)
350 {
351         JpegProgContext *context = (JpegProgContext *)data;
352         struct jpeg_decompress_struct *cinfo;
353         my_src_ptr  src;
354         guint       num_left, num_copy;
355         guint       last_bytes_left;
356         guint       spinguard;
357         gboolean    first;
358         guchar *bufhd;
359
360         g_return_val_if_fail (context != NULL, FALSE);
361         g_return_val_if_fail (buf != NULL, FALSE);
362
363         src = (my_src_ptr) context->cinfo.src;
364
365         cinfo = &context->cinfo;
366
367         /* XXXXXXX (drmike) - loop(s) below need to be recoded now I
368          *                    have a grasp of what the flow needs to be!
369          */
370
371
372         /* skip over data if requested, handle unsigned int sizes cleanly */
373         /* only can happen if we've already called jpeg_get_header once   */
374         if (context->src_initialized && src->skip_next) {
375                 if (src->skip_next > size) {
376                         src->skip_next -= size;
377                         return TRUE;
378                 } else {
379                         num_left = size - src->skip_next;
380                         bufhd = buf + src->skip_next;
381                         src->skip_next = 0;
382                 }
383         } else {
384                 num_left = size;
385                 bufhd = buf;
386         }
387
388         if (num_left == 0)
389                 return TRUE;
390
391         last_bytes_left = 0;
392         spinguard = 0;
393         first = TRUE;
394         while (TRUE) {
395
396                 /* handle any data from caller we haven't processed yet */
397                 if (num_left > 0) {
398                         if(src->pub.bytes_in_buffer && 
399                            src->pub.next_input_byte != src->buffer)
400                                 memmove(src->buffer, src->pub.next_input_byte,
401                                         src->pub.bytes_in_buffer);
402
403
404                         num_copy = MIN (JPEG_PROG_BUF_SIZE - src->pub.bytes_in_buffer,
405                                         num_left);
406
407 /*                      if (num_copy == 0) 
408                                 g_error ("Buffer overflow!");
409 */
410                         memcpy(src->buffer + src->pub.bytes_in_buffer, bufhd,num_copy);
411                         src->pub.next_input_byte = src->buffer;
412                         src->pub.bytes_in_buffer += num_copy;
413                         bufhd += num_copy;
414                         num_left -= num_copy;
415                 } else {
416                 /* did anything change from last pass, if not return */
417                         if (first) {
418                                 last_bytes_left = src->pub.bytes_in_buffer;
419                                 first = FALSE;
420                         } else if (src->pub.bytes_in_buffer == last_bytes_left)
421                                 spinguard++;
422                         else
423                                 last_bytes_left = src->pub.bytes_in_buffer;
424                 }
425
426                 /* should not go through twice and not pull bytes out of buf */
427                 if (spinguard > 2)
428                         return TRUE;
429
430                 /* try to load jpeg header */
431                 if (!context->got_header) {
432                         int rc;
433
434                         rc = jpeg_read_header (cinfo, TRUE);
435                         context->src_initialized = TRUE;
436
437                         if (rc == JPEG_SUSPENDED)
438                                 continue;
439
440                         context->got_header = TRUE;
441
442 #if 0
443                         if (jpeg_has_multiple_scans (cinfo)) {
444                                 g_print ("io-jpeg.c: Does not currently "
445                                          "support progressive jpeg files.\n");
446                                 return FALSE;
447                         }
448 #endif
449                         context->pixbuf = gdk_pixbuf_new(ART_PIX_RGB, 
450                                                          /*have_alpha*/ FALSE,
451                                                          8, 
452                                                          cinfo->image_width,
453                                                          cinfo->image_height);
454
455                         if (context->pixbuf == NULL) {
456                                 /* Failed to allocate memory */
457                                 g_error ("Couldn't allocate gdkpixbuf");
458                         }
459
460                         /* Use pixbuf buffer to store decompressed data */
461                         context->dptr = context->pixbuf->art_pixbuf->pixels;
462
463                         /* Notify the client that we are ready to go */
464                         (* context->prepared_func) (context->pixbuf,
465                                                     context->user_data);
466
467                 } else if (!context->did_prescan) {
468                         int rc;
469
470                         /* start decompression */
471                         rc = jpeg_start_decompress (cinfo);
472                         cinfo->do_fancy_upsampling = FALSE;
473                         cinfo->do_block_smoothing = FALSE;
474
475                         if (rc == JPEG_SUSPENDED)
476                                 continue;
477
478                         context->did_prescan = TRUE;
479                 } else {
480
481                         /* we're decompressing so feed jpeg lib scanlines */
482                         guchar *lines[4];
483                         guchar **lptr;
484                         guchar *rowptr;
485                         gint   nlines, i;
486                         gint   start_scanline;
487
488                         /* keep going until we've done all scanlines */
489                         while (cinfo->output_scanline < cinfo->output_height) {
490                                 start_scanline = cinfo->output_scanline;
491                                 lptr = lines;
492                                 rowptr = context->dptr;
493                                 for (i=0; i < cinfo->rec_outbuf_height; i++) {
494                                         *lptr++ = rowptr;
495                                         rowptr += context->pixbuf->art_pixbuf->rowstride;
496                                 }
497
498                                 nlines = jpeg_read_scanlines (cinfo, lines,
499                                                               cinfo->rec_outbuf_height);
500                                 if (nlines == 0)
501                                         break;
502
503                                 /* handle gray */
504                                 if (cinfo->output_components == 1)
505                                         explode_gray_into_buf (cinfo, lines);
506
507                                 context->dptr += nlines * context->pixbuf->art_pixbuf->rowstride;
508
509                                 /* send updated signal */
510                                 (* context->updated_func) (context->pixbuf,
511                                                  context->user_data,
512                                                  0, 
513                                                  cinfo->output_scanline-1,
514                                                  cinfo->image_width, 
515                                                  nlines);
516
517 #undef DEBUG_JPEG_PROGRESSIVE
518 #ifdef DEBUG_JPEG_PROGRESSIVE
519                                 
520                                 if (start_scanline != cinfo->output_scanline)
521                                         g_print("jpeg: Input pass=%2d, next input scanline=%3d,"
522                                                 " emitted %3d - %3d\n",
523                                                 cinfo->input_scan_number, cinfo->input_iMCU_row * 16,
524                                                 start_scanline, cinfo->output_scanline - 1);
525                                 
526                                 
527                                 
528                                 g_print ("Scanline %d of %d - ", 
529                                          cinfo->output_scanline,
530                                          cinfo->output_height);
531 /*                      g_print ("rec_height %d -", cinfo->rec_outbuf_height); */
532                                 g_print ("Processed %d lines - bytes left = %d\n",
533                                          nlines, cinfo->src->bytes_in_buffer);
534 #endif
535                         }
536                         /* did entire image */
537                         if (cinfo->output_scanline >= cinfo->output_height)
538                                 return TRUE;
539                         else
540                                 continue;
541                 }
542         }
543
544         return TRUE;
545 }