Add a pointer to the build function in the formatted exif tags struct
[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 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 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_fCamera(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_fDateTime(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_fShutterSpeed(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_fAperture(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_fExposureBias(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_fFocalLength(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_fFocalLength35mmFilm(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_fISOSpeedRating(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_fSubjectDistance(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_fFlash(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_fResolution(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_fColorProfile(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) { #name, label, exif_build##_##name }
438
439 ExifFormattedText ExifFormattedList[] = {
440         EXIF_FORMATTED_TAG(fCamera,             N_("Camera")),
441         EXIF_FORMATTED_TAG(fDateTime,           N_("Date")),
442         EXIF_FORMATTED_TAG(fShutterSpeed,       N_("Shutter speed")),
443         EXIF_FORMATTED_TAG(fAperture,           N_("Aperture")),
444         EXIF_FORMATTED_TAG(fExposureBias,       N_("Exposure bias")),
445         EXIF_FORMATTED_TAG(fISOSpeedRating,     N_("ISO sensitivity")),
446         EXIF_FORMATTED_TAG(fFocalLength,        N_("Focal length")),
447         EXIF_FORMATTED_TAG(fFocalLength35mmFilm,N_("Focal length 35mm")),
448         EXIF_FORMATTED_TAG(fSubjectDistance,    N_("Subject distance")),
449         EXIF_FORMATTED_TAG(fFlash,              N_("Flash")),
450         EXIF_FORMATTED_TAG(fResolution,         N_("Resolution")),
451         EXIF_FORMATTED_TAG(fColorProfile,       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         /* must begin with f, else not formatted */
458         if (key[0] == 'f')
459                 {
460                 gint i;
461
462                 if (key_valid) *key_valid = TRUE;
463
464                 for (i = 0; ExifFormattedList[i].key; i++)
465                         if (strcmp(key, ExifFormattedList[i].key) == 0)
466                                 return ExifFormattedList[i].build_func(exif);
467                 }
468
469         if (key_valid) *key_valid = FALSE;
470         return NULL;
471 }
472
473 const gchar *exif_get_description_by_key(const gchar *key)
474 {
475         gint i;
476
477         if (!key) return NULL;
478
479         i = 0;
480         while (ExifFormattedList[i].key != NULL)
481                 {
482                 if (strcmp(key, ExifFormattedList[i].key) == 0) return _(ExifFormattedList[i].description);
483                 i++;
484                 }
485
486         return exif_get_tag_description_by_key(key);
487 }
488
489 gint exif_get_integer(ExifData *exif, const gchar *key, gint *value)
490 {
491         ExifItem *item;
492
493         item = exif_get_item(exif, key);
494         return exif_item_get_integer(item, value);
495 }
496
497 ExifRational *exif_get_rational(ExifData *exif, const gchar *key, gint *sign)
498 {
499         ExifItem *item;
500
501         item = exif_get_item(exif, key);
502         return exif_item_get_rational(item, sign);
503 }
504
505 gchar *exif_get_data_as_text(ExifData *exif, const gchar *key)
506 {
507         ExifItem *item;
508         gchar *text;
509         gint key_valid;
510
511         if (!key) return NULL;
512
513         text = exif_get_formatted_by_key(exif, key, &key_valid);
514         if (key_valid) return text;
515
516         item = exif_get_item(exif, key);
517         if (item) return exif_item_get_data_as_text(item);
518
519         return NULL;
520 }
521
522 ExifData *exif_read_fd(FileData *fd)
523 {
524         gchar *sidecar_path = NULL;
525
526         if (!fd) return NULL;
527
528         if (filter_file_class(fd->extension, FORMAT_CLASS_RAWIMAGE))
529                 {
530                 GList *work;
531                 
532                 work = fd->parent ? fd->parent->sidecar_files : fd->sidecar_files;
533                 while (work)
534                         {
535                         FileData *sfd = work->data;
536                         work = work->next;
537                         if (strcasecmp(sfd->extension, ".xmp") == 0)
538                                 {
539                                 sidecar_path = sfd->path;
540                                 break;
541                                 }
542                         }
543                 }
544
545
546         // FIXME: some caching would be nice
547         return exif_read(fd->path, sidecar_path);
548 }
549
550
551
552 /* embedded icc in jpeg */
553
554
555 #define JPEG_MARKER             0xFF
556 #define JPEG_MARKER_SOI         0xD8
557 #define JPEG_MARKER_EOI         0xD9
558 #define JPEG_MARKER_APP1        0xE1
559 #define JPEG_MARKER_APP2        0xE2
560
561 /* jpeg container format:
562      all data markers start with 0XFF
563      2 byte long file start and end markers: 0xFFD8(SOI) and 0XFFD9(EOI)
564      4 byte long data segment markers in format: 0xFFTTSSSSNNN...
565        FF:   1 byte standard marker identifier
566        TT:   1 byte data type
567        SSSS: 2 bytes in Motorola byte alignment for length of the data.
568              This value includes these 2 bytes in the count, making actual
569              length of NN... == SSSS - 2.
570        NNN.: the data in this segment
571  */
572
573 gint exif_jpeg_segment_find(unsigned char *data, guint size,
574                             guchar app_marker, const gchar *magic, guint magic_len,
575                             guint *seg_offset, guint *seg_length)
576 {
577         guchar marker = 0;
578         guint offset = 0;
579         guint length = 0;
580
581         while (marker != app_marker &&
582                marker != JPEG_MARKER_EOI)
583                 {
584                 offset += length;
585                 length = 2;
586
587                 if (offset + 2 >= size ||
588                     data[offset] != JPEG_MARKER) return FALSE;
589
590                 marker = data[offset + 1];
591                 if (marker != JPEG_MARKER_SOI &&
592                     marker != JPEG_MARKER_EOI)
593                         {
594                         if (offset + 4 >= size) return FALSE;
595                         length += ((guint)data[offset + 2] << 8) + data[offset + 3];
596                         }
597                 }
598
599         if (marker == app_marker &&
600             offset + length < size &&
601             length >= 4 + magic_len &&
602             memcmp(data + offset + 4, magic, magic_len) == 0)
603                 {
604                 *seg_offset = offset + 4;
605                 *seg_length = length - 4;
606                 return TRUE;
607                 }
608
609         return FALSE;
610 }
611
612 gint exif_jpeg_parse_color(ExifData *exif, unsigned char *data, guint size)
613 {
614         guint seg_offset = 0;
615         guint seg_length = 0;
616         guint chunk_offset[255];
617         guint chunk_length[255];
618         guint chunk_count = 0;
619
620         /* For jpeg/jfif, ICC color profile data can be in more than one segment.
621            the data is in APP2 data segments that start with "ICC_PROFILE\x00\xNN\xTT"
622            NN = segment number for data
623            TT = total number of ICC segments (TT in each ICC segment should match)
624          */
625
626         while (exif_jpeg_segment_find(data + seg_offset + seg_length,
627                                       size - seg_offset - seg_length,
628                                       JPEG_MARKER_APP2,
629                                       "ICC_PROFILE\x00", 12,
630                                       &seg_offset, &seg_length))
631                 {
632                 guchar chunk_num;
633                 guchar chunk_tot;
634
635                 if (seg_length < 14) return FALSE;
636
637                 chunk_num = data[seg_offset + 12];
638                 chunk_tot = data[seg_offset + 13];
639
640                 if (chunk_num == 0 || chunk_tot == 0) return FALSE;
641
642                 if (chunk_count == 0)
643                         {
644                         guint i;
645
646                         chunk_count = (guint)chunk_tot;
647                         for (i = 0; i < chunk_count; i++) chunk_offset[i] = 0;
648                         for (i = 0; i < chunk_count; i++) chunk_length[i] = 0;
649                         }
650
651                 if (chunk_tot != chunk_count ||
652                     chunk_num > chunk_count) return FALSE;
653
654                 chunk_num--;
655                 chunk_offset[chunk_num] = seg_offset + 14;
656                 chunk_length[chunk_num] = seg_length - 14;
657                 }
658
659         if (chunk_count > 0)
660                 {
661                 unsigned char *cp_data;
662                 guint cp_length = 0;
663                 guint i;
664
665                 for (i = 0; i < chunk_count; i++) cp_length += chunk_length[i];
666                 cp_data = g_malloc(cp_length);
667
668                 for (i = 0; i < chunk_count; i++)
669                         {
670                         if (chunk_offset[i] == 0)
671                                 {
672                                 /* error, we never saw this chunk */
673                                 g_free(cp_data);
674                                 return FALSE;
675                                 }
676                         memcpy(cp_data, data + chunk_offset[i], chunk_length[i]);
677                         }
678                 DEBUG_1("Found embedded icc profile in jpeg");
679                 exif_add_jpeg_color_profile(exif, cp_data, cp_length);
680
681                 return TRUE;
682                 }
683
684         return FALSE;
685 }