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