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