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