Bug fix: Compute TimeZone data
[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                 if (!lat_deg || !lat_min)
707                         {
708                         return FALSE;
709                         }
710                 latitude = atof(lat_deg) + atof(lat_min) / 60;
711                 if (!g_strcmp0(text_latitude_ref, "South"))
712                         {
713                         latitude = -latitude;
714                         }
715                 lon_deg = strtok(text_longitude, "deg'");
716                 lon_min = strtok(NULL, "deg'");
717                 if (!lon_deg || !lon_min)
718                         {
719                         return FALSE;
720                         }
721                 longitude = atof(lon_deg) + atof(lon_min) / 60;
722                 if (!g_strcmp0(text_longitude_ref, "West"))
723                         {
724                         longitude = -longitude;
725                         }
726
727                 path = path_from_utf8(TIMEZONE_DATABASE);
728                 basename = g_path_get_basename(path);
729                 timezone_path = g_build_filename(get_rc_dir(), basename, NULL);
730                 if (g_file_test(timezone_path, G_FILE_TEST_EXISTS))
731                         {
732                         cd = ZDOpenDatabase(timezone_path);
733                         if (cd)
734                                 {
735                                 results = ZDLookup(cd, latitude, longitude, NULL);
736                                 if (results)
737                                         {
738                                         zd_tz(results, timezone, countryname, countryalpha2);
739                                         ret = TRUE;
740                                         }
741                                 }
742                         else
743                                 {
744                                 log_printf("Error: Init of timezone database %s failed\n", timezone_path);
745                                 }
746                         ZDCloseDatabase(cd);
747                         }
748                 g_free(path);
749                 g_free(timezone_path);
750                 g_free(basename);
751                 }
752
753         if (ret && text_date && text_time)
754                 {
755                 *exif_date_time = g_strconcat(text_date, ":", text_time, NULL);
756                 }
757         else
758                 {
759                 ret = FALSE;
760                 }
761         return ret;
762 }
763
764 /**
765  * @brief Creates local time from GPS lat/long
766  * @param[in] exif
767  * @returns Localised time and date
768  *
769  * GPS lat/long is translated to timezone using ZoneDetect.
770  * GPS UTC is converted to Unix time stamp (seconds since 1970).
771  * The TZ environment variable is set to the relevant timezone
772  * and the Unix timestamp converted to local time using locale.
773  * If the conversion fails, unformatted UTC is returned.
774  */
775 static gchar *exif_build_formatted_localtime(ExifData *exif)
776 {
777         gchar buf[128];
778         gchar *tmp;
779         gint buflen;
780         GError *error = NULL;
781         gchar *time_zone_image;
782         gchar *time_zone_org;
783         struct tm *tm_local;
784         struct tm tm_utc;
785         time_t stamp;
786         gchar *exif_date_time = NULL;
787         gchar *timezone = NULL;
788         gchar *countryname = NULL;
789         gchar *countryalpha2 = NULL;
790
791         if (exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2))
792                 {
793                 time_zone_image = g_strconcat("TZ=", timezone, NULL);
794                 time_zone_org = g_strconcat("TZ=", getenv("TZ"), NULL);
795                 putenv("TZ=UTC");
796
797                 memset(&tm_utc, 0, sizeof(tm_utc));
798                 if (exif_date_time && strptime(exif_date_time, "%Y:%m:%d:%H:%M:%S", &tm_utc))
799                         {
800                         stamp = mktime(&tm_utc);        // Convert the struct to a Unix timestamp
801                         putenv(time_zone_image);        // Switch to destination time zone
802
803                         tm_local = localtime(&stamp);
804
805                         /* Convert to localtime using locale */
806                         buflen = strftime(buf, sizeof(buf), "%x %X", tm_local);
807                         if (buflen > 0)
808                                 {
809                                 tmp = g_locale_to_utf8(buf, buflen, NULL, NULL, &error);
810                                 if (error)
811                                         {
812                                         log_printf("Error converting locale strftime to UTF-8: %s\n", error->message);
813                                         g_error_free(error);
814                                         }
815                                 else
816                                         {
817                                         g_free(exif_date_time);
818                                         exif_date_time = g_strdup(tmp);
819                                         }
820                                 }
821                                 g_free(tmp);
822                         }
823                 putenv(time_zone_org);
824
825                 g_free(time_zone_image);
826                 g_free(time_zone_org);
827                 }
828
829         g_free(timezone);
830         g_free(countryname);
831         g_free(countryalpha2);
832
833         return exif_date_time;
834 }
835
836 /**
837  * @brief Gets timezone from GPS lat/long
838  * @param[in] exif
839  * @returns Timezone string in the form "Europe/London"
840  *
841  *
842  */
843 static gchar *exif_build_formatted_timezone(ExifData *exif)
844 {
845         gchar *time_zone = NULL;
846         gchar *exif_date_time = NULL;
847         gchar *timezone = NULL;
848         gchar *countryname = NULL;
849         gchar *countryalpha2 = NULL;
850
851         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
852
853         g_free(exif_date_time);
854         g_free(countryname);
855         g_free(countryalpha2);
856
857         return timezone;
858 }
859
860 /**
861  * @brief Gets countryname from GPS lat/long
862  * @param[in] exif
863  * @returns Countryname string
864  *
865  *
866  */
867 static gchar *exif_build_formatted_countryname(ExifData *exif)
868 {
869         gchar *exif_date_time = NULL;
870         gchar *timezone = NULL;
871         gchar *countryname = NULL;
872         gchar *countryalpha2 = NULL;
873
874         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
875
876         g_free(exif_date_time);
877         g_free(timezone);
878         g_free(countryalpha2);
879
880         return countryname;
881 }
882
883 /**
884  * @brief Gets two-letter country code from GPS lat/long
885  * @param[in] exif
886  * @returns Countryalpha2 string
887  *
888  *
889  */
890 static gchar *exif_build_formatted_countrycode(ExifData *exif)
891 {
892         gchar *exif_date_time = NULL;
893         gchar *timezone = NULL;
894         gchar *countryname = NULL;
895         gchar *countryalpha2 = NULL;
896
897         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
898
899         g_free(exif_date_time);
900         g_free(timezone);
901         g_free(countryname);
902
903         return countryalpha2;
904 }
905
906 static gchar *exif_build_formatted_star_rating(ExifData *exif)
907 {
908         gint n = 0;
909
910         exif_get_integer(exif, "Xmp.xmp.Rating", &n);
911
912         return convert_rating_to_stars(n);
913 }
914
915 /* List of custom formatted pseudo-exif tags */
916 #define EXIF_FORMATTED_TAG(name, label) { EXIF_FORMATTED()#name, label, exif_build_formatted##_##name }
917
918 ExifFormattedText ExifFormattedList[] = {
919         EXIF_FORMATTED_TAG(Camera,              N_("Camera")),
920         EXIF_FORMATTED_TAG(DateTime,            N_("Date")),
921         EXIF_FORMATTED_TAG(DateTimeDigitized,   N_("DateDigitized")),
922         EXIF_FORMATTED_TAG(ShutterSpeed,        N_("Shutter speed")),
923         EXIF_FORMATTED_TAG(Aperture,            N_("Aperture")),
924         EXIF_FORMATTED_TAG(ExposureBias,        N_("Exposure bias")),
925         EXIF_FORMATTED_TAG(ISOSpeedRating,      N_("ISO sensitivity")),
926         EXIF_FORMATTED_TAG(FocalLength,         N_("Focal length")),
927         EXIF_FORMATTED_TAG(FocalLength35mmFilm, N_("Focal length 35mm")),
928         EXIF_FORMATTED_TAG(SubjectDistance,     N_("Subject distance")),
929         EXIF_FORMATTED_TAG(Flash,               N_("Flash")),
930         EXIF_FORMATTED_TAG(Resolution,          N_("Resolution")),
931         EXIF_FORMATTED_TAG(ColorProfile,        N_("Color profile")),
932         EXIF_FORMATTED_TAG(GPSPosition,         N_("GPS position")),
933         EXIF_FORMATTED_TAG(GPSAltitude,         N_("GPS altitude")),
934         EXIF_FORMATTED_TAG(localtime,           N_("Local time")),
935         EXIF_FORMATTED_TAG(timezone,            N_("Time zone")),
936         EXIF_FORMATTED_TAG(countryname,         N_("Country name")),
937         EXIF_FORMATTED_TAG(countrycode,         N_("Country code")),
938         EXIF_FORMATTED_TAG(star_rating,         N_("Star rating")),
939         {"file.size",                           N_("File size"),        NULL},
940         {"file.date",                           N_("File date"),        NULL},
941         {"file.mode",                           N_("File mode"),        NULL},
942         {"file.ctime",                          N_("File ctime"),       NULL},
943         {"file.owner",                          N_("File owner"),       NULL},
944         {"file.group",                          N_("File group"),       NULL},
945         {"file.link",                           N_("File link"),        NULL},
946         {"file.class",                          N_("File class"),       NULL},
947         { NULL, NULL, NULL }
948 };
949
950 gchar *exif_get_formatted_by_key(ExifData *exif, const gchar *key, gboolean *key_valid)
951 {
952         if (strncmp(key, EXIF_FORMATTED(), EXIF_FORMATTED_LEN) == 0)
953                 {
954                 gint i;
955
956                 if (key_valid) *key_valid = TRUE;
957
958                 key += EXIF_FORMATTED_LEN;
959                 for (i = 0; ExifFormattedList[i].key; i++)
960                         if (ExifFormattedList[i].build_func && strcmp(key, ExifFormattedList[i].key + EXIF_FORMATTED_LEN) == 0)
961                                 return ExifFormattedList[i].build_func(exif);
962                 }
963
964         if (key_valid) *key_valid = FALSE;
965         return NULL;
966 }
967
968 gchar *exif_get_description_by_key(const gchar *key)
969 {
970         if (!key) return NULL;
971
972         if (strncmp(key, EXIF_FORMATTED(), EXIF_FORMATTED_LEN) == 0 ||
973             strncmp(key, "file.", 5) == 0)
974                 {
975                 gint i;
976
977                 for (i = 0; ExifFormattedList[i].key; i++)
978                         if (strcmp(key, ExifFormattedList[i].key) == 0)
979                                 return g_strdup(_(ExifFormattedList[i].description));
980                 }
981
982         return exif_get_tag_description_by_key(key);
983 }
984
985 gint exif_get_integer(ExifData *exif, const gchar *key, gint *value)
986 {
987         ExifItem *item;
988
989         item = exif_get_item(exif, key);
990         return exif_item_get_integer(item, value);
991 }
992
993 ExifRational *exif_get_rational(ExifData *exif, const gchar *key, gint *sign)
994 {
995         ExifItem *item;
996
997         item = exif_get_item(exif, key);
998         return exif_item_get_rational(item, sign, 0);
999 }
1000
1001 gchar *exif_get_data_as_text(ExifData *exif, const gchar *key)
1002 {
1003         ExifItem *item;
1004         gchar *text;
1005         gboolean key_valid;
1006
1007         if (!key) return NULL;
1008
1009         text = exif_get_formatted_by_key(exif, key, &key_valid);
1010         if (key_valid) return text;
1011
1012         item = exif_get_item(exif, key);
1013         if (item) return exif_item_get_data_as_text(item);
1014
1015         return NULL;
1016 }
1017
1018
1019 static FileCacheData *exif_cache;
1020
1021 void exif_release_cb(FileData *fd)
1022 {
1023         exif_free(fd->exif);
1024         fd->exif = NULL;
1025 }
1026
1027 void exif_init_cache(void)
1028 {
1029         g_assert(!exif_cache);
1030         exif_cache = file_cache_new(exif_release_cb, 4);
1031 }
1032
1033 ExifData *exif_read_fd(FileData *fd)
1034 {
1035         gchar *sidecar_path;
1036
1037         if (!exif_cache) exif_init_cache();
1038
1039         if (!fd) return NULL;
1040
1041         if (file_cache_get(exif_cache, fd)) return fd->exif;
1042         g_assert(fd->exif == NULL);
1043
1044         /* CACHE_TYPE_XMP_METADATA file should exist only if the metadata are
1045          * not writable directly, thus it should contain the most up-to-date version */
1046         sidecar_path = NULL;
1047
1048 #ifdef HAVE_EXIV2
1049         /* we are not able to handle XMP sidecars without exiv2 */
1050         sidecar_path = cache_find_location(CACHE_TYPE_XMP_METADATA, fd->path);
1051
1052         if (!sidecar_path) sidecar_path = file_data_get_sidecar_path(fd, TRUE);
1053 #endif
1054
1055         fd->exif = exif_read(fd->path, sidecar_path, fd->modified_xmp);
1056
1057         g_free(sidecar_path);
1058         file_cache_put(exif_cache, fd, 1);
1059         return fd->exif;
1060 }
1061
1062
1063 void exif_free_fd(FileData *fd, ExifData *exif)
1064 {
1065         if (!fd) return;
1066         g_assert(fd->exif == exif);
1067 }
1068
1069 /* embedded icc in jpeg */
1070
1071 gboolean exif_jpeg_parse_color(ExifData *exif, guchar *data, guint size)
1072 {
1073         guint seg_offset = 0;
1074         guint seg_length = 0;
1075         guint chunk_offset[255];
1076         guint chunk_length[255];
1077         guint chunk_count = 0;
1078
1079         /* For jpeg/jfif, ICC color profile data can be in more than one segment.
1080            the data is in APP2 data segments that start with "ICC_PROFILE\x00\xNN\xTT"
1081            NN = segment number for data
1082            TT = total number of ICC segments (TT in each ICC segment should match)
1083          */
1084
1085         while (jpeg_segment_find(data + seg_offset + seg_length,
1086                                       size - seg_offset - seg_length,
1087                                       JPEG_MARKER_APP2,
1088                                       "ICC_PROFILE\x00", 12,
1089                                       &seg_offset, &seg_length))
1090                 {
1091                 guchar chunk_num;
1092                 guchar chunk_tot;
1093
1094                 if (seg_length < 14) return FALSE;
1095
1096                 chunk_num = data[seg_offset + 12];
1097                 chunk_tot = data[seg_offset + 13];
1098
1099                 if (chunk_num == 0 || chunk_tot == 0) return FALSE;
1100
1101                 if (chunk_count == 0)
1102                         {
1103                         guint i;
1104
1105                         chunk_count = (guint)chunk_tot;
1106                         for (i = 0; i < chunk_count; i++) chunk_offset[i] = 0;
1107                         for (i = 0; i < chunk_count; i++) chunk_length[i] = 0;
1108                         }
1109
1110                 if (chunk_tot != chunk_count ||
1111                     chunk_num > chunk_count) return FALSE;
1112
1113                 chunk_num--;
1114                 chunk_offset[chunk_num] = seg_offset + 14;
1115                 chunk_length[chunk_num] = seg_length - 14;
1116                 }
1117
1118         if (chunk_count > 0)
1119                 {
1120                 guchar *cp_data;
1121                 guint cp_length = 0;
1122                 guint i;
1123
1124                 for (i = 0; i < chunk_count; i++) cp_length += chunk_length[i];
1125                 cp_data = g_malloc(cp_length);
1126
1127                 for (i = 0; i < chunk_count; i++)
1128                         {
1129                         if (chunk_offset[i] == 0)
1130                                 {
1131                                 /* error, we never saw this chunk */
1132                                 g_free(cp_data);
1133                                 return FALSE;
1134                                 }
1135                         memcpy(cp_data, data + chunk_offset[i], chunk_length[i]);
1136                         }
1137                 DEBUG_1("Found embedded icc profile in jpeg");
1138                 exif_add_jpeg_color_profile(exif, cp_data, cp_length);
1139
1140                 return TRUE;
1141                 }
1142
1143         return FALSE;
1144 }
1145
1146 /*
1147  *-------------------------------------------------------------------
1148  * file info
1149  * it is here because it shares tag neming infrastructure with exif
1150  * we should probably not invest too much effort into this because
1151  * new exiv2 will support the same functionality
1152  * http://dev.exiv2.org/issues/show/505
1153  *-------------------------------------------------------------------
1154  */
1155
1156 static gchar *mode_number(mode_t m)
1157 {
1158         gint mb, mu, mg, mo;
1159         gchar pbuf[12];
1160
1161         mb = mu = mg = mo = 0;
1162
1163         if (m & S_ISUID) mb |= 4;
1164         if (m & S_ISGID) mb |= 2;
1165         if (m & S_ISVTX) mb |= 1;
1166
1167         if (m & S_IRUSR) mu |= 4;
1168         if (m & S_IWUSR) mu |= 2;
1169         if (m & S_IXUSR) mu |= 1;
1170
1171         if (m & S_IRGRP) mg |= 4;
1172         if (m & S_IWGRP) mg |= 2;
1173         if (m & S_IXGRP) mg |= 1;
1174
1175         if (m & S_IROTH) mo |= 4;
1176         if (m & S_IWOTH) mo |= 2;
1177         if (m & S_IXOTH) mo |= 1;
1178
1179         pbuf[0] = (m & S_IRUSR) ? 'r' : '-';
1180         pbuf[1] = (m & S_IWUSR) ? 'w' : '-';
1181         pbuf[2] = (m & S_IXUSR) ? 'x' : '-';
1182         pbuf[3] = (m & S_IRGRP) ? 'r' : '-';
1183         pbuf[4] = (m & S_IWGRP) ? 'w' : '-';
1184         pbuf[5] = (m & S_IXGRP) ? 'x' : '-';
1185         pbuf[6] = (m & S_IROTH) ? 'r' : '-';
1186         pbuf[7] = (m & S_IWOTH) ? 'w' : '-';
1187         pbuf[8] = (m & S_IXOTH) ? 'x' : '-';
1188         pbuf[9] = '\0';
1189
1190         return g_strdup_printf("%s (%d%d%d%d)", pbuf, mb, mu, mg, mo);
1191 }
1192
1193 gchar *metadata_file_info(FileData *fd, const gchar *key, MetadataFormat format)
1194 {
1195         if (strcmp(key, "file.size") == 0)
1196                 {
1197                 return g_strdup_printf("%ld", (long)fd->size);
1198                 }
1199         if (strcmp(key, "file.date") == 0)
1200                 {
1201                 return g_strdup(text_from_time(fd->date));
1202                 }
1203         if (strcmp(key, "file.mode") == 0)
1204                 {
1205                 return mode_number(fd->mode);
1206                 }
1207         if (strcmp(key, "file.ctime") == 0)
1208                 {
1209                 return g_strdup(text_from_time(fd->cdate));
1210                 }
1211         if (strcmp(key, "file.class") == 0)
1212                 {
1213                 return g_strdup(format_class_list[fd->format_class]);
1214                 }
1215         if (strcmp(key, "file.owner") == 0)
1216                 {
1217                 return g_strdup(fd->owner);
1218                 }
1219         if (strcmp(key, "file.group") == 0)
1220                 {
1221                 return g_strdup(fd->group);
1222                 }
1223         if (strcmp(key, "file.link") == 0)
1224                 {
1225                 return g_strdup(fd->sym_link);
1226                 }
1227         return g_strdup("");
1228 }
1229
1230 #ifdef HAVE_LUA
1231 gchar *metadata_lua_info(FileData *fd, const gchar *key, MetadataFormat format)
1232 {
1233         gchar *script_name;
1234         gchar *script_name_utf8;
1235         gchar *data;
1236         gchar *raw_data;
1237         gchar *valid_data;
1238
1239         script_name_utf8 = g_strdup(key + 4);
1240         script_name = path_from_utf8(script_name_utf8);
1241
1242         raw_data = lua_callvalue(fd, script_name, NULL);
1243         valid_data = g_utf8_make_valid(raw_data, -1);
1244         data = g_utf8_substring(valid_data, 0, 150);
1245
1246         g_free(script_name);
1247         g_free(script_name_utf8);
1248         g_free(raw_data);
1249         g_free(valid_data);
1250
1251         return data;
1252 }
1253 #endif
1254 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */