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