Simplify vflist_get_formatted()
[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;
97         guint j;
98
99         g_return_if_fail (cinfo != NULL);
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, m, y, k;
109                         c = p[0];
110                         m = p[1];
111                         y = p[2];
112                         k = p[3];
113                         if (cinfo->saw_Adobe_marker) {
114                                 p[0] = k*c / 255;
115                                 p[1] = k*m / 255;
116                                 p[2] = k*y / 255;
117                         }
118                         else {
119                                 p[0] = (255 - k)*(255 - c) / 255;
120                                 p[1] = (255 - k)*(255 - m) / 255;
121                                 p[2] = (255 - k)*(255 - y) / 255;
122                         }
123                         p[3] = 255;
124                         p += 4;
125                 }
126         }
127 }
128
129
130 static gpointer image_loader_cr3_new(ImageLoaderBackendCbAreaUpdated area_updated_cb, ImageLoaderBackendCbSize size_cb, ImageLoaderBackendCbAreaPrepared area_prepared_cb, gpointer data)
131 {
132         ImageLoaderJpeg *loader = g_new0(ImageLoaderJpeg, 1);
133
134         loader->area_updated_cb = area_updated_cb;
135         loader->size_cb = size_cb;
136         loader->area_prepared_cb = area_prepared_cb;
137         loader->data = data;
138         return (gpointer) loader;
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 = (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 == NULL) {
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 cinfo)
172 {
173   /* This method keeps libjpeg from dumping crap to stderr */
174
175   /* do nothing */
176 }
177
178
179 static void image_loader_cr3_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 cinfo) {}
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         struct jpeg_source_mgr* src = (struct jpeg_source_mgr*) cinfo->src;
220
221         if ((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 += (size_t) num_bytes;
228                 src->bytes_in_buffer -= (size_t) num_bytes;
229                 }
230 }
231 static void term_source (j_decompress_ptr cinfo) {}
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 == NULL)
237                 {   /* first time for this JPEG object? */
238                 cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) (
239                                         (j_common_ptr) cinfo, JPOOL_PERMANENT,
240                                         sizeof(struct jpeg_source_mgr));
241                 }
242
243         src = (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 = (JOCTET*)buffer;
251 }
252
253
254 static gboolean image_loader_cr3_load (gpointer loader, const guchar *buf, gsize count, GError **error)
255 {
256         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
257         struct jpeg_decompress_struct cinfo;
258         struct jpeg_decompress_struct cinfo2;
259         guchar *dptr, *dptr2;
260         guint rowstride;
261         guchar *stereo_buf2 = NULL;
262         guint stereo_length = 0;
263
264         struct error_handler_data jerr;
265
266 /** @FIXME Just start search at where full size jpeg should be,
267  * / then search through the file looking for a jpeg end-marker
268  */
269         gboolean found = FALSE;
270         gint i;
271         guint n;
272
273         n = 0;
274         while (n < count - 4 && !found)
275                 {
276                 if (memcmp(&buf[n], "mdat", 4) == 0)
277                         {
278                         if (memcmp(&buf[n + 12], "\xFF\xD8", 2) == 0)
279                                 {
280                                 i = 0;
281                                 while (!found )
282                                         {
283                                         if (memcmp(&buf[n + 12 + i], "\xFF\xD9", 2) == 0)
284                                                 {
285                                                 found = TRUE;
286                                                 }
287                                         i++;
288                                         }
289                                 }
290                         else
291                                 {
292                                 break;
293                                 }
294                         }
295                 else
296                         {
297                         n++;
298                         }
299                 }
300
301         if (!found)
302                 {
303                 return FALSE;
304                 }
305
306         count = i;
307         buf = (unsigned char *)buf + n + 12;
308
309         lj->stereo = FALSE;
310
311         MPOData *mpo = jpeg_get_mpo_data(buf, count);
312         if (mpo && mpo->num_images > 1)
313                 {
314                 guint i;
315                 gint idx1 = -1, idx2 = -1;
316                 guint num2 = 1;
317
318                 for (i = 0; i < mpo->num_images; i++)
319                         {
320                         if (mpo->images[i].type_code == 0x20002)
321                                 {
322                                 if (mpo->images[i].MPIndividualNum == 1)
323                                         {
324                                         idx1 = i;
325                                         }
326                                 else if (mpo->images[i].MPIndividualNum > num2)
327                                         {
328                                         idx2 = i;
329                                         num2 = mpo->images[i].MPIndividualNum;
330                                         }
331                                 }
332                         }
333
334                 if (idx1 >= 0 && idx2 >= 0)
335                         {
336                         lj->stereo = TRUE;
337                         stereo_buf2 = (unsigned char *)buf + mpo->images[idx2].offset;
338                         stereo_length = mpo->images[idx2].length;
339                         buf = (unsigned char *)buf + mpo->images[idx1].offset;
340                         count = mpo->images[idx1].length;
341                         }
342                 }
343         jpeg_mpo_data_free(mpo);
344
345         /* setup error handler */
346         cinfo.err = jpeg_std_error (&jerr.pub);
347         if (lj->stereo) cinfo2.err = jpeg_std_error (&jerr.pub);
348         jerr.pub.error_exit = fatal_error_handler;
349         jerr.pub.output_message = output_message_handler;
350
351         jerr.error = error;
352
353
354         if (setjmp(jerr.setjmp_buffer))
355                 {
356                 /* If we get here, the JPEG code has signaled an error.
357                  * We need to clean up the JPEG object, close the input file, and return.
358                 */
359                 jpeg_destroy_decompress(&cinfo);
360                 if (lj->stereo) jpeg_destroy_decompress(&cinfo2);
361                 return FALSE;
362                 }
363
364         jpeg_create_decompress(&cinfo);
365
366         set_mem_src(&cinfo, (unsigned char *)buf, count);
367
368
369         jpeg_read_header(&cinfo, TRUE);
370
371         if (lj->stereo)
372                 {
373                 jpeg_create_decompress(&cinfo2);
374                 set_mem_src(&cinfo2, stereo_buf2, stereo_length);
375                 jpeg_read_header(&cinfo2, TRUE);
376
377                 if (cinfo.image_width != cinfo2.image_width ||
378                     cinfo.image_height != cinfo2.image_height)
379                         {
380                         DEBUG_1("stereo data with different size");
381                         jpeg_destroy_decompress(&cinfo2);
382                         lj->stereo = FALSE;
383                         }
384                 }
385
386
387
388         lj->requested_width = lj->stereo ? cinfo.image_width * 2: cinfo.image_width;
389         lj->requested_height = cinfo.image_height;
390         lj->size_cb(loader, lj->requested_width, lj->requested_height, lj->data);
391
392         cinfo.scale_num = 1;
393         for (cinfo.scale_denom = 2; cinfo.scale_denom <= 8; cinfo.scale_denom *= 2) {
394                 jpeg_calc_output_dimensions(&cinfo);
395                 if (cinfo.output_width < (lj->stereo ? lj->requested_width / 2 : lj->requested_width) || cinfo.output_height < lj->requested_height) {
396                         cinfo.scale_denom /= 2;
397                         break;
398                 }
399         }
400         jpeg_calc_output_dimensions(&cinfo);
401         if (lj->stereo)
402                 {
403                 cinfo2.scale_num = cinfo.scale_num;
404                 cinfo2.scale_denom = cinfo.scale_denom;
405                 jpeg_calc_output_dimensions(&cinfo2);
406                 jpeg_start_decompress(&cinfo2);
407                 }
408
409
410         jpeg_start_decompress(&cinfo);
411
412
413         if (lj->stereo)
414                 {
415                 if (cinfo.output_width != cinfo2.output_width ||
416                     cinfo.output_height != cinfo2.output_height ||
417                     cinfo.out_color_components != cinfo2.out_color_components)
418                         {
419                         DEBUG_1("stereo data with different output size");
420                         jpeg_destroy_decompress(&cinfo2);
421                         lj->stereo = FALSE;
422                         }
423                 }
424
425
426         lj->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
427                                      cinfo.out_color_components == 4 ? TRUE : FALSE,
428                                      8, lj->stereo ? cinfo.output_width * 2: cinfo.output_width, cinfo.output_height);
429
430         if (!lj->pixbuf)
431                 {
432                 jpeg_destroy_decompress (&cinfo);
433                 if (lj->stereo) jpeg_destroy_decompress (&cinfo2);
434                 return 0;
435                 }
436         if (lj->stereo) g_object_set_data(G_OBJECT(lj->pixbuf), "stereo_data", GINT_TO_POINTER(STEREO_PIXBUF_CROSS));
437         lj->area_prepared_cb(loader, lj->data);
438
439         rowstride = gdk_pixbuf_get_rowstride(lj->pixbuf);
440         dptr = gdk_pixbuf_get_pixels(lj->pixbuf);
441         dptr2 = gdk_pixbuf_get_pixels(lj->pixbuf) + ((cinfo.out_color_components == 4) ? 4 * cinfo.output_width : 3 * cinfo.output_width);
442
443
444         while (cinfo.output_scanline < cinfo.output_height && !lj->abort)
445                 {
446                 guint scanline = cinfo.output_scanline;
447                 image_loader_cr3_read_scanline(&cinfo, &dptr, rowstride);
448                 lj->area_updated_cb(loader, 0, scanline, cinfo.output_width, cinfo.rec_outbuf_height, lj->data);
449                 if (lj->stereo)
450                         {
451                         guint scanline = cinfo2.output_scanline;
452                         image_loader_cr3_read_scanline(&cinfo2, &dptr2, rowstride);
453                         lj->area_updated_cb(loader, cinfo.output_width, scanline, cinfo2.output_width, cinfo2.rec_outbuf_height, lj->data);
454                         }
455                 }
456
457         jpeg_finish_decompress(&cinfo);
458         jpeg_destroy_decompress(&cinfo);
459         if (lj->stereo)
460                 {
461                 jpeg_finish_decompress(&cinfo);
462                 jpeg_destroy_decompress(&cinfo);
463                 }
464
465         return TRUE;
466 }
467
468 static void image_loader_cr3_set_size(gpointer loader, int width, int height)
469 {
470         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
471         lj->requested_width = width;
472         lj->requested_height = height;
473 }
474
475 static GdkPixbuf* image_loader_cr3_get_pixbuf(gpointer loader)
476 {
477         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
478         return lj->pixbuf;
479 }
480
481 static gchar* image_loader_cr3_get_format_name(gpointer loader)
482 {
483         return g_strdup("cr3");
484 }
485 static gchar** image_loader_cr3_get_format_mime_types(gpointer loader)
486 {
487         static gchar *mime[] = {"image/x-canon-cr3", NULL};
488         return g_strdupv(mime);
489 }
490
491 static gboolean image_loader_cr3_close(gpointer loader, GError **error)
492 {
493         return TRUE;
494 }
495
496 static void image_loader_cr3_abort(gpointer loader)
497 {
498         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
499         lj->abort = TRUE;
500 }
501
502 static void image_loader_cr3_free(gpointer loader)
503 {
504         ImageLoaderJpeg *lj = (ImageLoaderJpeg *) loader;
505         if (lj->pixbuf) g_object_unref(lj->pixbuf);
506         g_free(lj);
507 }
508
509
510 void image_loader_backend_set_cr3(ImageLoaderBackend *funcs)
511 {
512         funcs->loader_new = image_loader_cr3_new;
513         funcs->set_size = image_loader_cr3_set_size;
514         funcs->load = image_loader_cr3_load;
515         funcs->write = NULL;
516         funcs->get_pixbuf = image_loader_cr3_get_pixbuf;
517         funcs->close = image_loader_cr3_close;
518         funcs->abort = image_loader_cr3_abort;
519         funcs->free = image_loader_cr3_free;
520
521         funcs->get_format_name = image_loader_cr3_get_format_name;
522         funcs->get_format_mime_types = image_loader_cr3_get_format_mime_types;
523 }
524
525
526
527 #endif
528
529
530 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */