fd2c6a3af47b6a3284c2f316052a93db988c5dbb
[geeqie.git] / src / exif-common.c
1 /*
2  * Copyright (C) 2006 John Ellis
3  * Copyright (C) 2008 - 2016 The Geeqie Team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #define _XOPEN_SOURCE
25
26 #include <stdio.h>
27 #include <string.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/mman.h>
33 #include <math.h>
34
35 #ifdef HAVE_LCMS
36 /*** color support enabled ***/
37
38 #ifdef HAVE_LCMS2
39 #include <lcms2.h>
40 #else
41 #include <lcms.h>
42 #endif
43 #endif
44
45 #include <glib.h>
46
47 #include "intl.h"
48
49 #include "main.h"
50 #include "exif.h"
51
52 #include "filedata.h"
53 #include "filefilter.h"
54 #include "filecache.h"
55 #include "format_raw.h"
56 #include "glua.h"
57 #include "ui_fileops.h"
58 #include "cache.h"
59 #include "jpeg_parser.h"
60 #include "misc.h"
61 #include "zonedetect.h"
62
63
64 static gdouble exif_rational_to_double(ExifRational *r, gint sign)
65 {
66         if (!r || r->den == 0.0) return 0.0;
67
68         if (sign) return (gdouble)((gint)r->num) / (gdouble)((gint)r->den);
69         return (gdouble)r->num / r->den;
70 }
71
72 static gdouble exif_get_rational_as_double(ExifData *exif, const gchar *key)
73 {
74         ExifRational *r;
75         gint sign;
76
77         r = exif_get_rational(exif, key, &sign);
78         return exif_rational_to_double(r, sign);
79 }
80
81 static GString *append_comma_text(GString *string, const gchar *text)
82 {
83         string = g_string_append(string, ", ");
84         string = g_string_append(string, text);
85
86         return string;
87 }
88
89 static gchar *remove_common_prefix(gchar *s, gchar *t)
90 {
91         gint i;
92
93         if (!s || !t) return t;
94
95         for (i = 0; s[i] && t[i] && s[i] == t[i]; i++)
96                 ;
97         if (!i)
98                 return t;
99         if (s[i-1] == ' ' || !s[i])
100                 {
101                 while (t[i] == ' ')
102                         i++;
103                 return t + i;
104                 }
105         return s;
106 }
107
108 static gdouble get_crop_factor(ExifData *exif)
109 {
110         gdouble res_unit_tbl[] = {0.0, 25.4, 25.4, 10.0, 1.0, 0.001 };
111         gdouble xres = exif_get_rational_as_double(exif, "Exif.Photo.FocalPlaneXResolution");
112         gdouble yres = exif_get_rational_as_double(exif, "Exif.Photo.FocalPlaneYResolution");
113         gint res_unit;
114         gint w, h;
115         gdouble xsize, ysize, size, ratio;
116
117         if (xres == 0.0 || yres == 0.0) return 0.0;
118
119         if (!exif_get_integer(exif, "Exif.Photo.FocalPlaneResolutionUnit", &res_unit)) return 0.0;
120         if (res_unit < 1 || res_unit > 5) return 0.0;
121
122         if (!exif_get_integer(exif, "Exif.Photo.PixelXDimension", &w)) return 0.0;
123         if (!exif_get_integer(exif, "Exif.Photo.PixelYDimension", &h)) return 0.0;
124
125         xsize = w * res_unit_tbl[res_unit] / xres;
126         ysize = h * res_unit_tbl[res_unit] / yres;
127
128         ratio = xsize / ysize;
129
130         if (ratio < 0.5 || ratio > 2.0) return 0.0; /* reasonable ratio */
131
132         size = sqrt(xsize * xsize + ysize * ysize);
133
134         if (size < 1.0 || size > 100.0) return 0.0; /* reasonable sensor size in mm */
135
136         return sqrt(36*36+24*24) / size;
137
138 }
139
140 static gboolean remove_suffix(gchar *str, const gchar *suffix, gint suffix_len)
141 {
142         gint str_len = strlen(str);
143
144         if (suffix_len < 0) suffix_len = strlen(suffix);
145         if (str_len < suffix_len) return FALSE;
146
147         if (strcmp(str + str_len - suffix_len, suffix) != 0) return FALSE;
148         str[str_len - suffix_len] = '\0';
149
150         return TRUE;
151 }
152
153 static gchar *exif_build_formatted_Camera(ExifData *exif)
154 {
155         gchar *text;
156         gchar *make = exif_get_data_as_text(exif, "Exif.Image.Make");
157         gchar *model = exif_get_data_as_text(exif, "Exif.Image.Model");
158         gchar *software = exif_get_data_as_text(exif, "Exif.Image.Software");
159         gchar *model2;
160         gchar *software2;
161
162         if (make)
163                 {
164                 g_strstrip(make);
165
166                 if (remove_suffix(make, " CORPORATION", 12)) { /* Nikon */ }
167                 else if (remove_suffix(make, " Corporation", 12)) { /* Pentax */ }
168                 else if (remove_suffix(make, " OPTICAL CO.,LTD", 16)) { /* OLYMPUS */ };
169                 }
170
171         if (model)
172                 g_strstrip(model);
173
174         if (software)
175                 {
176                 gint i, j;
177
178                 g_strstrip(software);
179
180                 /* remove superfluous spaces (pentax K100D) */
181                 for (i = 0, j = 0; software[i]; i++, j++)
182                         {
183                         if (software[i] == ' ' && software[i + 1] == ' ')
184                                 i++;
185                         if (i != j) software[j] = software[i];
186                         }
187                 software[j] = '\0';
188                 }
189
190         model2 = remove_common_prefix(make, model);
191         software2 = remove_common_prefix(model2, software);
192
193         text = g_strdup_printf("%s%s%s%s%s%s", (make) ? make : "", (make && model2) ? " " : "",
194                                                (model2) ? model2 : "",
195                                                (software2 && (make || model2)) ? " (" : "",
196                                                (software2) ? software2 : "",
197                                                (software2 && (make || model2)) ? ")" : "");
198
199         g_free(make);
200         g_free(model);
201         g_free(software);
202         return text;
203 }
204
205 static gchar *exif_build_formatted_DateTime(ExifData *exif)
206 {
207         gchar *text = exif_get_data_as_text(exif, "Exif.Photo.DateTimeOriginal");
208         gchar *subsec = NULL;
209         gchar buf[128];
210         gchar *tmp;
211         gint buflen;
212         struct tm tm;
213         GError *error = NULL;
214
215         if (text)
216                 {
217                 subsec = exif_get_data_as_text(exif, "Exif.Photo.SubSecTimeOriginal");
218                 }
219         else
220                 {
221                 text = exif_get_data_as_text(exif, "Exif.Image.DateTime");
222                 if (text) subsec = exif_get_data_as_text(exif, "Exif.Photo.SubSecTime");
223                 }
224
225         /* Convert the stuff into a tm struct */
226         memset(&tm, 0, sizeof(tm)); /* Uh, strptime could let garbage in tm! */
227         if (text && strptime(text, "%Y:%m:%d %H:%M:%S", &tm))
228                 {
229                 buflen = strftime(buf, sizeof(buf), "%x %X", &tm);
230                 if (buflen > 0)
231                         {
232                         tmp = g_locale_to_utf8(buf, buflen, NULL, NULL, &error);
233                         if (error)
234                                 {
235                                 log_printf("Error converting locale strftime to UTF-8: %s\n", error->message);
236                                 g_error_free(error);
237                                 }
238                         else
239                                 {
240                                 g_free(text);
241                                 text = g_strdup(tmp);
242                                 }
243                         }
244                 }
245
246         if (subsec)
247                 {
248                 tmp = text;
249                 text = g_strconcat(tmp, ".", subsec, NULL);
250                 g_free(tmp);
251                 g_free(subsec);
252                 }
253         return text;
254 }
255
256 static gchar *exif_build_formatted_DateTimeDigitized(ExifData *exif)
257 {
258         gchar *text = exif_get_data_as_text(exif, "Exif.Photo.DateTimeDigitized");
259         gchar *subsec = NULL;
260         gchar buf[128];
261         gchar *tmp;
262         gint buflen;
263         struct tm tm;
264         GError *error = NULL;
265
266         if (text)
267                 {
268                 subsec = exif_get_data_as_text(exif, "Exif.Photo.SubSecTimeDigitized");
269                 }
270         else
271                 {
272                 text = exif_get_data_as_text(exif, "Exif.Image.DateTime");
273                 if (text) subsec = exif_get_data_as_text(exif, "Exif.Photo.SubSecTime");
274                 }
275
276         /* Convert the stuff into a tm struct */
277         memset(&tm, 0, sizeof(tm)); /* Uh, strptime could let garbage in tm! */
278         if (text && strptime(text, "%Y:%m:%d %H:%M:%S", &tm))
279                 {
280                 buflen = strftime(buf, sizeof(buf), "%x %X", &tm);
281                 if (buflen > 0)
282                         {
283                         tmp = g_locale_to_utf8(buf, buflen, NULL, NULL, &error);
284                         if (error)
285                                 {
286                                 log_printf("Error converting locale strftime to UTF-8: %s\n", error->message);
287                                 g_error_free(error);
288                                 }
289                         else
290                                 {
291                                 g_free(text);
292                                 text = g_strdup(tmp);
293                                 }
294                         }
295                 }
296
297         if (subsec)
298                 {
299                 tmp = text;
300                 text = g_strconcat(tmp, ".", subsec, NULL);
301                 g_free(tmp);
302                 g_free(subsec);
303                 }
304         return text;
305 }
306
307 static gchar *exif_build_formatted_ShutterSpeed(ExifData *exif)
308 {
309         ExifRational *r;
310
311         r = exif_get_rational(exif, "Exif.Photo.ExposureTime", NULL);
312         if (r && r->num && r->den)
313                 {
314                 gdouble n = (gdouble)r->den / (gdouble)r->num;
315                 return g_strdup_printf("%s%.0fs", n > 1.0 ? "1/" : "",
316                                                   n > 1.0 ? n : 1.0 / n);
317                 }
318         r = exif_get_rational(exif, "Exif.Photo.ShutterSpeedValue", NULL);
319         if (r && r->num  && r->den)
320                 {
321                 gdouble n = pow(2.0, exif_rational_to_double(r, TRUE));
322
323                 /* Correct exposure time to avoid values like 1/91s (seen on Minolta DImage 7) */
324                 if (n > 1.0 && (gint)n - ((gint)(n/10))*10 == 1) n--;
325
326                 return g_strdup_printf("%s%.0fs", n > 1.0 ? "1/" : "",
327                                                   n > 1.0 ? floor(n) : 1.0 / n);
328                 }
329         return NULL;
330 }
331
332 static gchar *exif_build_formatted_Aperture(ExifData *exif)
333 {
334         gdouble n;
335
336         n = exif_get_rational_as_double(exif, "Exif.Photo.FNumber");
337         if (n == 0.0) n = exif_get_rational_as_double(exif, "Exif.Photo.ApertureValue");
338         if (n == 0.0) return NULL;
339
340         return g_strdup_printf("f/%.1f", n);
341 }
342
343 static gchar *exif_build_formatted_ExposureBias(ExifData *exif)
344 {
345         ExifRational *r;
346         gint sign;
347         gdouble n;
348
349         r = exif_get_rational(exif, "Exif.Photo.ExposureBiasValue", &sign);
350         if (!r) return NULL;
351
352         n = exif_rational_to_double(r, sign);
353         return g_strdup_printf("%+.1f", n);
354 }
355
356 static gchar *exif_build_formatted_FocalLength(ExifData *exif)
357 {
358         gdouble n;
359
360         n = exif_get_rational_as_double(exif, "Exif.Photo.FocalLength");
361         if (n == 0.0) return NULL;
362         return g_strdup_printf("%.0f mm", n);
363 }
364
365 static gchar *exif_build_formatted_FocalLength35mmFilm(ExifData *exif)
366 {
367         gint n;
368         gdouble f, c;
369
370         if (exif_get_integer(exif, "Exif.Photo.FocalLengthIn35mmFilm", &n) && n != 0)
371                 {
372                 return g_strdup_printf("%d mm", n);
373                 }
374
375         f = exif_get_rational_as_double(exif, "Exif.Photo.FocalLength");
376         if (f == 0.0) return NULL;
377
378         c = get_crop_factor(exif);
379         if (c == 0.0) return NULL;
380
381         return g_strdup_printf("%.0f mm", f * c);
382 }
383
384 static gchar *exif_build_formatted_ISOSpeedRating(ExifData *exif)
385 {
386         gchar *text;
387
388         text = exif_get_data_as_text(exif, "Exif.Photo.ISOSpeedRatings");
389         /* old canon may set this instead */
390         if (!text) text = exif_get_data_as_text(exif, "Exif.CanonSi.ISOSpeed");
391         /* kodak may set this instead */
392         if (!text) text = exif_get_data_as_text(exif, "Exif.Photo.ExposureIndex");
393         return text;
394 }
395
396 static gchar *exif_build_formatted_SubjectDistance(ExifData *exif)
397 {
398         ExifRational *r;
399         gint sign;
400         gdouble n;
401
402         r = exif_get_rational(exif, "Exif.Photo.SubjectDistance", &sign);
403         if (!r) return NULL;
404
405         if ((glong)r->num == (glong)0xffffffff) return g_strdup(_("infinity"));
406         if ((glong)r->num == 0) return g_strdup(_("unknown"));
407
408         n = exif_rational_to_double(r, sign);
409         if (n == 0.0) return _("unknown");
410         return g_strdup_printf("%.3f m", n);
411 }
412
413 static gchar *exif_build_formatted_Flash(ExifData *exif)
414 {
415         /* grr, flash is a bitmask... */
416         GString *string;
417         gchar *text;
418         gint n;
419         gint v;
420
421         if (!exif_get_integer(exif, "Exif.Photo.Flash", &n)) return NULL;
422
423         /* Exif 2.1 only defines first 3 bits */
424         if (n <= 0x07) return exif_get_data_as_text(exif, "Exif.Photo.Flash");
425
426         /* must be Exif 2.2 */
427         string = g_string_new("");
428
429         /* flash fired (bit 0) */
430         string = g_string_append(string, (n & 0x01) ? _("yes") : _("no"));
431
432         /* flash mode (bits 3, 4) */
433         v = (n >> 3) & 0x03;
434         if (v) string = append_comma_text(string, _("mode:"));
435         switch (v)
436                 {
437                 case 1:
438                         string = g_string_append(string, _("on"));
439                         break;
440                 case 2:
441                         string = g_string_append(string, _("off"));
442                         break;
443                 case 3:
444                         string = g_string_append(string, _("auto"));
445                         break;
446                 }
447
448         /* return light (bits 1, 2) */
449         v = (n >> 1) & 0x03;
450         if (v == 2) string = append_comma_text(string, _("not detected by strobe"));
451         if (v == 3) string = append_comma_text(string, _("detected by strobe"));
452
453         /* we ignore flash function (bit 5) */
454
455         /* red-eye (bit 6) */
456         if ((n >> 5) & 0x01) string = append_comma_text(string, _("red-eye reduction"));
457
458         text = string->str;
459         g_string_free(string, FALSE);
460         return text;
461 }
462
463 static gchar *exif_build_formatted_Resolution(ExifData *exif)
464 {
465         ExifRational *rx, *ry;
466         gchar *units;
467         gchar *text;
468
469         rx = exif_get_rational(exif, "Exif.Image.XResolution", NULL);
470         ry = exif_get_rational(exif, "Exif.Image.YResolution", NULL);
471         if (!rx || !ry) return NULL;
472
473         units = exif_get_data_as_text(exif, "Exif.Image.ResolutionUnit");
474         text = g_strdup_printf("%0.f x %0.f (%s/%s)", rx->den ? (gdouble)rx->num / rx->den : 1.0,
475                                                       ry->den ? (gdouble)ry->num / ry->den : 1.0,
476                                                       _("dot"), (units) ? units : _("unknown"));
477
478         g_free(units);
479         return text;
480 }
481
482 static gchar *exif_build_formatted_ColorProfile(ExifData *exif)
483 {
484 #ifdef HAVE_LCMS2
485         cmsUInt8Number profileID[17];
486 #endif
487         const gchar *name = "";
488         const gchar *source = "";
489         guchar *profile_data;
490         guint profile_len;
491
492         profile_data = exif_get_color_profile(exif, &profile_len);
493         if (!profile_data)
494                 {
495                 gint cs;
496                 gchar *interop_index;
497
498                 /* ColorSpace == 1 specifies sRGB per EXIF 2.2 */
499                 if (!exif_get_integer(exif, "Exif.Photo.ColorSpace", &cs)) cs = 0;
500                 interop_index = exif_get_data_as_text(exif, "Exif.Iop.InteroperabilityIndex");
501
502                 if (cs == 1)
503                         {
504                         name = _("sRGB");
505                         source = "ColorSpace";
506                         }
507                 else if (cs == 2 || (interop_index && !strcmp(interop_index, "R03")))
508                         {
509                         name = _("AdobeRGB");
510                         source = (cs == 2) ? "ColorSpace" : "Iop";
511                         }
512
513                 g_free(interop_index);
514                 }
515         else
516                 {
517                 source = _("embedded");
518 #ifdef HAVE_LCMS
519
520                         {
521                         cmsHPROFILE profile;
522
523                         profile = cmsOpenProfileFromMem(profile_data, profile_len);
524                         if (profile)
525                                 {
526 #ifdef HAVE_LCMS2
527                                 profileID[16] = '\0';
528                                 cmsGetHeaderProfileID(profile, profileID);
529                                 name = (gchar *) profileID;
530 #else
531                                 name = (gchar *) cmsTakeProductName(profile);
532 #endif
533                                 cmsCloseProfile(profile);
534                                 }
535                         g_free(profile_data);
536                         }
537 #endif
538                 }
539         if (name[0] == 0 && source[0] == 0) return NULL;
540         return g_strdup_printf("%s (%s)", name, source);
541 }
542
543 static gchar *exif_build_formatted_GPSPosition(ExifData *exif)
544 {
545         GString *string;
546         gchar *text, *ref;
547         ExifRational *value;
548         ExifItem *item;
549         guint i;
550         gdouble p, p3;
551         gulong p1, p2;
552
553         string = g_string_new("");
554
555         item = exif_get_item(exif, "Exif.GPSInfo.GPSLatitude");
556         ref = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLatitudeRef");
557         if (item && ref)
558                 {
559                 p = 0;
560                 for (i = 0; i < exif_item_get_elements(item); i++)
561                         {
562                         value = exif_item_get_rational(item, NULL, i);
563                         if (value && value->num && value->den)
564                                 p += (gdouble)value->num / (gdouble)value->den / pow(60.0, (gdouble)i);
565                         }
566                 p1 = (gint)p;
567                 p2 = (gint)((p - p1)*60);
568                 p3 = ((p - p1)*60 - p2)*60;
569
570                 g_string_append_printf(string, "%0lu° %0lu' %0.2f\" %.1s", p1, p2, p3, ref);
571                 } // if (item && ref)
572
573         item = exif_get_item(exif, "Exif.GPSInfo.GPSLongitude");
574         ref = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLongitudeRef");
575         if (item && ref)
576                 {
577                 p = 0;
578                 for (i = 0; i < exif_item_get_elements(item); i++)
579                         {
580                         value = exif_item_get_rational(item, NULL, i);
581                         if (value && value->num && value->den)
582                         p += (gdouble)value->num / (gdouble)value->den / pow(60.0, (gdouble)i);
583                         }
584                 p1 = (gint)p;
585                 p2 = (gint)((p - p1)*60);
586                 p3 = ((p - p1)*60 - p2)*60;
587
588                 g_string_append_printf(string, ", %0lu° %0lu' %0.2f\" %.1s", p1, p2, p3, ref);
589                 } // if (item && ref)
590
591         text = string->str;
592         g_string_free(string, FALSE);
593
594         return text;
595 } // static gchar *exif_build_forma...
596
597 static gchar *exif_build_formatted_GPSAltitude(ExifData *exif)
598 {
599         ExifRational *r;
600         ExifItem *item;
601         gdouble alt;
602         gint ref;
603
604         item = exif_get_item(exif, "Exif.GPSInfo.GPSAltitudeRef");
605         r = exif_get_rational(exif, "Exif.GPSInfo.GPSAltitude", NULL);
606
607         if (!r || !item) return NULL;
608
609         alt = exif_rational_to_double(r, 0);
610         exif_item_get_integer(item, &ref);
611
612         return g_strdup_printf("%0.f m %s", alt, (ref==0)?_("Above Sea Level"):_("Below Sea Level"));
613 }
614
615 /**
616  * @brief Extracts timezone data from a ZoneDetect search structure
617  * @param[in] results ZoneDetect search structure
618  * @param[out] timezone in the form "Europe/London"
619  * @param[out] countryname in the form "United Kingdom"
620  * @param[out] countryalpha2 in the form "GB"
621  * 
622  * Refer to https://github.com/BertoldVdb/ZoneDetect
623  * for structure details
624  */
625 static void zd_tz(ZoneDetectResult *results, gchar **timezone, gchar **countryname, gchar **countryalpha2)
626 {
627         gchar *timezone_pre = NULL;
628         gchar *timezone_id = NULL;
629         unsigned int index = 0;
630
631         while(results[index].lookupResult != ZD_LOOKUP_END)
632                 {
633                 if(results[index].data)
634                         {
635                         for(unsigned int i=0; i<results[index].numFields; i++)
636                                 {
637                                 if (g_strstr_len(results[index].fieldNames[i], -1, "TimezoneIdPrefix"))
638                                         {
639                                         timezone_pre = g_strdup(results[index].data[i]);
640                                         }
641                                 if (g_strstr_len(results[index].fieldNames[i], -1, "TimezoneId"))
642                                         {
643                                         timezone_id = g_strdup(results[index].data[i]);
644                                         }
645                                 if (g_strstr_len(results[index].fieldNames[i], -1, "CountryName"))
646                                         {
647                                         *countryname = g_strdup(results[index].data[i]);
648                                         }
649                                 if (g_strstr_len(results[index].fieldNames[i], -1, "CountryAlpha2"))
650                                         {
651                                         *countryalpha2 = g_strdup(results[index].data[i]);
652                                         }
653                                 }
654                         }
655                 index++;
656                 }
657
658         *timezone = g_strconcat(timezone_pre, timezone_id, NULL);
659         g_free(timezone_pre);
660         g_free(timezone_id);
661 }
662
663 /**
664  * @brief Gets timezone data from an exif structure
665  * @param[in] exif
666  * @returns TRUE if timezone data found AND GPS date and time found
667  * @param[out] exif_date_time exif date/time in the form 2018:11:30:17:05:04
668  * @param[out] timezone in the form "Europe/London"
669  * @param[out] countryname in the form "United Kingdom"
670  * @param[out] countryalpha2 in the form "GB"
671  *
672  *
673  */
674 static gboolean exif_build_tz_data(ExifData *exif, gchar **exif_date_time, gchar **timezone, gchar **countryname, gchar **countryalpha2)
675 {
676         gfloat latitude;
677         gfloat longitude;
678         gchar *text_latitude;
679         gchar *text_longitude;
680         gchar *text_latitude_ref;
681         gchar *text_longitude_ref;
682         gchar *text_date;
683         gchar *text_time;
684         gchar *lat_deg;
685         gchar *lat_min;
686         gchar *lon_deg;
687         gchar *lon_min;
688         gchar *timezone_path;
689         ZoneDetect *cd;
690         ZoneDetectResult *results;
691         gboolean ret = FALSE;
692         gchar *basename;
693         gchar *path;
694
695         text_latitude = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLatitude");
696         text_longitude = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLongitude");
697         text_latitude_ref = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLatitudeRef");
698         text_longitude_ref = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLongitudeRef");
699         text_date = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSDateStamp");
700         text_time = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSTimeStamp");
701
702         if (text_latitude && text_longitude && text_latitude_ref && text_longitude_ref)
703                 {
704                 lat_deg = strtok(text_latitude, "deg'");
705                 lat_min = strtok(NULL, "deg'");
706                 latitude = atof(lat_deg) + atof(lat_min) / 60;
707                 if (!g_strcmp0(text_latitude_ref, "South"))
708                         {
709                         latitude = -latitude;
710                         }
711                 lon_deg = strtok(text_longitude, "deg'");
712                 lon_min = strtok(NULL, "deg'");
713                 longitude = atof(lon_deg) + atof(lon_min) / 60;
714                 if (!g_strcmp0(text_longitude_ref, "West"))
715                         {
716                         longitude = -longitude;
717                         }
718
719                 path = path_from_utf8(TIMEZONE_DATABASE);
720                 basename = g_path_get_basename(path);
721                 timezone_path = g_build_filename(get_rc_dir(), basename, NULL);
722                 if (g_file_test(timezone_path, G_FILE_TEST_EXISTS))
723                         {
724                         cd = ZDOpenDatabase(timezone_path);
725                         if (cd)
726                                 {
727                                 results = ZDLookup(cd, latitude, longitude, NULL);
728                                 if (results)
729                                         {
730                                         zd_tz(results, timezone, countryname, countryalpha2);
731                                         ret = TRUE;
732                                         }
733                                 }
734                         else
735                                 {
736                                 log_printf("Error: Init of timezone database %s failed\n", timezone_path);
737                                 }
738                         ZDCloseDatabase(cd);
739                         }
740                 g_free(path);
741                 g_free(timezone_path);
742                 g_free(basename);
743                 }
744
745         if (ret && text_date && text_time)
746                 {
747                 *exif_date_time = g_strconcat(text_date, ":", text_time, NULL);
748                 }
749         else
750                 {
751                 ret = FALSE;
752                 }
753         return ret;
754 }
755
756 /**
757  * @brief Creates local time from GPS lat/long
758  * @param[in] exif
759  * @returns Localised time and date
760  *
761  * GPS lat/long is translated to timezone using ZoneDetect.
762  * GPS UTC is converted to Unix time stamp (seconds since 1970).
763  * The TZ environment variable is set to the relevant timezone
764  * and the Unix timestamp converted to local time using locale.
765  * If the conversion fails, unformatted UTC is returned.
766  */
767 static gchar *exif_build_formatted_localtime(ExifData *exif)
768 {
769         gchar buf[128];
770         gchar *tmp;
771         gint buflen;
772         GError *error = NULL;
773         gchar *time_zone_image;
774         gchar *time_zone_org;
775         struct tm *tm_local;
776         struct tm tm_utc;
777         time_t stamp;
778         gchar *exif_date_time = NULL;
779         gchar *timezone = NULL;
780         gchar *countryname = NULL;
781         gchar *countryalpha2 = NULL;
782
783         if (exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2))
784                 {
785                 time_zone_image = g_strconcat("TZ=", timezone, NULL);
786                 time_zone_org = g_strconcat("TZ=", getenv("TZ"), NULL);
787                 putenv("TZ=UTC");
788
789                 memset(&tm_utc, 0, sizeof(tm_utc));
790                 if (exif_date_time && strptime(exif_date_time, "%Y:%m:%d:%H:%M:%S", &tm_utc))
791                         {
792                         stamp = mktime(&tm_utc);        // Convert the struct to a Unix timestamp
793                         putenv(time_zone_image);        // Switch to destination time zone
794
795                         tm_local = localtime(&stamp);
796
797                         /* Convert to localtime using locale */
798                         buflen = strftime(buf, sizeof(buf), "%x %X", tm_local);
799                         if (buflen > 0)
800                                 {
801                                 tmp = g_locale_to_utf8(buf, buflen, NULL, NULL, &error);
802                                 if (error)
803                                         {
804                                         log_printf("Error converting locale strftime to UTF-8: %s\n", error->message);
805                                         g_error_free(error);
806                                         }
807                                 else
808                                         {
809                                         g_free(exif_date_time);
810                                         exif_date_time = g_strdup(tmp);
811                                         }
812                                 }
813                                 g_free(tmp);
814                         }
815                 putenv(time_zone_org);
816
817                 g_free(time_zone_image);
818                 g_free(time_zone_org);
819                 }
820
821         g_free(timezone);
822         g_free(countryname);
823         g_free(countryalpha2);
824
825         return exif_date_time;
826 }
827
828 /**
829  * @brief Gets timezone from GPS lat/long
830  * @param[in] exif
831  * @returns Timezone string in the form "Europe/London"
832  *
833  *
834  */
835 static gchar *exif_build_formatted_timezone(ExifData *exif)
836 {
837         gchar *time_zone = NULL;
838         gchar *exif_date_time = NULL;
839         gchar *timezone = NULL;
840         gchar *countryname = NULL;
841         gchar *countryalpha2 = NULL;
842
843         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
844
845         g_free(exif_date_time);
846         g_free(countryname);
847         g_free(countryalpha2);
848
849         return timezone;
850 }
851
852 /**
853  * @brief Gets countryname from GPS lat/long
854  * @param[in] exif
855  * @returns Countryname string
856  *
857  *
858  */
859 static gchar *exif_build_formatted_countryname(ExifData *exif)
860 {
861         gchar *exif_date_time = NULL;
862         gchar *timezone = NULL;
863         gchar *countryname = NULL;
864         gchar *countryalpha2 = NULL;
865
866         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
867
868         g_free(exif_date_time);
869         g_free(timezone);
870         g_free(countryalpha2);
871
872         return countryname;
873 }
874
875 /**
876  * @brief Gets two-letter country code from GPS lat/long
877  * @param[in] exif
878  * @returns Countryalpha2 string
879  *
880  *
881  */
882 static gchar *exif_build_formatted_countrycode(ExifData *exif)
883 {
884         gchar *exif_date_time = NULL;
885         gchar *timezone = NULL;
886         gchar *countryname = NULL;
887         gchar *countryalpha2 = NULL;
888
889         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
890
891         g_free(exif_date_time);
892         g_free(timezone);
893         g_free(countryname);
894
895         return countryalpha2;
896 }
897
898 static gchar *exif_build_formatted_star_rating(ExifData *exif)
899 {
900         gint n = 0;
901
902         exif_get_integer(exif, "Xmp.xmp.Rating", &n);
903
904         return convert_rating_to_stars(n);
905 }
906
907 /* List of custom formatted pseudo-exif tags */
908 #define EXIF_FORMATTED_TAG(name, label) { EXIF_FORMATTED()#name, label, exif_build_formatted##_##name }
909
910 ExifFormattedText ExifFormattedList[] = {
911         EXIF_FORMATTED_TAG(Camera,              N_("Camera")),
912         EXIF_FORMATTED_TAG(DateTime,            N_("Date")),
913         EXIF_FORMATTED_TAG(DateTimeDigitized,   N_("DateDigitized")),
914         EXIF_FORMATTED_TAG(ShutterSpeed,        N_("Shutter speed")),
915         EXIF_FORMATTED_TAG(Aperture,            N_("Aperture")),
916         EXIF_FORMATTED_TAG(ExposureBias,        N_("Exposure bias")),
917         EXIF_FORMATTED_TAG(ISOSpeedRating,      N_("ISO sensitivity")),
918         EXIF_FORMATTED_TAG(FocalLength,         N_("Focal length")),
919         EXIF_FORMATTED_TAG(FocalLength35mmFilm, N_("Focal length 35mm")),
920         EXIF_FORMATTED_TAG(SubjectDistance,     N_("Subject distance")),
921         EXIF_FORMATTED_TAG(Flash,               N_("Flash")),
922         EXIF_FORMATTED_TAG(Resolution,          N_("Resolution")),
923         EXIF_FORMATTED_TAG(ColorProfile,        N_("Color profile")),
924         EXIF_FORMATTED_TAG(GPSPosition,         N_("GPS position")),
925         EXIF_FORMATTED_TAG(GPSAltitude,         N_("GPS altitude")),
926         EXIF_FORMATTED_TAG(localtime,           N_("Local time")),
927         EXIF_FORMATTED_TAG(timezone,            N_("Time zone")),
928         EXIF_FORMATTED_TAG(countryname,         N_("Country name")),
929         EXIF_FORMATTED_TAG(countrycode,         N_("Country code")),
930         EXIF_FORMATTED_TAG(star_rating,         N_("Star rating")),
931         {"file.size",                           N_("File size"),        NULL},
932         {"file.date",                           N_("File date"),        NULL},
933         {"file.mode",                           N_("File mode"),        NULL},
934         {"file.ctime",                          N_("File ctime"),       NULL},
935         {"file.owner",                          N_("File owner"),       NULL},
936         {"file.group",                          N_("File group"),       NULL},
937         {"file.link",                           N_("File link"),        NULL},
938         {"file.class",                          N_("File class"),       NULL},
939         { NULL, NULL, NULL }
940 };
941
942 gchar *exif_get_formatted_by_key(ExifData *exif, const gchar *key, gboolean *key_valid)
943 {
944         if (strncmp(key, EXIF_FORMATTED(), EXIF_FORMATTED_LEN) == 0)
945                 {
946                 gint i;
947
948                 if (key_valid) *key_valid = TRUE;
949
950                 key += EXIF_FORMATTED_LEN;
951                 for (i = 0; ExifFormattedList[i].key; i++)
952                         if (ExifFormattedList[i].build_func && strcmp(key, ExifFormattedList[i].key + EXIF_FORMATTED_LEN) == 0)
953                                 return ExifFormattedList[i].build_func(exif);
954                 }
955
956         if (key_valid) *key_valid = FALSE;
957         return NULL;
958 }
959
960 gchar *exif_get_description_by_key(const gchar *key)
961 {
962         if (!key) return NULL;
963
964         if (strncmp(key, EXIF_FORMATTED(), EXIF_FORMATTED_LEN) == 0 ||
965             strncmp(key, "file.", 5) == 0)
966                 {
967                 gint i;
968
969                 for (i = 0; ExifFormattedList[i].key; i++)
970                         if (strcmp(key, ExifFormattedList[i].key) == 0)
971                                 return g_strdup(_(ExifFormattedList[i].description));
972                 }
973
974         return exif_get_tag_description_by_key(key);
975 }
976
977 gint exif_get_integer(ExifData *exif, const gchar *key, gint *value)
978 {
979         ExifItem *item;
980
981         item = exif_get_item(exif, key);
982         return exif_item_get_integer(item, value);
983 }
984
985 ExifRational *exif_get_rational(ExifData *exif, const gchar *key, gint *sign)
986 {
987         ExifItem *item;
988
989         item = exif_get_item(exif, key);
990         return exif_item_get_rational(item, sign, 0);
991 }
992
993 gchar *exif_get_data_as_text(ExifData *exif, const gchar *key)
994 {
995         ExifItem *item;
996         gchar *text;
997         gboolean key_valid;
998
999         if (!key) return NULL;
1000
1001         text = exif_get_formatted_by_key(exif, key, &key_valid);
1002         if (key_valid) return text;
1003
1004         item = exif_get_item(exif, key);
1005         if (item) return exif_item_get_data_as_text(item);
1006
1007         return NULL;
1008 }
1009
1010
1011 static FileCacheData *exif_cache;
1012
1013 void exif_release_cb(FileData *fd)
1014 {
1015         exif_free(fd->exif);
1016         fd->exif = NULL;
1017 }
1018
1019 void exif_init_cache(void)
1020 {
1021         g_assert(!exif_cache);
1022         exif_cache = file_cache_new(exif_release_cb, 4);
1023 }
1024
1025 ExifData *exif_read_fd(FileData *fd)
1026 {
1027         gchar *sidecar_path;
1028
1029         if (!exif_cache) exif_init_cache();
1030
1031         if (!fd) return NULL;
1032
1033         if (file_cache_get(exif_cache, fd)) return fd->exif;
1034         g_assert(fd->exif == NULL);
1035
1036         /* CACHE_TYPE_XMP_METADATA file should exist only if the metadata are
1037          * not writable directly, thus it should contain the most up-to-date version */
1038         sidecar_path = NULL;
1039
1040 #ifdef HAVE_EXIV2
1041         /* we are not able to handle XMP sidecars without exiv2 */
1042         sidecar_path = cache_find_location(CACHE_TYPE_XMP_METADATA, fd->path);
1043
1044         if (!sidecar_path) sidecar_path = file_data_get_sidecar_path(fd, TRUE);
1045 #endif
1046
1047         fd->exif = exif_read(fd->path, sidecar_path, fd->modified_xmp);
1048
1049         g_free(sidecar_path);
1050         file_cache_put(exif_cache, fd, 1);
1051         return fd->exif;
1052 }
1053
1054
1055 void exif_free_fd(FileData *fd, ExifData *exif)
1056 {
1057         if (!fd) return;
1058         g_assert(fd->exif == exif);
1059 }
1060
1061 /* embedded icc in jpeg */
1062
1063 gboolean exif_jpeg_parse_color(ExifData *exif, guchar *data, guint size)
1064 {
1065         guint seg_offset = 0;
1066         guint seg_length = 0;
1067         guint chunk_offset[255];
1068         guint chunk_length[255];
1069         guint chunk_count = 0;
1070
1071         /* For jpeg/jfif, ICC color profile data can be in more than one segment.
1072            the data is in APP2 data segments that start with "ICC_PROFILE\x00\xNN\xTT"
1073            NN = segment number for data
1074            TT = total number of ICC segments (TT in each ICC segment should match)
1075          */
1076
1077         while (jpeg_segment_find(data + seg_offset + seg_length,
1078                                       size - seg_offset - seg_length,
1079                                       JPEG_MARKER_APP2,
1080                                       "ICC_PROFILE\x00", 12,
1081                                       &seg_offset, &seg_length))
1082                 {
1083                 guchar chunk_num;
1084                 guchar chunk_tot;
1085
1086                 if (seg_length < 14) return FALSE;
1087
1088                 chunk_num = data[seg_offset + 12];
1089                 chunk_tot = data[seg_offset + 13];
1090
1091                 if (chunk_num == 0 || chunk_tot == 0) return FALSE;
1092
1093                 if (chunk_count == 0)
1094                         {
1095                         guint i;
1096
1097                         chunk_count = (guint)chunk_tot;
1098                         for (i = 0; i < chunk_count; i++) chunk_offset[i] = 0;
1099                         for (i = 0; i < chunk_count; i++) chunk_length[i] = 0;
1100                         }
1101
1102                 if (chunk_tot != chunk_count ||
1103                     chunk_num > chunk_count) return FALSE;
1104
1105                 chunk_num--;
1106                 chunk_offset[chunk_num] = seg_offset + 14;
1107                 chunk_length[chunk_num] = seg_length - 14;
1108                 }
1109
1110         if (chunk_count > 0)
1111                 {
1112                 guchar *cp_data;
1113                 guint cp_length = 0;
1114                 guint i;
1115
1116                 for (i = 0; i < chunk_count; i++) cp_length += chunk_length[i];
1117                 cp_data = g_malloc(cp_length);
1118
1119                 for (i = 0; i < chunk_count; i++)
1120                         {
1121                         if (chunk_offset[i] == 0)
1122                                 {
1123                                 /* error, we never saw this chunk */
1124                                 g_free(cp_data);
1125                                 return FALSE;
1126                                 }
1127                         memcpy(cp_data, data + chunk_offset[i], chunk_length[i]);
1128                         }
1129                 DEBUG_1("Found embedded icc profile in jpeg");
1130                 exif_add_jpeg_color_profile(exif, cp_data, cp_length);
1131
1132                 return TRUE;
1133                 }
1134
1135         return FALSE;
1136 }
1137
1138 /*
1139  *-------------------------------------------------------------------
1140  * file info
1141  * it is here because it shares tag neming infrastructure with exif
1142  * we should probably not invest too much effort into this because
1143  * new exiv2 will support the same functionality
1144  * http://dev.exiv2.org/issues/show/505
1145  *-------------------------------------------------------------------
1146  */
1147
1148 static gchar *mode_number(mode_t m)
1149 {
1150         gint mb, mu, mg, mo;
1151         gchar pbuf[12];
1152
1153         mb = mu = mg = mo = 0;
1154
1155         if (m & S_ISUID) mb |= 4;
1156         if (m & S_ISGID) mb |= 2;
1157         if (m & S_ISVTX) mb |= 1;
1158
1159         if (m & S_IRUSR) mu |= 4;
1160         if (m & S_IWUSR) mu |= 2;
1161         if (m & S_IXUSR) mu |= 1;
1162
1163         if (m & S_IRGRP) mg |= 4;
1164         if (m & S_IWGRP) mg |= 2;
1165         if (m & S_IXGRP) mg |= 1;
1166
1167         if (m & S_IROTH) mo |= 4;
1168         if (m & S_IWOTH) mo |= 2;
1169         if (m & S_IXOTH) mo |= 1;
1170
1171         pbuf[0] = (m & S_IRUSR) ? 'r' : '-';
1172         pbuf[1] = (m & S_IWUSR) ? 'w' : '-';
1173         pbuf[2] = (m & S_IXUSR) ? 'x' : '-';
1174         pbuf[3] = (m & S_IRGRP) ? 'r' : '-';
1175         pbuf[4] = (m & S_IWGRP) ? 'w' : '-';
1176         pbuf[5] = (m & S_IXGRP) ? 'x' : '-';
1177         pbuf[6] = (m & S_IROTH) ? 'r' : '-';
1178         pbuf[7] = (m & S_IWOTH) ? 'w' : '-';
1179         pbuf[8] = (m & S_IXOTH) ? 'x' : '-';
1180         pbuf[9] = '\0';
1181
1182         return g_strdup_printf("%s (%d%d%d%d)", pbuf, mb, mu, mg, mo);
1183 }
1184
1185 gchar *metadata_file_info(FileData *fd, const gchar *key, MetadataFormat format)
1186 {
1187         if (strcmp(key, "file.size") == 0)
1188                 {
1189                 return g_strdup_printf("%ld", (long)fd->size);
1190                 }
1191         if (strcmp(key, "file.date") == 0)
1192                 {
1193                 return g_strdup(text_from_time(fd->date));
1194                 }
1195         if (strcmp(key, "file.mode") == 0)
1196                 {
1197                 return mode_number(fd->mode);
1198                 }
1199         if (strcmp(key, "file.ctime") == 0)
1200                 {
1201                 return g_strdup(text_from_time(fd->cdate));
1202                 }
1203         if (strcmp(key, "file.class") == 0)
1204                 {
1205                 return g_strdup(format_class_list[fd->format_class]);
1206                 }
1207         if (strcmp(key, "file.owner") == 0)
1208                 {
1209                 return g_strdup(fd->owner);
1210                 }
1211         if (strcmp(key, "file.group") == 0)
1212                 {
1213                 return g_strdup(fd->group);
1214                 }
1215         if (strcmp(key, "file.link") == 0)
1216                 {
1217                 return g_strdup(fd->sym_link);
1218                 }
1219         return g_strdup("");
1220 }
1221
1222 #ifdef HAVE_LUA
1223 gchar *metadata_lua_info(FileData *fd, const gchar *key, MetadataFormat format)
1224 {
1225         gchar *script_name;
1226         gchar *script_name_utf8;
1227         gchar *data;
1228         gchar *raw_data;
1229         gchar *valid_data;
1230
1231         script_name_utf8 = g_strdup(key + 4);
1232         script_name = path_from_utf8(script_name_utf8);
1233
1234         raw_data = lua_callvalue(fd, script_name, NULL);
1235         valid_data = g_utf8_make_valid(raw_data, -1);
1236         data = g_utf8_substring(valid_data, 0, 150);
1237
1238         g_free(script_name);
1239         g_free(script_name_utf8);
1240         g_free(raw_data);
1241         g_free(valid_data);
1242
1243         return data;
1244 }
1245 #endif
1246 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */