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