clang-tidy: bugprone-macro-parentheses
[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 "main.h"
31
32 #include "image-load.h"
33 #include "image-load-jpeg.h"
34 #include "jpeg-parser.h"
35
36 #ifdef HAVE_JPEG
37
38 #include <csetjmp>
39 #include <jerror.h>
40 #include <jpeglib.h>
41
42 struct ImageLoaderJpeg {
43         ImageLoaderBackendCbAreaUpdated area_updated_cb;
44         ImageLoaderBackendCbSize size_cb;
45         ImageLoaderBackendCbAreaPrepared area_prepared_cb;
46
47         gpointer data;
48
49         GdkPixbuf *pixbuf;
50         guint requested_width;
51         guint requested_height;
52
53         gboolean abort;
54         gboolean stereo;
55
56 };
57
58 /* error handler data */
59 struct error_handler_data {
60         struct jpeg_error_mgr pub;
61         sigjmp_buf setjmp_buffer;
62         GError **error;
63 };
64
65 /* explode gray image data from jpeg library into rgb components in pixbuf */
66 static void
67 explode_gray_into_buf (struct jpeg_decompress_struct *cinfo,
68                        guchar **lines)
69 {
70         gint i, j;
71         guint w;
72
73         g_return_if_fail (cinfo != nullptr);
74         g_return_if_fail (cinfo->output_components == 1);
75         g_return_if_fail (cinfo->out_color_space == JCS_GRAYSCALE);
76
77         /* Expand grey->colour.  Expand from the end of the
78          * memory down, so we can use the same buffer.
79          */
80         w = cinfo->output_width;
81         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
82                 guchar *from, *to;
83
84                 from = lines[i] + w - 1;
85                 to = lines[i] + (w - 1) * 3;
86                 for (j = w - 1; j >= 0; j--) {
87                         to[0] = from[0];
88                         to[1] = from[0];
89                         to[2] = from[0];
90                         to -= 3;
91                         from--;
92                 }
93         }
94 }
95
96
97 static void
98 convert_cmyk_to_rgb (struct jpeg_decompress_struct *cinfo,
99                      guchar **lines)
100 {
101         gint i;
102         guint j;
103
104         g_return_if_fail (cinfo != nullptr);
105         g_return_if_fail (cinfo->output_components == 4);
106         g_return_if_fail (cinfo->out_color_space == JCS_CMYK);
107
108         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
109                 guchar *p;
110
111                 p = lines[i];
112                 for (j = 0; j < cinfo->output_width; j++) {
113                         int c, m, y, k;
114                         c = p[0];
115                         m = p[1];
116                         y = p[2];
117                         k = p[3];
118                         if (cinfo->saw_Adobe_marker) {
119                                 p[0] = k*c / 255;
120                                 p[1] = k*m / 255;
121                                 p[2] = k*y / 255;
122                         }
123                         else {
124                                 p[0] = (255 - k)*(255 - c) / 255;
125                                 p[1] = (255 - k)*(255 - m) / 255;
126                                 p[2] = (255 - k)*(255 - y) / 255;
127                         }
128                         p[3] = 255;
129                         p += 4;
130                 }
131         }
132 }
133
134
135 static gpointer image_loader_jpeg_new(ImageLoaderBackendCbAreaUpdated area_updated_cb, ImageLoaderBackendCbSize size_cb, ImageLoaderBackendCbAreaPrepared area_prepared_cb, gpointer data)
136 {
137         auto loader = g_new0(ImageLoaderJpeg, 1);
138
139         loader->area_updated_cb = area_updated_cb;
140         loader->size_cb = size_cb;
141         loader->area_prepared_cb = area_prepared_cb;
142         loader->data = data;
143         return loader;
144 }
145
146 static void
147 fatal_error_handler (j_common_ptr cinfo)
148 {
149         struct error_handler_data *errmgr;
150         char buffer[JMSG_LENGTH_MAX];
151
152         errmgr = reinterpret_cast<struct error_handler_data *>(cinfo->err);
153
154         /* Create the message */
155         (* cinfo->err->format_message) (cinfo, buffer);
156
157         /* broken check for *error == NULL for robustness against
158          * crappy JPEG library
159          */
160         if (errmgr->error && *errmgr->error == nullptr) {
161                 g_set_error (errmgr->error,
162                              GDK_PIXBUF_ERROR,
163                              cinfo->err->msg_code == JERR_OUT_OF_MEMORY
164                              ? GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY
165                              : GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
166                              _("Error interpreting JPEG image file (%s)"),
167                              buffer);
168         }
169
170         siglongjmp (errmgr->setjmp_buffer, 1);
171
172         g_assert_not_reached ();
173 }
174
175 static void
176 output_message_handler (j_common_ptr)
177 {
178   /* This method keeps libjpeg from dumping crap to stderr */
179
180   /* do nothing */
181 }
182
183
184 void image_loader_jpeg_read_scanline(struct jpeg_decompress_struct *cinfo, guchar **dptr, guint rowstride)
185 {
186         guchar *lines[4];
187         guchar **lptr;
188         gint i;
189
190         lptr = lines;
191         for (i = 0; i < cinfo->rec_outbuf_height; i++)
192                 {
193                 *lptr++ = *dptr;
194                 *dptr += rowstride;
195                 }
196
197         jpeg_read_scanlines (cinfo, lines, cinfo->rec_outbuf_height);
198
199         switch (cinfo->out_color_space)
200                 {
201                     case JCS_GRAYSCALE:
202                       explode_gray_into_buf (cinfo, lines);
203                       break;
204                     case JCS_RGB:
205                       /* do nothing */
206                       break;
207                     case JCS_CMYK:
208                       convert_cmyk_to_rgb (cinfo, lines);
209                       break;
210                     default:
211                       break;
212                 }
213 }
214
215
216 static void init_source (j_decompress_ptr) {}
217 static boolean fill_input_buffer (j_decompress_ptr cinfo)
218 {
219         ERREXIT(cinfo, JERR_INPUT_EMPTY);
220         return TRUE;
221 }
222 static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
223 {
224         auto src = static_cast<struct jpeg_source_mgr*>(cinfo->src);
225
226         if (static_cast<gulong>(num_bytes) > src->bytes_in_buffer)
227                 {
228                 ERREXIT(cinfo, JERR_INPUT_EOF);
229                 }
230         else if (num_bytes > 0)
231                 {
232                 src->next_input_byte += static_cast<size_t>(num_bytes);
233                 src->bytes_in_buffer -= static_cast<size_t>(num_bytes);
234                 }
235 }
236 static void term_source (j_decompress_ptr) {}
237 static void set_mem_src (j_decompress_ptr cinfo, void* buffer, long nbytes)
238 {
239         struct jpeg_source_mgr* src;
240
241         if (cinfo->src == nullptr)
242                 {   /* first time for this JPEG object? */
243                 cinfo->src = static_cast<struct jpeg_source_mgr *>((*cinfo->mem->alloc_small) (
244                                         reinterpret_cast<j_common_ptr>(cinfo), JPOOL_PERMANENT,
245                                         sizeof(struct jpeg_source_mgr)));
246                 }
247
248         src = static_cast<struct jpeg_source_mgr*>(cinfo->src);
249         src->init_source = init_source;
250         src->fill_input_buffer = fill_input_buffer;
251         src->skip_input_data = skip_input_data;
252         src->resync_to_restart = jpeg_resync_to_restart; /* use default method */
253         src->term_source = term_source;
254         src->bytes_in_buffer = nbytes;
255         src->next_input_byte = static_cast<JOCTET*>(buffer);
256 }
257
258
259 static gboolean image_loader_jpeg_load (gpointer loader, const guchar *buf, gsize count, GError **error)
260 {
261         auto lj = static_cast<ImageLoaderJpeg *>(loader);
262         struct jpeg_decompress_struct cinfo;
263         struct jpeg_decompress_struct cinfo2;
264         guchar *dptr, *dptr2;
265         guint rowstride;
266         guchar *stereo_buf2 = nullptr;
267         guint stereo_length = 0;
268
269         struct error_handler_data jerr;
270
271         lj->stereo = FALSE;
272
273         MPOData *mpo = jpeg_get_mpo_data(buf, count);
274         if (mpo && mpo->num_images > 1)
275                 {
276                 guint i;
277                 gint idx1 = -1, idx2 = -1;
278                 guint num2 = 1;
279
280                 for (i = 0; i < mpo->num_images; i++)
281                         {
282                         if (mpo->images[i].type_code == 0x20002)
283                                 {
284                                 if (mpo->images[i].MPIndividualNum == 1)
285                                         {
286                                         idx1 = i;
287                                         }
288                                 else if (mpo->images[i].MPIndividualNum > num2)
289                                         {
290                                         idx2 = i;
291                                         num2 = mpo->images[i].MPIndividualNum;
292                                         }
293                                 }
294                         }
295
296                 if (idx1 >= 0 && idx2 >= 0)
297                         {
298                         lj->stereo = TRUE;
299                         stereo_buf2 = const_cast<unsigned char *>(buf) + mpo->images[idx2].offset;
300                         stereo_length = mpo->images[idx2].length;
301                         buf = const_cast<unsigned char *>(buf) + mpo->images[idx1].offset;
302                         count = mpo->images[idx1].length;
303                         }
304                 }
305         jpeg_mpo_data_free(mpo);
306
307         /* setup error handler */
308         cinfo.err = jpeg_std_error (&jerr.pub);
309         if (lj->stereo) cinfo2.err = jpeg_std_error (&jerr.pub);
310         jerr.pub.error_exit = fatal_error_handler;
311         jerr.pub.output_message = output_message_handler;
312
313         jerr.error = error;
314
315
316         if (sigsetjmp(jerr.setjmp_buffer, 0))
317                 {
318                 /* If we get here, the JPEG code has signaled an error.
319                  * We need to clean up the JPEG object, close the input file, and return.
320                 */
321                 jpeg_destroy_decompress(&cinfo);
322                 if (lj->stereo) jpeg_destroy_decompress(&cinfo2);
323                 return FALSE;
324                 }
325
326         jpeg_create_decompress(&cinfo);
327
328         set_mem_src(&cinfo, const_cast<unsigned char *>(buf), count);
329
330
331         jpeg_read_header(&cinfo, TRUE);
332
333         if (lj->stereo)
334                 {
335                 jpeg_create_decompress(&cinfo2);
336                 set_mem_src(&cinfo2, stereo_buf2, stereo_length);
337                 jpeg_read_header(&cinfo2, TRUE);
338
339                 if (cinfo.image_width != cinfo2.image_width ||
340                     cinfo.image_height != cinfo2.image_height)
341                         {
342                         DEBUG_1("stereo data with different size");
343                         jpeg_destroy_decompress(&cinfo2);
344                         lj->stereo = FALSE;
345                         }
346                 }
347
348
349
350         lj->requested_width = lj->stereo ? cinfo.image_width * 2: cinfo.image_width;
351         lj->requested_height = cinfo.image_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         auto lj = static_cast<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         auto lj = static_cast<ImageLoaderJpeg *>(loader);
440         return lj->pixbuf;
441 }
442
443 static gchar* image_loader_jpeg_get_format_name(gpointer)
444 {
445         return g_strdup("jpeg");
446 }
447 static gchar** image_loader_jpeg_get_format_mime_types(gpointer)
448 {
449         static const gchar *mime[] = {"image/jpeg", nullptr};
450         return g_strdupv(const_cast<gchar **>(mime));
451 }
452
453 static gboolean image_loader_jpeg_close(gpointer, GError **)
454 {
455         return TRUE;
456 }
457
458 static void image_loader_jpeg_abort(gpointer loader)
459 {
460         auto lj = static_cast<ImageLoaderJpeg *>(loader);
461         lj->abort = TRUE;
462 }
463
464 static void image_loader_jpeg_free(gpointer loader)
465 {
466         auto lj = static_cast<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 = nullptr;
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: */