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