Simplify vflist_get_formatted()
[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 = tmp;
819                                         }
820                                 }
821                         }
822                 putenv(time_zone_org);
823
824                 g_free(time_zone_image);
825                 g_free(time_zone_org);
826                 }
827
828         g_free(timezone);
829         g_free(countryname);
830         g_free(countryalpha2);
831
832         return exif_date_time;
833 }
834
835 /**
836  * @brief Gets timezone from GPS lat/long
837  * @param[in] exif
838  * @returns Timezone string in the form "Europe/London"
839  *
840  *
841  */
842 static gchar *exif_build_formatted_timezone(ExifData *exif)
843 {
844         gchar *exif_date_time = NULL;
845         gchar *timezone = NULL;
846         gchar *countryname = NULL;
847         gchar *countryalpha2 = NULL;
848
849         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
850
851         g_free(exif_date_time);
852         g_free(countryname);
853         g_free(countryalpha2);
854
855         return timezone;
856 }
857
858 /**
859  * @brief Gets countryname from GPS lat/long
860  * @param[in] exif
861  * @returns Countryname string
862  *
863  *
864  */
865 static gchar *exif_build_formatted_countryname(ExifData *exif)
866 {
867         gchar *exif_date_time = NULL;
868         gchar *timezone = NULL;
869         gchar *countryname = NULL;
870         gchar *countryalpha2 = NULL;
871
872         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
873
874         g_free(exif_date_time);
875         g_free(timezone);
876         g_free(countryalpha2);
877
878         return countryname;
879 }
880
881 /**
882  * @brief Gets two-letter country code from GPS lat/long
883  * @param[in] exif
884  * @returns Countryalpha2 string
885  *
886  *
887  */
888 static gchar *exif_build_formatted_countrycode(ExifData *exif)
889 {
890         gchar *exif_date_time = NULL;
891         gchar *timezone = NULL;
892         gchar *countryname = NULL;
893         gchar *countryalpha2 = NULL;
894
895         exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
896
897         g_free(exif_date_time);
898         g_free(timezone);
899         g_free(countryname);
900
901         return countryalpha2;
902 }
903
904 static gchar *exif_build_formatted_star_rating(ExifData *exif)
905 {
906         gint n = 0;
907
908         exif_get_integer(exif, "Xmp.xmp.Rating", &n);
909
910         return convert_rating_to_stars(n);
911 }
912
913 /* List of custom formatted pseudo-exif tags */
914 #define EXIF_FORMATTED_TAG(name, label) { EXIF_FORMATTED()#name, label, exif_build_formatted##_##name }
915
916 ExifFormattedText ExifFormattedList[] = {
917         EXIF_FORMATTED_TAG(Camera,              N_("Camera")),
918         EXIF_FORMATTED_TAG(DateTime,            N_("Date")),
919         EXIF_FORMATTED_TAG(DateTimeDigitized,   N_("DateDigitized")),
920         EXIF_FORMATTED_TAG(ShutterSpeed,        N_("Shutter speed")),
921         EXIF_FORMATTED_TAG(Aperture,            N_("Aperture")),
922         EXIF_FORMATTED_TAG(ExposureBias,        N_("Exposure bias")),
923         EXIF_FORMATTED_TAG(ISOSpeedRating,      N_("ISO sensitivity")),
924         EXIF_FORMATTED_TAG(FocalLength,         N_("Focal length")),
925         EXIF_FORMATTED_TAG(FocalLength35mmFilm, N_("Focal length 35mm")),
926         EXIF_FORMATTED_TAG(SubjectDistance,     N_("Subject distance")),
927         EXIF_FORMATTED_TAG(Flash,               N_("Flash")),
928         EXIF_FORMATTED_TAG(Resolution,          N_("Resolution")),
929         EXIF_FORMATTED_TAG(ColorProfile,        N_("Color profile")),
930         EXIF_FORMATTED_TAG(GPSPosition,         N_("GPS position")),
931         EXIF_FORMATTED_TAG(GPSAltitude,         N_("GPS altitude")),
932         EXIF_FORMATTED_TAG(localtime,           N_("Local time")),
933         EXIF_FORMATTED_TAG(timezone,            N_("Time zone")),
934         EXIF_FORMATTED_TAG(countryname,         N_("Country name")),
935         EXIF_FORMATTED_TAG(countrycode,         N_("Country code")),
936         EXIF_FORMATTED_TAG(star_rating,         N_("Star rating")),
937         {"file.size",                           N_("File size"),        NULL},
938         {"file.date",                           N_("File date"),        NULL},
939         {"file.mode",                           N_("File mode"),        NULL},
940         {"file.ctime",                          N_("File ctime"),       NULL},
941         {"file.owner",                          N_("File owner"),       NULL},
942         {"file.group",                          N_("File group"),       NULL},
943         {"file.link",                           N_("File link"),        NULL},
944         {"file.class",                          N_("File class"),       NULL},
945         {"file.page_no",                        N_("Page no."),         NULL},
946         {"lua.lensID",                          N_("Lens"),             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 || strncmp(key, "file.", 5) == 0 || strncmp(key, "lua.", 4) == 0)
973                 {
974                 gint i;
975
976                 for (i = 0; ExifFormattedList[i].key; i++)
977                         if (strcmp(key, ExifFormattedList[i].key) == 0)
978                                 return g_strdup(_(ExifFormattedList[i].description));
979                 }
980
981         return exif_get_tag_description_by_key(key);
982 }
983
984 gint exif_get_integer(ExifData *exif, const gchar *key, gint *value)
985 {
986         ExifItem *item;
987
988         item = exif_get_item(exif, key);
989         return exif_item_get_integer(item, value);
990 }
991
992 ExifRational *exif_get_rational(ExifData *exif, const gchar *key, gint *sign)
993 {
994         ExifItem *item;
995
996         item = exif_get_item(exif, key);
997         return exif_item_get_rational(item, sign, 0);
998 }
999
1000 gchar *exif_get_data_as_text(ExifData *exif, const gchar *key)
1001 {
1002         ExifItem *item;
1003         gchar *text;
1004         gboolean key_valid;
1005
1006         if (!key) return NULL;
1007
1008         text = exif_get_formatted_by_key(exif, key, &key_valid);
1009         if (key_valid) return text;
1010
1011         item = exif_get_item(exif, key);
1012         if (item) return exif_item_get_data_as_text(item);
1013
1014         return NULL;
1015 }
1016
1017
1018 static FileCacheData *exif_cache;
1019
1020 void exif_release_cb(FileData *fd)
1021 {
1022         exif_free(fd->exif);
1023         fd->exif = NULL;
1024 }
1025
1026 void exif_init_cache(void)
1027 {
1028         g_assert(!exif_cache);
1029         exif_cache = file_cache_new(exif_release_cb, 4);
1030 }
1031
1032 ExifData *exif_read_fd(FileData *fd)
1033 {
1034         gchar *sidecar_path;
1035
1036         if (!exif_cache) exif_init_cache();
1037
1038         if (!fd) return NULL;
1039
1040         if (file_cache_get(exif_cache, fd)) return fd->exif;
1041         g_assert(fd->exif == NULL);
1042
1043         /* CACHE_TYPE_XMP_METADATA file should exist only if the metadata are
1044          * not writable directly, thus it should contain the most up-to-date version */
1045         sidecar_path = NULL;
1046
1047 #ifdef HAVE_EXIV2
1048         /* we are not able to handle XMP sidecars without exiv2 */
1049         sidecar_path = cache_find_location(CACHE_TYPE_XMP_METADATA, fd->path);
1050
1051         if (!sidecar_path) sidecar_path = file_data_get_sidecar_path(fd, TRUE);
1052 #endif
1053
1054         fd->exif = exif_read(fd->path, sidecar_path, fd->modified_xmp);
1055
1056         g_free(sidecar_path);
1057         file_cache_put(exif_cache, fd, 1);
1058         return fd->exif;
1059 }
1060
1061
1062 void exif_free_fd(FileData *fd, ExifData *exif)
1063 {
1064         if (!fd) return;
1065         g_assert(fd->exif == exif);
1066 }
1067
1068 /* embedded icc in jpeg */
1069
1070 gboolean exif_jpeg_parse_color(ExifData *exif, guchar *data, guint size)
1071 {
1072         guint seg_offset = 0;
1073         guint seg_length = 0;
1074         guint chunk_offset[255];
1075         guint chunk_length[255];
1076         guint chunk_count = 0;
1077
1078         /* For jpeg/jfif, ICC color profile data can be in more than one segment.
1079            the data is in APP2 data segments that start with "ICC_PROFILE\x00\xNN\xTT"
1080            NN = segment number for data
1081            TT = total number of ICC segments (TT in each ICC segment should match)
1082          */
1083
1084         while (jpeg_segment_find(data + seg_offset + seg_length,
1085                                       size - seg_offset - seg_length,
1086                                       JPEG_MARKER_APP2,
1087                                       "ICC_PROFILE\x00", 12,
1088                                       &seg_offset, &seg_length))
1089                 {
1090                 guchar chunk_num;
1091                 guchar chunk_tot;
1092
1093                 if (seg_length < 14) return FALSE;
1094
1095                 chunk_num = data[seg_offset + 12];
1096                 chunk_tot = data[seg_offset + 13];
1097
1098                 if (chunk_num == 0 || chunk_tot == 0) return FALSE;
1099
1100                 if (chunk_count == 0)
1101                         {
1102                         guint i;
1103
1104                         chunk_count = (guint)chunk_tot;
1105                         for (i = 0; i < chunk_count; i++) chunk_offset[i] = 0;
1106                         for (i = 0; i < chunk_count; i++) chunk_length[i] = 0;
1107                         }
1108
1109                 if (chunk_tot != chunk_count ||
1110                     chunk_num > chunk_count) return FALSE;
1111
1112                 chunk_num--;
1113                 chunk_offset[chunk_num] = seg_offset + 14;
1114                 chunk_length[chunk_num] = seg_length - 14;
1115                 }
1116
1117         if (chunk_count > 0)
1118                 {
1119                 guchar *cp_data;
1120                 guint cp_length = 0;
1121                 guint i;
1122
1123                 for (i = 0; i < chunk_count; i++) cp_length += chunk_length[i];
1124                 cp_data = g_malloc(cp_length);
1125
1126                 for (i = 0; i < chunk_count; i++)
1127                         {
1128                         if (chunk_offset[i] == 0)
1129                                 {
1130                                 /* error, we never saw this chunk */
1131                                 g_free(cp_data);
1132                                 return FALSE;
1133                                 }
1134                         memcpy(cp_data, data + chunk_offset[i], chunk_length[i]);
1135                         }
1136                 DEBUG_1("Found embedded icc profile in jpeg");
1137                 exif_add_jpeg_color_profile(exif, cp_data, cp_length);
1138
1139                 return TRUE;
1140                 }
1141
1142         return FALSE;
1143 }
1144
1145 /*
1146  *-------------------------------------------------------------------
1147  * file info
1148  * it is here because it shares tag neming infrastructure with exif
1149  * we should probably not invest too much effort into this because
1150  * new exiv2 will support the same functionality
1151  * http://dev.exiv2.org/issues/show/505
1152  *-------------------------------------------------------------------
1153  */
1154
1155 static gchar *mode_number(mode_t m)
1156 {
1157         gint mb, mu, mg, mo;
1158         gchar pbuf[12];
1159
1160         mb = mu = mg = mo = 0;
1161
1162         if (m & S_ISUID) mb |= 4;
1163         if (m & S_ISGID) mb |= 2;
1164         if (m & S_ISVTX) mb |= 1;
1165
1166         if (m & S_IRUSR) mu |= 4;
1167         if (m & S_IWUSR) mu |= 2;
1168         if (m & S_IXUSR) mu |= 1;
1169
1170         if (m & S_IRGRP) mg |= 4;
1171         if (m & S_IWGRP) mg |= 2;
1172         if (m & S_IXGRP) mg |= 1;
1173
1174         if (m & S_IROTH) mo |= 4;
1175         if (m & S_IWOTH) mo |= 2;
1176         if (m & S_IXOTH) mo |= 1;
1177
1178         pbuf[0] = (m & S_IRUSR) ? 'r' : '-';
1179         pbuf[1] = (m & S_IWUSR) ? 'w' : '-';
1180         pbuf[2] = (m & S_IXUSR) ? 'x' : '-';
1181         pbuf[3] = (m & S_IRGRP) ? 'r' : '-';
1182         pbuf[4] = (m & S_IWGRP) ? 'w' : '-';
1183         pbuf[5] = (m & S_IXGRP) ? 'x' : '-';
1184         pbuf[6] = (m & S_IROTH) ? 'r' : '-';
1185         pbuf[7] = (m & S_IWOTH) ? 'w' : '-';
1186         pbuf[8] = (m & S_IXOTH) ? 'x' : '-';
1187         pbuf[9] = '\0';
1188
1189         return g_strdup_printf("%s (%d%d%d%d)", pbuf, mb, mu, mg, mo);
1190 }
1191
1192 gchar *metadata_file_info(FileData *fd, const gchar *key, MetadataFormat format)
1193 {
1194         gchar *page_n_of_m;
1195
1196         if (strcmp(key, "file.size") == 0)
1197                 {
1198                 return g_strdup_printf("%ld", (long)fd->size);
1199                 }
1200         if (strcmp(key, "file.date") == 0)
1201                 {
1202                 return g_strdup(text_from_time(fd->date));
1203                 }
1204         if (strcmp(key, "file.mode") == 0)
1205                 {
1206                 return mode_number(fd->mode);
1207                 }
1208         if (strcmp(key, "file.ctime") == 0)
1209                 {
1210                 return g_strdup(text_from_time(fd->cdate));
1211                 }
1212         if (strcmp(key, "file.class") == 0)
1213                 {
1214                 return g_strdup(format_class_list[fd->format_class]);
1215                 }
1216         if (strcmp(key, "file.owner") == 0)
1217                 {
1218                 return g_strdup(fd->owner);
1219                 }
1220         if (strcmp(key, "file.group") == 0)
1221                 {
1222                 return g_strdup(fd->group);
1223                 }
1224         if (strcmp(key, "file.link") == 0)
1225                 {
1226                 return g_strdup(fd->sym_link);
1227                 }
1228         if (strcmp(key, "file.page_no") == 0)
1229                 {
1230                 if (fd->page_total > 1)
1231                         {
1232                         page_n_of_m = g_strdup_printf("[%d/%d]", fd->page_num + 1, fd->page_total);
1233                         return page_n_of_m;
1234                         }
1235                 else
1236                         {
1237                         return NULL;
1238                         }
1239                 }
1240         return g_strdup("");
1241 }
1242
1243 #ifdef HAVE_LUA
1244 gchar *metadata_lua_info(FileData *fd, const gchar *key, MetadataFormat format)
1245 {
1246         gchar *script_name;
1247         gchar *script_name_utf8;
1248         gchar *data;
1249         gchar *raw_data;
1250         gchar *valid_data;
1251
1252         script_name_utf8 = g_strdup(key + 4);
1253         script_name = path_from_utf8(script_name_utf8);
1254
1255         raw_data = lua_callvalue(fd, script_name, NULL);
1256         valid_data = g_utf8_make_valid(raw_data, -1);
1257         data = g_utf8_substring(valid_data, 0, 150);
1258
1259         g_free(script_name);
1260         g_free(script_name_utf8);
1261         g_free(raw_data);
1262         g_free(valid_data);
1263
1264         return data;
1265 }
1266 #endif
1267 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */