7d5e4d0dd5c1efb605b49359a9461ef3135d5ad1
[geeqie.git] / src / image-load-cr3.cc
1 /*
2  * Copyright (C) 2020 The Geeqie Team
3  *
4  * Authors: Colin Clark
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 /** This is a Will Not Fix */
22 #pragma GCC diagnostic ignored "-Wclobbered"
23
24 /** @FIXME This is just a copy of image-load-jpeg.cc, with an adjusted
25  * start address for a .cr3 file
26  */
27 #include "main.h"
28
29 #include "image-load.h"
30 #include "image-load-cr3.h"
31 #include "jpeg-parser.h"
32
33 #ifdef HAVE_JPEG
34
35 #include <csetjmp>
36 #include <jerror.h>
37 #include <jpeglib.h>
38
39 struct ImageLoaderJpeg {
40         ImageLoaderBackendCbAreaUpdated area_updated_cb;
41         ImageLoaderBackendCbSize size_cb;
42         ImageLoaderBackendCbAreaPrepared area_prepared_cb;
43
44         gpointer data;
45
46         GdkPixbuf *pixbuf;
47         guint requested_width;
48         guint requested_height;
49
50         gboolean abort;
51         gboolean stereo;
52
53 };
54
55 /* error handler data */
56 struct error_handler_data {
57         struct jpeg_error_mgr pub;
58         sigjmp_buf setjmp_buffer;
59         GError **error;
60 };
61
62 /* explode gray image data from jpeg library into rgb components in pixbuf */
63 static void
64 explode_gray_into_buf (struct jpeg_decompress_struct *cinfo,
65                        guchar **lines)
66 {
67         gint i;
68         gint j;
69         guint w;
70
71         g_return_if_fail (cinfo != nullptr);
72         g_return_if_fail (cinfo->output_components == 1);
73         g_return_if_fail (cinfo->out_color_space == JCS_GRAYSCALE);
74
75         /* Expand grey->colour.  Expand from the end of the
76          * memory down, so we can use the same buffer.
77          */
78         w = cinfo->output_width;
79         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
80                 guchar *from;
81                 guchar *to;
82
83                 from = lines[i] + w - 1;
84                 to = lines[i] + (w - 1) * 3;
85                 for (j = w - 1; j >= 0; j--) {
86                         to[0] = from[0];
87                         to[1] = from[0];
88                         to[2] = from[0];
89                         to -= 3;
90                         from--;
91                 }
92         }
93 }
94
95
96 static void
97 convert_cmyk_to_rgb (struct jpeg_decompress_struct *cinfo,
98                      guchar **lines)
99 {
100         gint i;
101         guint j;
102
103         g_return_if_fail (cinfo != nullptr);
104         g_return_if_fail (cinfo->output_components == 4);
105         g_return_if_fail (cinfo->out_color_space == JCS_CMYK);
106
107         for (i = cinfo->rec_outbuf_height - 1; i >= 0; i--) {
108                 guchar *p;
109
110                 p = lines[i];
111                 for (j = 0; j < cinfo->output_width; j++) {
112                         int c;
113                         int m;
114                         int y;
115                         int k;
116                         c = p[0];
117                         m = p[1];
118                         y = p[2];
119                         k = p[3];
120                         if (cinfo->saw_Adobe_marker) {
121                                 p[0] = k*c / 255;
122                                 p[1] = k*m / 255;
123                                 p[2] = k*y / 255;
124                         }
125                         else {
126                                 p[0] = (255 - k)*(255 - c) / 255;
127                                 p[1] = (255 - k)*(255 - m) / 255;
128                                 p[2] = (255 - k)*(255 - y) / 255;
129                         }
130                         p[3] = 255;
131                         p += 4;
132                 }
133         }
134 }
135
136
137 static gpointer image_loader_cr3_new(ImageLoaderBackendCbAreaUpdated area_updated_cb, ImageLoaderBackendCbSize size_cb, ImageLoaderBackendCbAreaPrepared area_prepared_cb, gpointer data)
138 {
139         auto loader = g_new0(ImageLoaderJpeg, 1);
140
141         loader->area_updated_cb = area_updated_cb;
142         loader->size_cb = size_cb;
143         loader->area_prepared_cb = area_prepared_cb;
144         loader->data = data;
145         return loader;
146 }
147
148 static void
149 fatal_error_handler (j_common_ptr cinfo)
150 {
151         struct error_handler_data *errmgr;
152         char buffer[JMSG_LENGTH_MAX];
153
154         errmgr = reinterpret_cast<struct error_handler_data *>(cinfo->err);
155
156         /* Create the message */
157         (* cinfo->err->format_message) (cinfo, buffer);
158
159         /* broken check for *error == NULL for robustness against
160          * crappy JPEG library
161          */
162         if (errmgr->error && *errmgr->error == nullptr) {
163                 g_set_error (errmgr->error,
164                              GDK_PIXBUF_ERROR,
165                              cinfo->err->msg_code == JERR_OUT_OF_MEMORY
166                              ? GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY
167                              : GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
168                              _("Error interpreting JPEG image file (%s)"),
169                              buffer);
170         }
171
172         siglongjmp (errmgr->setjmp_buffer, 1);
173
174         g_assert_not_reached ();
175 }
176
177 static void
178 output_message_handler (j_common_ptr)
179 {
180   /* This method keeps libjpeg from dumping crap to stderr */
181
182   /* do nothing */
183 }
184
185
186 static void image_loader_cr3_read_scanline(struct jpeg_decompress_struct *cinfo, guchar **dptr, guint rowstride)
187 {
188         guchar *lines[4];
189         guchar **lptr;
190         gint i;
191
192         lptr = lines;
193         for (i = 0; i < cinfo->rec_outbuf_height; i++)
194                 {
195                 *lptr++ = *dptr;
196                 *dptr += rowstride;
197                 }
198
199         jpeg_read_scanlines (cinfo, lines, cinfo->rec_outbuf_height);
200
201         switch (cinfo->out_color_space)
202                 {
203                     case JCS_GRAYSCALE:
204                       explode_gray_into_buf (cinfo, lines);
205                       break;
206                     case JCS_RGB:
207                       /* do nothing */
208                       break;
209                     case JCS_CMYK:
210                       convert_cmyk_to_rgb (cinfo, lines);
211                       break;
212                     default:
213                       break;
214                 }
215 }
216
217
218 static void init_source (j_decompress_ptr) {}
219 static boolean fill_input_buffer (j_decompress_ptr cinfo)
220 {
221         ERREXIT(cinfo, JERR_INPUT_EMPTY);
222         return TRUE;
223 }
224 static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
225 {
226         auto src = static_cast<struct jpeg_source_mgr*>(cinfo->src);
227
228         if (static_cast<gulong>(num_bytes) > src->bytes_in_buffer)
229                 {
230                 ERREXIT(cinfo, JERR_INPUT_EOF);
231                 }
232         else if (num_bytes > 0)
233                 {
234                 src->next_input_byte += static_cast<size_t>(num_bytes);
235                 src->bytes_in_buffer -= static_cast<size_t>(num_bytes);
236                 }
237 }
238 static void term_source (j_decompress_ptr) {}
239 static void set_mem_src (j_decompress_ptr cinfo, void* buffer, long nbytes)
240 {
241         struct jpeg_source_mgr* src;
242
243         if (cinfo->src == nullptr)
244                 {   /* first time for this JPEG object? */
245                 cinfo->src = static_cast<struct jpeg_source_mgr *>((*cinfo->mem->alloc_small) (
246                                         reinterpret_cast<j_common_ptr>(cinfo), JPOOL_PERMANENT,
247                                         sizeof(struct jpeg_source_mgr)));
248                 }
249
250         src = static_cast<struct jpeg_source_mgr*>(cinfo->src);
251         src->init_source = init_source;
252         src->fill_input_buffer = fill_input_buffer;
253         src->skip_input_data = skip_input_data;
254         src->resync_to_restart = jpeg_resync_to_restart; /* use default method */
255         src->term_source = term_source;
256         src->bytes_in_buffer = nbytes;
257         src->next_input_byte = static_cast<JOCTET*>(buffer);
258 }
259
260
261 static gboolean image_loader_cr3_load (gpointer loader, const guchar *buf, gsize count, GError **error)
262 {
263         auto lj = static_cast<ImageLoaderJpeg *>(loader);
264         struct jpeg_decompress_struct cinfo;
265         struct jpeg_decompress_struct cinfo2;
266         guchar *dptr;
267         guchar *dptr2;
268         guint rowstride;
269         guchar *stereo_buf2 = nullptr;
270         guint stereo_length = 0;
271
272         struct error_handler_data jerr;
273
274 /** @FIXME Just start search at where full size jpeg should be,
275  * / then search through the file looking for a jpeg end-marker
276  */
277         gboolean found = FALSE;
278         gint i;
279         guint n;
280
281         n = 0;
282         while (n < count - 4 && !found)
283                 {
284                 if (memcmp(&buf[n], "mdat", 4) == 0)
285                         {
286                         if (memcmp(&buf[n + 12], "\xFF\xD8", 2) == 0)
287                                 {
288                                 i = 0;
289                                 while (!found )
290                                         {
291                                         if (memcmp(&buf[n + 12 + i], "\xFF\xD9", 2) == 0)
292                                                 {
293                                                 found = TRUE;
294                                                 }
295                                         i++;
296                                         }
297                                 }
298                         else
299                                 {
300                                 break;
301                                 }
302                         }
303                 else
304                         {
305                         n++;
306                         }
307                 }
308
309         if (!found)
310                 {
311                 return FALSE;
312                 }
313
314         count = i;
315         buf = const_cast<unsigned char *>(buf) + n + 12;
316
317         lj->stereo = FALSE;
318
319         MPOData *mpo = jpeg_get_mpo_data(buf, count);
320         if (mpo && mpo->num_images > 1)
321                 {
322                 guint i;
323                 gint idx1 = -1;
324                 gint idx2 = -1;
325                 guint num2 = 1;
326
327                 for (i = 0; i < mpo->num_images; i++)
328                         {
329                         if (mpo->images[i].type_code == 0x20002)
330                                 {
331                                 if (mpo->images[i].MPIndividualNum == 1)
332                                         {
333                                         idx1 = i;
334                                         }
335                                 else if (mpo->images[i].MPIndividualNum > num2)
336                                         {
337                                         idx2 = i;
338                                         num2 = mpo->images[i].MPIndividualNum;
339                                         }
340                                 }
341                         }
342
343                 if (idx1 >= 0 && idx2 >= 0)
344                         {
345                         lj->stereo = TRUE;
346                         stereo_buf2 = const_cast<unsigned char *>(buf) + mpo->images[idx2].offset;
347                         stereo_length = mpo->images[idx2].length;
348                         buf = const_cast<unsigned char *>(buf) + mpo->images[idx1].offset;
349                         count = mpo->images[idx1].length;
350                         }
351                 }
352         jpeg_mpo_data_free(mpo);
353
354         /* setup error handler */
355         cinfo.err = jpeg_std_error (&jerr.pub);
356         if (lj->stereo) cinfo2.err = jpeg_std_error (&jerr.pub);
357         jerr.pub.error_exit = fatal_error_handler;
358         jerr.pub.output_message = output_message_handler;
359
360         jerr.error = error;
361
362
363         if (sigsetjmp(jerr.setjmp_buffer, 0))
364                 {
365                 /* If we get here, the JPEG code has signaled an error.
366                  * We need to clean up the JPEG object, close the input file, and return.
367                 */
368                 jpeg_destroy_decompress(&cinfo);
369                 if (lj->stereo) jpeg_destroy_decompress(&cinfo2);
370                 return FALSE;
371                 }
372
373         jpeg_create_decompress(&cinfo);
374
375         set_mem_src(&cinfo, const_cast<unsigned char *>(buf), count);
376
377
378         jpeg_read_header(&cinfo, TRUE);
379
380         if (lj->stereo)
381                 {
382                 jpeg_create_decompress(&cinfo2);
383                 set_mem_src(&cinfo2, stereo_buf2, stereo_length);
384                 jpeg_read_header(&cinfo2, TRUE);
385
386                 if (cinfo.image_width != cinfo2.image_width ||
387                     cinfo.image_height != cinfo2.image_height)
388                         {
389                         DEBUG_1("stereo data with different size");
390                         jpeg_destroy_decompress(&cinfo2);
391                         lj->stereo = FALSE;
392                         }
393                 }
394
395
396
397         lj->requested_width = lj->stereo ? cinfo.image_width * 2: cinfo.image_width;
398         lj->requested_height = cinfo.image_height;
399         lj->size_cb(loader, lj->requested_width, lj->requested_height, lj->data);
400
401         cinfo.scale_num = 1;
402         for (cinfo.scale_denom = 2; cinfo.scale_denom <= 8; cinfo.scale_denom *= 2) {
403                 jpeg_calc_output_dimensions(&cinfo);
404                 if (cinfo.output_width < (lj->stereo ? lj->requested_width / 2 : lj->requested_width) || cinfo.output_height < lj->requested_height) {
405                         cinfo.scale_denom /= 2;
406                         break;
407                 }
408         }
409         jpeg_calc_output_dimensions(&cinfo);
410         if (lj->stereo)
411                 {
412                 cinfo2.scale_num = cinfo.scale_num;
413                 cinfo2.scale_denom = cinfo.scale_denom;
414                 jpeg_calc_output_dimensions(&cinfo2);
415                 jpeg_start_decompress(&cinfo2);
416                 }
417
418
419         jpeg_start_decompress(&cinfo);
420
421
422         if (lj->stereo)
423                 {
424                 if (cinfo.output_width != cinfo2.output_width ||
425                     cinfo.output_height != cinfo2.output_height ||
426                     cinfo.out_color_components != cinfo2.out_color_components)
427                         {
428                         DEBUG_1("stereo data with different output size");
429                         jpeg_destroy_decompress(&cinfo2);
430                         lj->stereo = FALSE;
431                         }
432                 }
433
434
435         lj->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
436                                      cinfo.out_color_components == 4 ? TRUE : FALSE,
437                                      8, lj->stereo ? cinfo.output_width * 2: cinfo.output_width, cinfo.output_height);
438
439         if (!lj->pixbuf)
440                 {
441                 jpeg_destroy_decompress (&cinfo);
442                 if (lj->stereo) jpeg_destroy_decompress (&cinfo2);
443                 return 0;
444                 }
445         if (lj->stereo) g_object_set_data(G_OBJECT(lj->pixbuf), "stereo_data", GINT_TO_POINTER(STEREO_PIXBUF_CROSS));
446         lj->area_prepared_cb(loader, lj->data);
447
448         rowstride = gdk_pixbuf_get_rowstride(lj->pixbuf);
449         dptr = gdk_pixbuf_get_pixels(lj->pixbuf);
450         dptr2 = gdk_pixbuf_get_pixels(lj->pixbuf) + ((cinfo.out_color_components == 4) ? 4 * cinfo.output_width : 3 * cinfo.output_width);
451
452
453         while (cinfo.output_scanline < cinfo.output_height && !lj->abort)
454                 {
455                 guint scanline = cinfo.output_scanline;
456                 image_loader_cr3_read_scanline(&cinfo, &dptr, rowstride);
457                 lj->area_updated_cb(loader, 0, scanline, cinfo.output_width, cinfo.rec_outbuf_height, lj->data);
458                 if (lj->stereo)
459                         {
460                         guint scanline = cinfo2.output_scanline;
461                         image_loader_cr3_read_scanline(&cinfo2, &dptr2, rowstride);
462                         lj->area_updated_cb(loader, cinfo.output_width, scanline, cinfo2.output_width, cinfo2.rec_outbuf_height, lj->data);
463                         }
464                 }
465
466         jpeg_finish_decompress(&cinfo);
467         jpeg_destroy_decompress(&cinfo);
468         if (lj->stereo)
469                 {
470                 jpeg_finish_decompress(&cinfo);
471                 jpeg_destroy_decompress(&cinfo);
472                 }
473
474         return TRUE;
475 }
476
477 static void image_loader_cr3_set_size(gpointer loader, int width, int height)
478 {
479         auto lj = static_cast<ImageLoaderJpeg *>(loader);
480         lj->requested_width = width;
481         lj->requested_height = height;
482 }
483
484 static GdkPixbuf* image_loader_cr3_get_pixbuf(gpointer loader)
485 {
486         auto lj = static_cast<ImageLoaderJpeg *>(loader);
487         return lj->pixbuf;
488 }
489
490 static gchar* image_loader_cr3_get_format_name(gpointer)
491 {
492         return g_strdup("cr3");
493 }
494 static gchar** image_loader_cr3_get_format_mime_types(gpointer)
495 {
496         static const gchar *mime[] = {"image/x-canon-cr3", nullptr};
497         return g_strdupv(const_cast<gchar **>(mime));
498 }
499
500 static gboolean image_loader_cr3_close(gpointer, GError **)
501 {
502         return TRUE;
503 }
504
505 static void image_loader_cr3_abort(gpointer loader)
506 {
507         auto lj = static_cast<ImageLoaderJpeg *>(loader);
508         lj->abort = TRUE;
509 }
510
511 static void image_loader_cr3_free(gpointer loader)
512 {
513         auto lj = static_cast<ImageLoaderJpeg *>(loader);
514         if (lj->pixbuf) g_object_unref(lj->pixbuf);
515         g_free(lj);
516 }
517
518
519 void image_loader_backend_set_cr3(ImageLoaderBackend *funcs)
520 {
521         funcs->loader_new = image_loader_cr3_new;
522         funcs->set_size = image_loader_cr3_set_size;
523         funcs->load = image_loader_cr3_load;
524         funcs->write = nullptr;
525         funcs->get_pixbuf = image_loader_cr3_get_pixbuf;
526         funcs->close = image_loader_cr3_close;
527         funcs->abort = image_loader_cr3_abort;
528         funcs->free = image_loader_cr3_free;
529
530         funcs->get_format_name = image_loader_cr3_get_format_name;
531         funcs->get_format_mime_types = image_loader_cr3_get_format_mime_types;
532 }
533
534
535
536 #endif
537
538
539 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */