Simplify vflist_get_formatted()
[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;
100         guint j;
101
102         g_return_if_fail (cinfo != NULL);
103         g_return_if_fail (cinfo->output_components == 4);
104         g_return_if_fail (cinfo->out_color_space == JCS_CMYK);
105
106         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
107                 guchar *p;
108
109                 p = lines[i];
110                 for (j = 0; j < cinfo->output_width; j++) {
111                         int c, m, y, k;
112                         c = p[0];
113                         m = p[1];
114                         y = p[2];
115                         k = p[3];
116                         if (cinfo->saw_Adobe_marker) {
117                                 p[0] = k*c / 255;
118                                 p[1] = k*m / 255;
119                                 p[2] = k*y / 255;
120                         }
121                         else {
122                                 p[0] = (255 - k)*(255 - c) / 255;
123                                 p[1] = (255 - k)*(255 - m) / 255;
124                                 p[2] = (255 - k)*(255 - y) / 255;
125                         }
126                         p[3] = 255;
127                         p += 4;
128                 }
129         }
130 }
131
132
133 static gpointer image_loader_jpeg_new(ImageLoaderBackendCbAreaUpdated area_updated_cb, ImageLoaderBackendCbSize size_cb, ImageLoaderBackendCbAreaPrepared area_prepared_cb, gpointer data)
134 {
135         ImageLoaderJpeg *loader = g_new0(ImageLoaderJpeg, 1);
136
137         loader->area_updated_cb = area_updated_cb;
138         loader->size_cb = size_cb;
139         loader->area_prepared_cb = area_prepared_cb;
140         loader->data = data;
141         return (gpointer) loader;
142 }
143
144 static void
145 fatal_error_handler (j_common_ptr cinfo)
146 {
147         struct error_handler_data *errmgr;
148         char buffer[JMSG_LENGTH_MAX];
149
150         errmgr = (struct error_handler_data *) cinfo->err;
151
152         /* Create the message */
153         (* cinfo->err->format_message) (cinfo, buffer);
154
155         /* broken check for *error == NULL for robustness against
156          * crappy JPEG library
157          */
158         if (errmgr->error && *errmgr->error == NULL) {
159                 g_set_error (errmgr->error,
160                              GDK_PIXBUF_ERROR,
161                              cinfo->err->msg_code == JERR_OUT_OF_MEMORY
162                              ? GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY
163                              : GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
164                              _("Error interpreting JPEG image file (%s)"),
165                              buffer);
166         }
167
168         siglongjmp (errmgr->setjmp_buffer, 1);
169
170         g_assert_not_reached ();
171 }
172
173 static void
174 output_message_handler (j_common_ptr cinfo)
175 {
176   /* This method keeps libjpeg from dumping crap to stderr */
177
178   /* do nothing */
179 }
180
181
182 void image_loader_jpeg_read_scanline(struct jpeg_decompress_struct *cinfo, guchar **dptr, guint rowstride)
183 {
184         guchar *lines[4];
185         guchar **lptr;
186         gint i;
187
188         lptr = lines;
189         for (i = 0; i < cinfo->rec_outbuf_height; i++)
190                 {
191                 *lptr++ = *dptr;
192                 *dptr += rowstride;
193                 }
194
195         jpeg_read_scanlines (cinfo, lines, cinfo->rec_outbuf_height);
196
197         switch (cinfo->out_color_space)
198                 {
199                     case JCS_GRAYSCALE:
200                       explode_gray_into_buf (cinfo, lines);
201                       break;
202                     case JCS_RGB:
203                       /* do nothing */
204                       break;
205                     case JCS_CMYK:
206                       convert_cmyk_to_rgb (cinfo, lines);
207                       break;
208                     default:
209                       break;
210                 }
211 }
212
213
214 static void init_source (j_decompress_ptr cinfo) {}
215 static boolean fill_input_buffer (j_decompress_ptr cinfo)
216 {
217         ERREXIT(cinfo, JERR_INPUT_EMPTY);
218         return TRUE;
219 }
220 static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
221 {
222         struct jpeg_source_mgr* src = (struct jpeg_source_mgr*) cinfo->src;
223
224         if ((gulong)num_bytes > src->bytes_in_buffer)
225                 {
226                 ERREXIT(cinfo, JERR_INPUT_EOF);
227                 }
228         else if (num_bytes > 0)
229                 {
230                 src->next_input_byte += (size_t) num_bytes;
231                 src->bytes_in_buffer -= (size_t) num_bytes;
232                 }
233 }
234 static void term_source (j_decompress_ptr cinfo) {}
235 static void set_mem_src (j_decompress_ptr cinfo, void* buffer, long nbytes)
236 {
237         struct jpeg_source_mgr* src;
238
239         if (cinfo->src == NULL)
240                 {   /* first time for this JPEG object? */
241                 cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) (
242                                         (j_common_ptr) cinfo, JPOOL_PERMANENT,
243                                         sizeof(struct jpeg_source_mgr));
244                 }
245
246         src = (struct jpeg_source_mgr*) cinfo->src;
247         src->init_source = init_source;
248         src->fill_input_buffer = fill_input_buffer;
249         src->skip_input_data = skip_input_data;
250         src->resync_to_restart = jpeg_resync_to_restart; /* use default method */
251         src->term_source = term_source;
252         src->bytes_in_buffer = nbytes;
253         src->next_input_byte = (JOCTET*)buffer;
254 }
255
256
257 static gboolean image_loader_jpeg_load (gpointer loader, const guchar *buf, gsize count, GError **error)
258 {
259         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
260         struct jpeg_decompress_struct cinfo;
261         struct jpeg_decompress_struct cinfo2;
262         guchar *dptr, *dptr2;
263         guint rowstride;
264         guchar *stereo_buf2 = NULL;
265         guint stereo_length = 0;
266
267         struct error_handler_data jerr;
268
269         lj->stereo = FALSE;
270 //      DEBUG_1("TG: JPG requested size w=%d:h=%d", lj->requested_width > 0, lj->requested_height);
271
272         MPOData *mpo = jpeg_get_mpo_data(buf, count);
273         if (mpo && mpo->num_images > 1)
274                 {
275                 guint i;
276                 gint idx1 = -1, idx2 = -1;
277                 guint num2 = 1;
278
279                 for (i = 0; i < mpo->num_images; i++)
280                         {
281                         if (mpo->images[i].type_code == 0x20002)
282                                 {
283                                 if (mpo->images[i].MPIndividualNum == 1)
284                                         {
285                                         idx1 = i;
286                                         }
287                                 else if (mpo->images[i].MPIndividualNum > num2)
288                                         {
289                                         idx2 = i;
290                                         num2 = mpo->images[i].MPIndividualNum;
291                                         }
292                                 }
293                         }
294
295                 if (idx1 >= 0 && idx2 >= 0)
296                         {
297                         lj->stereo = TRUE;
298                         stereo_buf2 = (unsigned char *)buf + mpo->images[idx2].offset;
299                         stereo_length = mpo->images[idx2].length;
300                         buf = (unsigned char *)buf + mpo->images[idx1].offset;
301                         count = mpo->images[idx1].length;
302                         }
303                 }
304         jpeg_mpo_data_free(mpo);
305
306         /* setup error handler */
307         cinfo.err = jpeg_std_error (&jerr.pub);
308         if (lj->stereo) cinfo2.err = jpeg_std_error (&jerr.pub);
309         jerr.pub.error_exit = fatal_error_handler;
310         jerr.pub.output_message = output_message_handler;
311
312         jerr.error = error;
313
314
315         if (setjmp(jerr.setjmp_buffer))
316                 {
317                 /* If we get here, the JPEG code has signaled an error.
318                  * We need to clean up the JPEG object, close the input file, and return.
319                 */
320                 jpeg_destroy_decompress(&cinfo);
321                 if (lj->stereo) jpeg_destroy_decompress(&cinfo2);
322                 return FALSE;
323                 }
324
325         jpeg_create_decompress(&cinfo);
326
327         set_mem_src(&cinfo, (unsigned char *)buf, count);
328
329
330         jpeg_read_header(&cinfo, TRUE);
331
332         if (lj->stereo)
333                 {
334                 jpeg_create_decompress(&cinfo2);
335                 set_mem_src(&cinfo2, stereo_buf2, stereo_length);
336                 jpeg_read_header(&cinfo2, TRUE);
337
338                 if (cinfo.image_width != cinfo2.image_width ||
339                     cinfo.image_height != cinfo2.image_height)
340                         {
341                         DEBUG_1("stereo data with different size");
342                         jpeg_destroy_decompress(&cinfo2);
343                         lj->stereo = FALSE;
344                         }
345                 }
346
347
348
349         lj->requested_width = lj->stereo ? cinfo.image_width * 2: cinfo.image_width;
350         lj->requested_height = cinfo.image_height;
351 //      DEBUG_1("TG: JPG requested size v2 w=%d:h=%d", lj->requested_width > 0, lj->requested_height);
352         lj->size_cb(loader, lj->requested_width, lj->requested_height, lj->data);
353
354         cinfo.scale_num = 1;
355         for (cinfo.scale_denom = 2; cinfo.scale_denom <= 8; cinfo.scale_denom *= 2) {
356                 jpeg_calc_output_dimensions(&cinfo);
357                 if (cinfo.output_width < (lj->stereo ? lj->requested_width / 2 : lj->requested_width) || cinfo.output_height < lj->requested_height) {
358                         cinfo.scale_denom /= 2;
359                         break;
360                 }
361         }
362         jpeg_calc_output_dimensions(&cinfo);
363         if (lj->stereo)
364                 {
365                 cinfo2.scale_num = cinfo.scale_num;
366                 cinfo2.scale_denom = cinfo.scale_denom;
367                 jpeg_calc_output_dimensions(&cinfo2);
368                 jpeg_start_decompress(&cinfo2);
369                 }
370
371
372         jpeg_start_decompress(&cinfo);
373
374
375         if (lj->stereo)
376                 {
377                 if (cinfo.output_width != cinfo2.output_width ||
378                     cinfo.output_height != cinfo2.output_height ||
379                     cinfo.out_color_components != cinfo2.out_color_components)
380                         {
381                         DEBUG_1("stereo data with different output size");
382                         jpeg_destroy_decompress(&cinfo2);
383                         lj->stereo = FALSE;
384                         }
385                 }
386
387
388         lj->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
389                                      cinfo.out_color_components == 4 ? TRUE : FALSE,
390                                      8, lj->stereo ? cinfo.output_width * 2: cinfo.output_width, cinfo.output_height);
391
392         if (!lj->pixbuf)
393                 {
394                 jpeg_destroy_decompress (&cinfo);
395                 if (lj->stereo) jpeg_destroy_decompress (&cinfo2);
396                 return 0;
397                 }
398         if (lj->stereo) g_object_set_data(G_OBJECT(lj->pixbuf), "stereo_data", GINT_TO_POINTER(STEREO_PIXBUF_CROSS));
399         lj->area_prepared_cb(loader, lj->data);
400
401         rowstride = gdk_pixbuf_get_rowstride(lj->pixbuf);
402         dptr = gdk_pixbuf_get_pixels(lj->pixbuf);
403         dptr2 = gdk_pixbuf_get_pixels(lj->pixbuf) + ((cinfo.out_color_components == 4) ? 4 * cinfo.output_width : 3 * cinfo.output_width);
404
405
406         while (cinfo.output_scanline < cinfo.output_height && !lj->abort)
407                 {
408                 guint scanline = cinfo.output_scanline;
409                 image_loader_jpeg_read_scanline(&cinfo, &dptr, rowstride);
410                 lj->area_updated_cb(loader, 0, scanline, cinfo.output_width, cinfo.rec_outbuf_height, lj->data);
411                 if (lj->stereo)
412                         {
413                         guint scanline = cinfo2.output_scanline;
414                         image_loader_jpeg_read_scanline(&cinfo2, &dptr2, rowstride);
415                         lj->area_updated_cb(loader, cinfo.output_width, scanline, cinfo2.output_width, cinfo2.rec_outbuf_height, lj->data);
416                         }
417                 }
418
419         jpeg_finish_decompress(&cinfo);
420         jpeg_destroy_decompress(&cinfo);
421         if (lj->stereo)
422                 {
423                 jpeg_finish_decompress(&cinfo);
424                 jpeg_destroy_decompress(&cinfo);
425                 }
426
427         return TRUE;
428 }
429
430 static void image_loader_jpeg_set_size(gpointer loader, int width, int height)
431 {
432         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
433         lj->requested_width = width;
434         lj->requested_height = height;
435 }
436
437 static GdkPixbuf* image_loader_jpeg_get_pixbuf(gpointer loader)
438 {
439         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
440         return lj->pixbuf;
441 }
442
443 static gchar* image_loader_jpeg_get_format_name(gpointer loader)
444 {
445         return g_strdup("jpeg");
446 }
447 static gchar** image_loader_jpeg_get_format_mime_types(gpointer loader)
448 {
449         static gchar *mime[] = {"image/jpeg", NULL};
450         return g_strdupv(mime);
451 }
452
453 static gboolean image_loader_jpeg_close(gpointer loader, GError **error)
454 {
455         return TRUE;
456 }
457
458 static void image_loader_jpeg_abort(gpointer loader)
459 {
460         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
461         lj->abort = TRUE;
462 }
463
464 static void image_loader_jpeg_free(gpointer loader)
465 {
466         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
467         if (lj->pixbuf) g_object_unref(lj->pixbuf);
468         g_free(lj);
469 }
470
471
472 void image_loader_backend_set_jpeg(ImageLoaderBackend *funcs)
473 {
474         funcs->loader_new = image_loader_jpeg_new;
475         funcs->set_size = image_loader_jpeg_set_size;
476         funcs->load = image_loader_jpeg_load;
477         funcs->write = NULL;
478         funcs->get_pixbuf = image_loader_jpeg_get_pixbuf;
479         funcs->close = image_loader_jpeg_close;
480         funcs->abort = image_loader_jpeg_abort;
481         funcs->free = image_loader_jpeg_free;
482
483         funcs->get_format_name = image_loader_jpeg_get_format_name;
484         funcs->get_format_mime_types = image_loader_jpeg_get_format_mime_types;
485 }
486
487
488
489 #endif
490
491
492 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */