improved mpo parser, consider individual image type code
[geeqie.git] / src / image_load_jpeg.c
1 /*
2  * Geeqie
3  * (C) 2004 John Ellis
4  * Copyright (C) 2008 - 2011 The Geeqie Team
5  *
6  * Author: Vladimir Nadvornik
7  *
8  * This software is released under the GNU General Public License (GNU GPL).
9  * Please read the included file COPYING for more information.
10  * This software comes with no warranty of any kind, use at your own risk!
11  */
12
13 /* based on code from GdkPixbuf library - JPEG image loader
14  *
15  * Copyright (C) 1999 Michael Zucchi
16  * Copyright (C) 1999 The Free Software Foundation
17  * 
18  * Progressive loading code Copyright (C) 1999 Red Hat, Inc.
19  *
20  * Authors: Michael Zucchi <zucchi@zedzone.mmc.com.au>
21  *          Federico Mena-Quintero <federico@gimp.org>
22  *          Michael Fulbright <drmike@redhat.com>
23  *
24  * This library is free software; you can redistribute it and/or
25  * modify it under the terms of the GNU Lesser General Public
26  * License as published by the Free Software Foundation; either
27  * version 2 of the License, or (at your option) any later version.
28  *
29  * This library is distributed in the hope that it will be useful,
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
32  * Lesser General Public License for more details.
33  *
34  * You should have received a copy of the GNU Lesser General Public
35  * License along with this library; if not, write to the
36  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
37  * Boston, MA 02111-1307, USA.
38  */
39
40
41 #include "main.h"
42 #include "image-load.h"
43 #include "image_load_jpeg.h"
44 #include "jpeg_parser.h"
45
46 #include <setjmp.h>
47 #include <jpeglib.h>
48 #include <jerror.h>
49
50 typedef struct _ImageLoaderJpeg ImageLoaderJpeg;
51 struct _ImageLoaderJpeg {
52         ImageLoaderBackendCbAreaUpdated area_updated_cb;
53         ImageLoaderBackendCbSize size_cb;
54         ImageLoaderBackendCbAreaPrepared area_prepared_cb;
55         
56         gpointer data;
57         
58         GdkPixbuf *pixbuf;
59         guint requested_width;
60         guint requested_height;
61         
62         gboolean abort;
63         gboolean stereo;
64         
65 };
66
67 /* error handler data */
68 struct error_handler_data {
69         struct jpeg_error_mgr pub;
70         sigjmp_buf setjmp_buffer;
71         GError **error;
72 };
73
74 /* explode gray image data from jpeg library into rgb components in pixbuf */
75 static void
76 explode_gray_into_buf (struct jpeg_decompress_struct *cinfo,
77                        guchar **lines) 
78 {
79         gint i, j;
80         guint w;
81
82         g_return_if_fail (cinfo != NULL);
83         g_return_if_fail (cinfo->output_components == 1);
84         g_return_if_fail (cinfo->out_color_space == JCS_GRAYSCALE);
85
86         /* Expand grey->colour.  Expand from the end of the
87          * memory down, so we can use the same buffer.
88          */
89         w = cinfo->output_width;
90         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
91                 guchar *from, *to;
92                 
93                 from = lines[i] + w - 1;
94                 to = lines[i] + (w - 1) * 3;
95                 for (j = w - 1; j >= 0; j--) {
96                         to[0] = from[0];
97                         to[1] = from[0];
98                         to[2] = from[0];
99                         to -= 3;
100                         from--;
101                 }
102         }
103 }
104
105
106 static void
107 convert_cmyk_to_rgb (struct jpeg_decompress_struct *cinfo,
108                      guchar **lines) 
109 {
110         gint i, j;
111
112         g_return_if_fail (cinfo != NULL);
113         g_return_if_fail (cinfo->output_components == 4);
114         g_return_if_fail (cinfo->out_color_space == JCS_CMYK);
115
116         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
117                 guchar *p;
118                 
119                 p = lines[i];
120                 for (j = 0; j < cinfo->output_width; j++) {
121                         int c, m, y, k;
122                         c = p[0];
123                         m = p[1];
124                         y = p[2];
125                         k = p[3];
126                         if (cinfo->saw_Adobe_marker) {
127                                 p[0] = k*c / 255;
128                                 p[1] = k*m / 255;
129                                 p[2] = k*y / 255;
130                         }
131                         else {
132                                 p[0] = (255 - k)*(255 - c) / 255;
133                                 p[1] = (255 - k)*(255 - m) / 255;
134                                 p[2] = (255 - k)*(255 - y) / 255;
135                         }
136                         p[3] = 255;
137                         p += 4;
138                 }
139         }
140 }
141
142
143 static gpointer image_loader_jpeg_new(ImageLoaderBackendCbAreaUpdated area_updated_cb, ImageLoaderBackendCbSize size_cb, ImageLoaderBackendCbAreaPrepared area_prepared_cb, gpointer data)
144 {
145         ImageLoaderJpeg *loader = g_new0(ImageLoaderJpeg, 1);
146         
147         loader->area_updated_cb = area_updated_cb;
148         loader->size_cb = size_cb;
149         loader->area_prepared_cb = area_prepared_cb;
150         loader->data = data;
151         return (gpointer) loader;
152 }
153
154 static void
155 fatal_error_handler (j_common_ptr cinfo)
156 {
157         struct error_handler_data *errmgr;
158         char buffer[JMSG_LENGTH_MAX];
159         
160         errmgr = (struct error_handler_data *) cinfo->err;
161         
162         /* Create the message */
163         (* cinfo->err->format_message) (cinfo, buffer);
164
165         /* broken check for *error == NULL for robustness against
166          * crappy JPEG library
167          */
168         if (errmgr->error && *errmgr->error == NULL) {
169                 g_set_error (errmgr->error,
170                              GDK_PIXBUF_ERROR,
171                              cinfo->err->msg_code == JERR_OUT_OF_MEMORY 
172                              ? GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY 
173                              : GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
174                              _("Error interpreting JPEG image file (%s)"),
175                              buffer);
176         }
177         
178         siglongjmp (errmgr->setjmp_buffer, 1);
179
180         g_assert_not_reached ();
181 }
182
183 static void
184 output_message_handler (j_common_ptr cinfo)
185 {
186   /* This method keeps libjpeg from dumping crap to stderr */
187
188   /* do nothing */
189 }
190
191
192 void image_loader_jpeg_read_scanline(struct jpeg_decompress_struct *cinfo, guchar **dptr, guint rowstride)
193 {
194         guchar *lines[4];
195         guchar **lptr;
196         gint i;
197
198         lptr = lines;
199         for (i = 0; i < cinfo->rec_outbuf_height; i++) 
200                 {
201                 *lptr++ = *dptr;
202                 *dptr += rowstride;
203                 }
204
205         jpeg_read_scanlines (cinfo, lines, cinfo->rec_outbuf_height);
206
207         switch (cinfo->out_color_space) 
208                 {
209                     case JCS_GRAYSCALE:
210                       explode_gray_into_buf (cinfo, lines);
211                       break;
212                     case JCS_RGB:
213                       /* do nothing */
214                       break;
215                     case JCS_CMYK:
216                       convert_cmyk_to_rgb (cinfo, lines);
217                       break;
218                     default:
219                       break;
220                 }
221 }
222
223
224 static void init_source (j_decompress_ptr cinfo) {}
225 static boolean fill_input_buffer (j_decompress_ptr cinfo)
226 {
227         ERREXIT(cinfo, JERR_INPUT_EMPTY);
228 }
229 static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
230 {
231         struct jpeg_source_mgr* src = (struct jpeg_source_mgr*) cinfo->src;
232
233         if (num_bytes > 0) 
234                 {
235                 src->next_input_byte += (size_t) num_bytes;
236                 src->bytes_in_buffer -= (size_t) num_bytes;
237                 }
238 }
239 static void term_source (j_decompress_ptr cinfo) {}
240 static void set_mem_src (j_decompress_ptr cinfo, void* buffer, long nbytes)
241 {
242         struct jpeg_source_mgr* src;
243
244         if (cinfo->src == NULL) 
245                 {   /* first time for this JPEG object? */
246                 cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) (
247                                         (j_common_ptr) cinfo, JPOOL_PERMANENT,
248                                         sizeof(struct jpeg_source_mgr));
249                 }
250
251         src = (struct jpeg_source_mgr*) cinfo->src;
252         src->init_source = init_source;
253         src->fill_input_buffer = fill_input_buffer;
254         src->skip_input_data = skip_input_data;
255         src->resync_to_restart = jpeg_resync_to_restart; /* use default method */
256         src->term_source = term_source;
257         src->bytes_in_buffer = nbytes;
258         src->next_input_byte = (JOCTET*)buffer;
259 }
260
261
262 static gboolean image_loader_jpeg_load (gpointer loader, const guchar *buf, gsize count, GError **error)
263 {
264         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
265         struct jpeg_decompress_struct cinfo;
266         struct jpeg_decompress_struct cinfo2;
267         guchar *dptr, *dptr2;
268         guint rowstride;
269         guchar *stereo_buf2 = NULL;
270         guint stereo_length = 0;
271
272         struct error_handler_data jerr;
273         
274         lj->stereo = FALSE;
275
276         MPOData *mpo = jpeg_get_mpo_data(buf, count);
277         if (mpo && mpo->num_images > 1)
278                 {
279                 guint i;
280                 gint idx1 = -1, idx2 = -1;
281                 guint num2 = 1;
282                 
283                 for (i = 0; i < mpo->num_images; i++)
284                         {
285                         if (mpo->images[i].type_code == 0x20002)
286                                 {
287                                 if (mpo->images[i].MPIndividualNum == 1)
288                                         {
289                                         idx1 = i;
290                                         }
291                                 else if (mpo->images[i].MPIndividualNum > num2)
292                                         {
293                                         idx2 = i;
294                                         num2 = mpo->images[i].MPIndividualNum;
295                                         }
296                                 }
297                         }
298                         
299                 if (idx1 >= 0 && idx2 >= 0)
300                         {
301                         lj->stereo = TRUE;
302                         stereo_buf2 = (unsigned char *)buf + mpo->images[idx2].offset;
303                         stereo_length = mpo->images[idx2].length;
304                         buf = (unsigned char *)buf + mpo->images[idx1].offset;
305                         count = mpo->images[idx1].length;
306                         }
307                 }
308         jpeg_mpo_data_free(mpo);
309
310         /* setup error handler */
311         cinfo.err = jpeg_std_error (&jerr.pub);
312         if (lj->stereo) cinfo2.err = jpeg_std_error (&jerr.pub);
313         jerr.pub.error_exit = fatal_error_handler;
314         jerr.pub.output_message = output_message_handler;
315
316         jerr.error = error;
317
318
319         if (setjmp(jerr.setjmp_buffer)) 
320                 {
321                 /* If we get here, the JPEG code has signaled an error.
322                  * We need to clean up the JPEG object, close the input file, and return.
323                 */
324                 jpeg_destroy_decompress(&cinfo);
325                 if (lj->stereo) jpeg_destroy_decompress(&cinfo2);
326                 return FALSE;
327                 }
328         
329         jpeg_create_decompress(&cinfo);
330
331         set_mem_src(&cinfo, (unsigned char *)buf, count);
332
333
334         jpeg_read_header(&cinfo, TRUE);
335         
336         if (lj->stereo)
337                 {
338                 jpeg_create_decompress(&cinfo2);
339                 set_mem_src(&cinfo2, stereo_buf2, stereo_length);
340                 jpeg_read_header(&cinfo2, TRUE);
341                 
342                 if (cinfo.image_width != cinfo2.image_width ||
343                     cinfo.image_height != cinfo2.image_height) 
344                         {
345                         DEBUG_1("stereo data with different size");
346                         jpeg_destroy_decompress(&cinfo2);
347                         lj->stereo = FALSE;
348                         }
349                 }
350
351                     
352
353         lj->requested_width = lj->stereo ? cinfo.image_width * 2: cinfo.image_width;
354         lj->requested_height = cinfo.image_height;
355         lj->size_cb(loader, lj->requested_width, lj->requested_height, lj->data);
356                         
357         cinfo.scale_num = 1;
358         for (cinfo.scale_denom = 2; cinfo.scale_denom <= 8; cinfo.scale_denom *= 2) {
359                 jpeg_calc_output_dimensions(&cinfo);
360                 if (cinfo.output_width < (lj->stereo ? lj->requested_width / 2 : lj->requested_width) || cinfo.output_height < lj->requested_height) {
361                         cinfo.scale_denom /= 2;
362                         break;
363                 }
364         }
365         jpeg_calc_output_dimensions(&cinfo);
366         if (lj->stereo)
367                 {
368                 cinfo2.scale_num = cinfo.scale_num;
369                 cinfo2.scale_denom = cinfo.scale_denom;
370                 jpeg_calc_output_dimensions(&cinfo2);
371                 jpeg_start_decompress(&cinfo2);
372                 }
373                 
374
375         jpeg_start_decompress(&cinfo);
376         
377
378         if (lj->stereo)
379                 {
380                 if (cinfo.output_width != cinfo2.output_width ||
381                     cinfo.output_height != cinfo2.output_height ||
382                     cinfo.out_color_components != cinfo2.out_color_components) 
383                         {
384                         DEBUG_1("stereo data with different output size");
385                         jpeg_destroy_decompress(&cinfo2);
386                         lj->stereo = FALSE;
387                         }
388                 }
389         
390         
391         lj->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, 
392                                      cinfo.out_color_components == 4 ? TRUE : FALSE, 
393                                      8, lj->stereo ? cinfo.output_width * 2: cinfo.output_width, cinfo.output_height);
394
395         if (!lj->pixbuf) 
396                 {
397                 jpeg_destroy_decompress (&cinfo);
398                 if (lj->stereo) jpeg_destroy_decompress (&cinfo2);
399                 return 0;
400                 }
401         if (lj->stereo) g_object_set_data(G_OBJECT(lj->pixbuf), "stereo_data", GINT_TO_POINTER(STEREO_PIXBUF_CROSS));
402         lj->area_prepared_cb(loader, lj->data);
403
404         rowstride = gdk_pixbuf_get_rowstride(lj->pixbuf);
405         dptr = gdk_pixbuf_get_pixels(lj->pixbuf);
406         dptr2 = gdk_pixbuf_get_pixels(lj->pixbuf) + ((cinfo.out_color_components == 4) ? 4 * cinfo.output_width : 3 * cinfo.output_width);
407         
408
409         while (cinfo.output_scanline < cinfo.output_height && !lj->abort) 
410                 {
411                 guint scanline = cinfo.output_scanline;
412                 image_loader_jpeg_read_scanline(&cinfo, &dptr, rowstride);
413                 lj->area_updated_cb(loader, 0, scanline, cinfo.output_width, cinfo.rec_outbuf_height, lj->data);
414                 if (lj->stereo)
415                         {
416                         guint scanline = cinfo2.output_scanline;
417                         image_loader_jpeg_read_scanline(&cinfo2, &dptr2, rowstride);
418                         lj->area_updated_cb(loader, cinfo.output_width, scanline, cinfo2.output_width, cinfo2.rec_outbuf_height, lj->data);
419                         }
420                 }
421
422         jpeg_finish_decompress(&cinfo);
423         jpeg_destroy_decompress(&cinfo);
424         if (lj->stereo)
425                 {
426                 jpeg_finish_decompress(&cinfo);
427                 jpeg_destroy_decompress(&cinfo);
428                 }
429
430         return TRUE;
431 }
432
433 static void image_loader_jpeg_set_size(gpointer loader, int width, int height)
434 {
435         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
436         lj->requested_width = width;
437         lj->requested_height = height;
438 }
439
440 static GdkPixbuf* image_loader_jpeg_get_pixbuf(gpointer loader)
441 {
442         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
443         return lj->pixbuf;
444 }
445
446 static gchar* image_loader_jpeg_get_format_name(gpointer loader)
447 {
448         return g_strdup("jpeg");
449 }
450 static gchar** image_loader_jpeg_get_format_mime_types(gpointer loader)
451 {
452         static gchar *mime[] = {"image/jpeg", NULL};
453         return g_strdupv(mime);
454 }
455
456 static gboolean image_loader_jpeg_close(gpointer loader, GError **error)
457 {
458         return TRUE;
459 }
460
461 static void image_loader_jpeg_abort(gpointer loader)
462 {
463         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
464         lj->abort = TRUE;
465 }
466
467 static void image_loader_jpeg_free(gpointer loader)
468 {
469         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
470         if (lj->pixbuf) g_object_unref(lj->pixbuf);
471         g_free(lj);
472 }
473
474
475 void image_loader_backend_set_jpeg(ImageLoaderBackend *funcs)
476 {
477         funcs->loader_new = image_loader_jpeg_new;
478         funcs->set_size = image_loader_jpeg_set_size;
479         funcs->load = image_loader_jpeg_load;
480         funcs->write = NULL;
481         funcs->get_pixbuf = image_loader_jpeg_get_pixbuf;
482         funcs->close = image_loader_jpeg_close;
483         funcs->abort = image_loader_jpeg_abort;
484         funcs->free = image_loader_jpeg_free;
485         
486         funcs->get_format_name = image_loader_jpeg_get_format_name;
487         funcs->get_format_mime_types = image_loader_jpeg_get_format_mime_types;
488 }
489
490
491