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