implemented generic FileData cache
[geeqie.git] / src / exif-common.c
1 /*
2  * Geeqie
3  * (C) 2006 John Ellis
4  * Copyright (C) 2008 The Geeqie Team
5  *
6 */
7
8 #ifdef HAVE_CONFIG_H
9 #  include "config.h"
10 #endif
11
12 #include <stdio.h>
13 #include <string.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/mman.h>
19 #include <math.h>
20
21 #ifdef HAVE_LCMS
22 /*** color support enabled ***/
23
24 #ifdef HAVE_LCMS_LCMS_H
25   #include <lcms/lcms.h>
26 #else
27   #include <lcms.h>
28 #endif
29 #endif
30
31 #include <glib.h>
32
33 #include "intl.h"
34
35 #include "main.h"
36 #include "exif.h"
37
38 #include "filedata.h"
39 #include "filefilter.h"
40 #include "filecache.h"
41 #include "format_raw.h"
42 #include "ui_fileops.h"
43
44
45 static double exif_rational_to_double(ExifRational *r, gint sign)
46 {
47         if (!r || r->den == 0.0) return 0.0;
48
49         if (sign) return (double)((int)r->num) / (double)((int)r->den);
50         return (double)r->num / r->den;
51 }
52
53 static double exif_get_rational_as_double(ExifData *exif, const gchar *key)
54 {
55         ExifRational *r;
56         gint sign;
57
58         r = exif_get_rational(exif, key, &sign);
59         return exif_rational_to_double(r, sign);
60 }
61
62 static GString *append_comma_text(GString *string, const gchar *text)
63 {
64         string = g_string_append(string, ", ");
65         string = g_string_append(string, text);
66
67         return string;
68 }
69
70 static gchar *remove_common_prefix(gchar *s, gchar *t)
71 {
72         gint i;
73
74         if (!s || !t) return t;
75
76         for (i = 0; s[i] && t[i] && s[i] == t[i]; i++)
77                 ;
78         if (!i)
79                 return t;
80         if (s[i-1] == ' ' || !s[i])
81                 {
82                 while (t[i] == ' ')
83                         i++;
84                 return t + i;
85                 }
86         return s;
87 }
88
89 static double get_crop_factor(ExifData *exif)
90 {
91         double res_unit_tbl[] = {0.0, 25.4, 25.4, 10.0, 1.0, 0.001 };
92
93         double xres = exif_get_rational_as_double(exif, "Exif.Photo.FocalPlaneXResolution");
94         double yres = exif_get_rational_as_double(exif, "Exif.Photo.FocalPlaneYResolution");
95         int res_unit;
96         int w, h;
97         double xsize, ysize, size, ratio;
98
99         if (xres == 0.0 || yres == 0.0) return 0.0;
100
101         if (!exif_get_integer(exif, "Exif.Photo.FocalPlaneResolutionUnit", &res_unit)) return 0.0;
102         if (res_unit < 1 || res_unit > 5) return 0.0;
103
104         if (!exif_get_integer(exif, "Exif.Photo.PixelXDimension", &w)) return 0.0;
105         if (!exif_get_integer(exif, "Exif.Photo.PixelYDimension", &h)) return 0.0;
106
107         xsize = w * res_unit_tbl[res_unit] / xres;
108         ysize = h * res_unit_tbl[res_unit] / yres;
109
110         ratio = xsize / ysize;
111
112         if (ratio < 0.5 || ratio > 2.0) return 0.0; /* reasonable ratio */
113
114         size = sqrt(xsize * xsize + ysize * ysize);
115
116         if (size < 1.0 || size > 100.0) return 0.0; /* reasonable sensor size in mm */
117
118         return sqrt(36*36+24*24) / size;
119
120 }
121
122 static gint remove_suffix(gchar *str, const gchar *suffix, gint suffix_len)
123 {
124         gint str_len = strlen(str);
125         
126         if (suffix_len < 0) suffix_len = strlen(suffix);
127         if (str_len < suffix_len) return FALSE;
128         
129         if (strcmp(str + str_len - suffix_len, suffix) != 0) return FALSE; 
130         str[str_len - suffix_len] = '\0';
131         
132         return TRUE;
133 }
134
135 static gchar *exif_build_formatted_Camera(ExifData *exif)
136 {
137         gchar *text;
138         gchar *make = exif_get_data_as_text(exif, "Exif.Image.Make");
139         gchar *model = exif_get_data_as_text(exif, "Exif.Image.Model");
140         gchar *software = exif_get_data_as_text(exif, "Exif.Image.Software");
141         gchar *model2;
142         gchar *software2;
143
144         if (make)
145                 {
146                 g_strstrip(make);
147
148                 if (remove_suffix(make, " CORPORATION", 12)) { /* Nikon */ }
149                 else if (remove_suffix(make, " Corporation", 12)) { /* Pentax */ }
150                 else if (remove_suffix(make, " OPTICAL CO.,LTD", 16)) { /* OLYMPUS */ };
151                 }
152
153         if (model)
154                 g_strstrip(model);
155
156         if (software)
157                 {
158                 gint i;
159
160                 g_strstrip(software);
161                 
162                 /* remove superfluous spaces (pentax K100D) */
163                 for (i = 0; software[i]; i++)
164                         if (software[i] == ' ' && software[i + 1] == ' ')
165                                 {
166                                 gint j;
167
168                                 for (j = 1; software[i + j] == ' '; j++);
169                                 memmove(software + i + 1, software + i + j, strlen(software + i + j) + 1);
170                                 }
171                 }
172
173         model2 = remove_common_prefix(make, model);
174         software2 = remove_common_prefix(model2, software);
175
176         text = g_strdup_printf("%s%s%s%s%s%s", (make) ? make : "", (make && model2) ? " " : "",
177                                                (model2) ? model2 : "",
178                                                (software2 && (make || model2)) ? " (" : "",
179                                                (software2) ? software2 : "",
180                                                (software2 && (make || model2)) ? ")" : "");
181
182         g_free(make);
183         g_free(model);
184         g_free(software);
185         return text;
186 }
187
188 static gchar *exif_build_formatted_DateTime(ExifData *exif)
189 {
190         gchar *text = exif_get_data_as_text(exif, "Exif.Photo.DateTimeOriginal");
191         gchar *subsec = NULL;
192
193         if (text) subsec = exif_get_data_as_text(exif, "Exif.Photo.SubSecTimeOriginal");
194         if (!text)
195                 {
196                 text = exif_get_data_as_text(exif, "Exif.Image.DateTime");
197                 if (text) subsec = exif_get_data_as_text(exif, "Exif.Photo.SubSecTime");
198                 }
199         if (subsec)
200                 {
201                 gchar *tmp = text;
202                 text = g_strconcat(tmp, ".", subsec, NULL);
203                 g_free(tmp);
204                 g_free(subsec);
205                 }
206         return text;
207 }
208
209 static gchar *exif_build_formatted_ShutterSpeed(ExifData *exif)
210 {
211         ExifRational *r;
212
213         r = exif_get_rational(exif, "Exif.Photo.ExposureTime", NULL);
214         if (r && r->num && r->den)
215                 {
216                 double n = (double)r->den / (double)r->num;
217                 return g_strdup_printf("%s%.0fs", n > 1.0 ? "1/" : "",
218                                                   n > 1.0 ? n : 1.0 / n);
219                 }
220         r = exif_get_rational(exif, "Exif.Photo.ShutterSpeedValue", NULL);
221         if (r && r->num  && r->den)
222                 {
223                 double n = pow(2.0, exif_rational_to_double(r, TRUE));
224
225                 /* Correct exposure time to avoid values like 1/91s (seen on Minolta DImage 7) */
226                 if (n > 1.0 && (int)n - ((int)(n/10))*10 == 1) n--;
227
228                 return g_strdup_printf("%s%.0fs", n > 1.0 ? "1/" : "",
229                                                   n > 1.0 ? floor(n) : 1.0 / n);
230                 }
231         return NULL;
232 }
233
234 static gchar *exif_build_formatted_Aperture(ExifData *exif)
235 {
236         double n;
237
238         n = exif_get_rational_as_double(exif, "Exif.Photo.FNumber");
239         if (n == 0.0) n = exif_get_rational_as_double(exif, "Exif.Photo.ApertureValue");
240         if (n == 0.0) return NULL;
241
242         return g_strdup_printf("f/%.1f", n);
243 }
244
245 static gchar *exif_build_formatted_ExposureBias(ExifData *exif)
246 {
247         ExifRational *r;
248         gint sign;
249         double n;
250
251         r = exif_get_rational(exif, "Exif.Photo.ExposureBiasValue", &sign);
252         if (!r) return NULL;
253
254         n = exif_rational_to_double(r, sign);
255         return g_strdup_printf("%+.1f", n);
256 }
257
258 static gchar *exif_build_formatted_FocalLength(ExifData *exif)
259 {
260         double n;
261
262         n = exif_get_rational_as_double(exif, "Exif.Photo.FocalLength");
263         if (n == 0.0) return NULL;
264         return g_strdup_printf("%.0f mm", n);
265 }
266
267 static gchar *exif_build_formatted_FocalLength35mmFilm(ExifData *exif)
268 {
269         gint n;
270         double f, c;
271
272         if (exif_get_integer(exif, "Exif.Photo.FocalLengthIn35mmFilm", &n) && n != 0)
273                 {
274                 return g_strdup_printf("%d mm", n);
275                 }
276
277         f = exif_get_rational_as_double(exif, "Exif.Photo.FocalLength");
278         c = get_crop_factor(exif);
279
280         if (f != 0.0 && c != 0.0)
281                 {
282                 return g_strdup_printf("%.0f mm", f * c);
283                 }
284
285         return NULL;
286 }
287
288 static gchar *exif_build_formatted_ISOSpeedRating(ExifData *exif)
289 {
290         gchar *text;
291
292         text = exif_get_data_as_text(exif, "Exif.Photo.ISOSpeedRatings");
293         /* kodak may set this instead */
294         if (!text) text = exif_get_data_as_text(exif, "Exif.Photo.ExposureIndex");
295         return text;
296 }
297
298 static gchar *exif_build_formatted_SubjectDistance(ExifData *exif)
299 {
300         ExifRational *r;
301         gint sign;
302         double n;
303
304         r = exif_get_rational(exif, "Exif.Photo.SubjectDistance", &sign);
305         if (!r) return NULL;
306
307         if ((long)r->num == (long)0xffffffff) return g_strdup(_("infinity"));
308         if ((long)r->num == 0) return g_strdup(_("unknown"));
309
310         n = exif_rational_to_double(r, sign);
311         if (n == 0.0) return _("unknown");
312         return g_strdup_printf("%.3f m", n);
313 }
314
315 static gchar *exif_build_formatted_Flash(ExifData *exif)
316 {
317         /* grr, flash is a bitmask... */
318         GString *string;
319         gchar *text;
320         gint n;
321         gint v;
322
323         if (!exif_get_integer(exif, "Exif.Photo.Flash", &n)) return NULL;
324
325         /* Exif 2.1 only defines first 3 bits */
326         if (n <= 0x07) return exif_get_data_as_text(exif, "Exif.Photo.Flash");
327
328         /* must be Exif 2.2 */
329         string = g_string_new("");
330
331         /* flash fired (bit 0) */
332         string = g_string_append(string, (n & 0x01) ? _("yes") : _("no"));
333
334         /* flash mode (bits 3, 4) */
335         v = (n >> 3) & 0x03;
336         if (v) string = append_comma_text(string, _("mode:"));
337         switch (v)
338                 {
339                 case 1:
340                         string = g_string_append(string, _("on"));
341                         break;
342                 case 2:
343                         string = g_string_append(string, _("off"));
344                         break;
345                 case 3:
346                         string = g_string_append(string, _("auto"));
347                         break;
348                 }
349
350         /* return light (bits 1, 2) */
351         v = (n >> 1) & 0x03;
352         if (v == 2) string = append_comma_text(string, _("not detected by strobe"));
353         if (v == 3) string = append_comma_text(string, _("detected by strobe"));
354
355         /* we ignore flash function (bit 5) */
356
357         /* red-eye (bit 6) */
358         if ((n >> 5) & 0x01) string = append_comma_text(string, _("red-eye reduction"));
359
360         text = string->str;
361         g_string_free(string, FALSE);
362         return text;
363 }
364
365 static gchar *exif_build_formatted_Resolution(ExifData *exif)
366 {
367         ExifRational *rx, *ry;
368         gchar *units;
369         gchar *text;
370
371         rx = exif_get_rational(exif, "Exif.Image.XResolution", NULL);
372         ry = exif_get_rational(exif, "Exif.Image.YResolution", NULL);
373         if (!rx || !ry) return NULL;
374
375         units = exif_get_data_as_text(exif, "Exif.Image.ResolutionUnit");
376         text = g_strdup_printf("%0.f x %0.f (%s/%s)", rx->den ? (double)rx->num / rx->den : 1.0,
377                                                       ry->den ? (double)ry->num / ry->den : 1.0,
378                                                       _("dot"), (units) ? units : _("unknown"));
379
380         g_free(units);
381         return text;
382 }
383
384 static gchar *exif_build_formatted_ColorProfile(ExifData *exif)
385 {
386         const gchar *name = "";
387         const gchar *source = "";
388         unsigned char *profile_data;
389         guint profile_len;
390
391         profile_data = exif_get_color_profile(exif, &profile_len);
392         if (!profile_data)
393                 {
394                 gint cs;
395                 gchar *interop_index;
396
397                 /* ColorSpace == 1 specifies sRGB per EXIF 2.2 */
398                 if (!exif_get_integer(exif, "Exif.Photo.ColorSpace", &cs)) cs = 0;
399                 interop_index = exif_get_data_as_text(exif, "Exif.Iop.InteroperabilityIndex");
400
401                 if (cs == 1)
402                         {
403                         name = _("sRGB");
404                         source = "ColorSpace";
405                         }
406                 else if (cs == 2 || (interop_index && !strcmp(interop_index, "R03")))
407                         {
408                         name = _("AdobeRGB");
409                         source = (cs == 2) ? "ColorSpace" : "Iop";
410                         }
411
412                 g_free(interop_index);
413                 }
414         else
415                 {
416                 source = _("embedded");
417 #ifdef HAVE_LCMS
418
419                         {
420                         cmsHPROFILE profile;
421
422                         profile = cmsOpenProfileFromMem(profile_data, profile_len);
423                         if (profile)
424                                 {
425                                 name = cmsTakeProductName(profile);
426                                 cmsCloseProfile(profile);
427                                 }
428                         g_free(profile_data);
429                         }
430 #endif
431                 }
432         if (name[0] == 0 && source[0] == 0) return NULL;
433         return g_strdup_printf("%s (%s)", name, source);
434 }
435
436
437 /* List of custom formatted pseudo-exif tags */
438 #define EXIF_FORMATTED_TAG(name, label) { "formatted."#name, label, exif_build_formatted##_##name }
439
440 ExifFormattedText ExifFormattedList[] = {
441         EXIF_FORMATTED_TAG(Camera,              N_("Camera")),
442         EXIF_FORMATTED_TAG(DateTime,            N_("Date")),
443         EXIF_FORMATTED_TAG(ShutterSpeed,        N_("Shutter speed")),
444         EXIF_FORMATTED_TAG(Aperture,            N_("Aperture")),
445         EXIF_FORMATTED_TAG(ExposureBias,        N_("Exposure bias")),
446         EXIF_FORMATTED_TAG(ISOSpeedRating,      N_("ISO sensitivity")),
447         EXIF_FORMATTED_TAG(FocalLength,         N_("Focal length")),
448         EXIF_FORMATTED_TAG(FocalLength35mmFilm, N_("Focal length 35mm")),
449         EXIF_FORMATTED_TAG(SubjectDistance,     N_("Subject distance")),
450         EXIF_FORMATTED_TAG(Flash,               N_("Flash")),
451         EXIF_FORMATTED_TAG(Resolution,          N_("Resolution")),
452         EXIF_FORMATTED_TAG(ColorProfile,        N_("Color profile")),
453         { NULL, NULL, NULL }
454 };
455
456 gchar *exif_get_formatted_by_key(ExifData *exif, const gchar *key, gint *key_valid)
457 {
458         if (strncmp(key, "formatted.", 10) == 0)
459                 {
460                 gint i;
461
462                 if (key_valid) *key_valid = TRUE;
463
464                 key = key + 10;
465                 for (i = 0; ExifFormattedList[i].key; i++)
466                         if (strcmp(key, ExifFormattedList[i].key + 10) == 0)
467                                 return ExifFormattedList[i].build_func(exif);
468                 }
469
470         if (key_valid) *key_valid = FALSE;
471         return NULL;
472 }
473
474 const gchar *exif_get_description_by_key(const gchar *key)
475 {
476         gint i;
477
478         if (!key) return NULL;
479
480         if (strncmp(key, "formatted.", 10) == 0)
481                 {
482                 key = key + 10;
483                 for (i = 0; ExifFormattedList[i].key; i++)
484                         if (strcmp(key, ExifFormattedList[i].key + 10) == 0)
485                                 return _(ExifFormattedList[i].description);
486                 }
487
488         return exif_get_tag_description_by_key(key);
489 }
490
491 gint exif_get_integer(ExifData *exif, const gchar *key, gint *value)
492 {
493         ExifItem *item;
494
495         item = exif_get_item(exif, key);
496         return exif_item_get_integer(item, value);
497 }
498
499 ExifRational *exif_get_rational(ExifData *exif, const gchar *key, gint *sign)
500 {
501         ExifItem *item;
502
503         item = exif_get_item(exif, key);
504         return exif_item_get_rational(item, sign);
505 }
506
507 gchar *exif_get_data_as_text(ExifData *exif, const gchar *key)
508 {
509         ExifItem *item;
510         gchar *text;
511         gint key_valid;
512
513         if (!key) return NULL;
514
515         text = exif_get_formatted_by_key(exif, key, &key_valid);
516         if (key_valid) return text;
517
518         item = exif_get_item(exif, key);
519         if (item) return exif_item_get_data_as_text(item);
520
521         return NULL;
522 }
523
524
525 static FileCacheData *exif_cache;
526
527 void exif_release_cb(FileData *fd)
528 {
529         exif_free(fd->exif);
530         fd->exif = NULL;
531 }
532
533 ExifData *exif_read_fd(FileData *fd)
534 {
535         gchar *sidecar_path = NULL;
536
537         if (!fd) return NULL;
538         
539         if (!exif_cache) exif_cache = file_cache_new(exif_release_cb, 4);
540         
541         if (file_cache_get(exif_cache, fd)) return fd->exif;
542
543         if (filter_file_class(fd->extension, FORMAT_CLASS_RAWIMAGE))
544                 {
545                 GList *work;
546                 
547                 work = fd->parent ? fd->parent->sidecar_files : fd->sidecar_files;
548                 while (work)
549                         {
550                         FileData *sfd = work->data;
551                         work = work->next;
552                         if (strcasecmp(sfd->extension, ".xmp") == 0)
553                                 {
554                                 sidecar_path = sfd->path;
555                                 break;
556                                 }
557                         }
558                 }
559
560
561         fd->exif = exif_read(fd->path, sidecar_path);
562         return fd->exif;
563 }
564
565 void exif_free_fd(FileData *fd, ExifData *exif)
566 {
567         if (!fd) return;
568         g_assert(fd->exif == exif);
569         
570         file_cache_put(exif_cache, fd, 1);
571 }
572
573 /* embedded icc in jpeg */
574
575
576 #define JPEG_MARKER             0xFF
577 #define JPEG_MARKER_SOI         0xD8
578 #define JPEG_MARKER_EOI         0xD9
579 #define JPEG_MARKER_APP1        0xE1
580 #define JPEG_MARKER_APP2        0xE2
581
582 /* jpeg container format:
583      all data markers start with 0XFF
584      2 byte long file start and end markers: 0xFFD8(SOI) and 0XFFD9(EOI)
585      4 byte long data segment markers in format: 0xFFTTSSSSNNN...
586        FF:   1 byte standard marker identifier
587        TT:   1 byte data type
588        SSSS: 2 bytes in Motorola byte alignment for length of the data.
589              This value includes these 2 bytes in the count, making actual
590              length of NN... == SSSS - 2.
591        NNN.: the data in this segment
592  */
593
594 gint exif_jpeg_segment_find(unsigned char *data, guint size,
595                             guchar app_marker, const gchar *magic, guint magic_len,
596                             guint *seg_offset, guint *seg_length)
597 {
598         guchar marker = 0;
599         guint offset = 0;
600         guint length = 0;
601
602         while (marker != app_marker &&
603                marker != JPEG_MARKER_EOI)
604                 {
605                 offset += length;
606                 length = 2;
607
608                 if (offset + 2 >= size ||
609                     data[offset] != JPEG_MARKER) return FALSE;
610
611                 marker = data[offset + 1];
612                 if (marker != JPEG_MARKER_SOI &&
613                     marker != JPEG_MARKER_EOI)
614                         {
615                         if (offset + 4 >= size) return FALSE;
616                         length += ((guint)data[offset + 2] << 8) + data[offset + 3];
617                         }
618                 }
619
620         if (marker == app_marker &&
621             offset + length < size &&
622             length >= 4 + magic_len &&
623             memcmp(data + offset + 4, magic, magic_len) == 0)
624                 {
625                 *seg_offset = offset + 4;
626                 *seg_length = length - 4;
627                 return TRUE;
628                 }
629
630         return FALSE;
631 }
632
633 gint exif_jpeg_parse_color(ExifData *exif, unsigned char *data, guint size)
634 {
635         guint seg_offset = 0;
636         guint seg_length = 0;
637         guint chunk_offset[255];
638         guint chunk_length[255];
639         guint chunk_count = 0;
640
641         /* For jpeg/jfif, ICC color profile data can be in more than one segment.
642            the data is in APP2 data segments that start with "ICC_PROFILE\x00\xNN\xTT"
643            NN = segment number for data
644            TT = total number of ICC segments (TT in each ICC segment should match)
645          */
646
647         while (exif_jpeg_segment_find(data + seg_offset + seg_length,
648                                       size - seg_offset - seg_length,
649                                       JPEG_MARKER_APP2,
650                                       "ICC_PROFILE\x00", 12,
651                                       &seg_offset, &seg_length))
652                 {
653                 guchar chunk_num;
654                 guchar chunk_tot;
655
656                 if (seg_length < 14) return FALSE;
657
658                 chunk_num = data[seg_offset + 12];
659                 chunk_tot = data[seg_offset + 13];
660
661                 if (chunk_num == 0 || chunk_tot == 0) return FALSE;
662
663                 if (chunk_count == 0)
664                         {
665                         guint i;
666
667                         chunk_count = (guint)chunk_tot;
668                         for (i = 0; i < chunk_count; i++) chunk_offset[i] = 0;
669                         for (i = 0; i < chunk_count; i++) chunk_length[i] = 0;
670                         }
671
672                 if (chunk_tot != chunk_count ||
673                     chunk_num > chunk_count) return FALSE;
674
675                 chunk_num--;
676                 chunk_offset[chunk_num] = seg_offset + 14;
677                 chunk_length[chunk_num] = seg_length - 14;
678                 }
679
680         if (chunk_count > 0)
681                 {
682                 unsigned char *cp_data;
683                 guint cp_length = 0;
684                 guint i;
685
686                 for (i = 0; i < chunk_count; i++) cp_length += chunk_length[i];
687                 cp_data = g_malloc(cp_length);
688
689                 for (i = 0; i < chunk_count; i++)
690                         {
691                         if (chunk_offset[i] == 0)
692                                 {
693                                 /* error, we never saw this chunk */
694                                 g_free(cp_data);
695                                 return FALSE;
696                                 }
697                         memcpy(cp_data, data + chunk_offset[i], chunk_length[i]);
698                         }
699                 DEBUG_1("Found embedded icc profile in jpeg");
700                 exif_add_jpeg_color_profile(exif, cp_data, cp_length);
701
702                 return TRUE;
703                 }
704
705         return FALSE;
706 }