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