1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
3 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
5 * Copyright (C) 2011, Rob Norris <rw_norris@hotmail.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 * This uses EXIF information from images to create waypoints at those positions
26 * For the implementation I have chosen to use libexif, which keeps Viking a pure C program
27 * For an alternative implementation (a la gpscorrelate), one could use libeviv2 but it appears to be C++ only.
30 #include "geotag_exif.h"
39 #include <glib/gi18n.h>
40 #include <libexif/exif-data.h>
41 #include "libjpeg/jpeg-data.h"
44 * Attempt to get a single comment from the various exif fields
46 static gchar* geotag_get_exif_comment ( ExifData *ed )
51 // Try various options to create a comment
53 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_0], EXIF_TAG_IMAGE_DESCRIPTION);
55 exif_entry_get_value ( ee, str, 128 );
56 return g_strdup ( str );
59 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_0], EXIF_TAG_XP_COMMENT);
61 exif_entry_get_value ( ee, str, 128 );
62 return g_strdup ( str );
65 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_0], EXIF_TAG_XP_SUBJECT);
67 exif_entry_get_value ( ee, str, 128 );
68 return g_strdup ( str );
71 // Consider using these for existing GPS info??
72 //#define EXIF_TAG_GPS_TIME_STAMP 0x0007
73 //#define EXIF_TAG_GPS_DATE_STAMP 0x001d
74 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_ORIGINAL);
76 exif_entry_get_value ( ee, str, 128 );
77 return g_strdup ( str );
80 // Otherwise nothing found
85 * Handles 3 part location Rationals
86 * Handles 1 part rational (must specify 0 for the offset)
88 static gdouble Rational2Double ( unsigned char *data, int offset, ExifByteOrder order )
90 // Explaination from GPS Correlate 'exif-gps.cpp' v 1.6.1
91 // What we are trying to do here is convert the three rationals:
95 // dd/v is easy: result = dd/v.
100 // ss/v is sorta easy.
102 // -- / 3600 = result
104 // Each part is added to the final number.
107 er = exif_get_rational (data, order);
108 ans = (gdouble)er.numerator / (gdouble)er.denominator;
112 er = exif_get_rational (data+(1*offset), order);
113 ans = ans + ( ( (gdouble)er.numerator / (gdouble)er.denominator ) / 60.0 );
114 er = exif_get_rational (data+(2*offset), order);
115 ans = ans + ( ( (gdouble)er.numerator / (gdouble)er.denominator ) / 3600.0 );
121 * a_geotag_create_waypoint_from_file:
122 * @filename: The image file to process
123 * @vcmode: The current location mode to use in the positioning of Waypoint
124 * @name: Returns a name for the Waypoint (can be NULL)
126 * Returns: An allocated Waypoint or NULL if Waypoint could not be generated (e.g. no EXIF info)
129 VikWaypoint* a_geotag_create_waypoint_from_file ( const gchar *filename, VikCoordMode vcmode, gchar **name )
131 // Default return values (for failures)
133 VikWaypoint *wp = NULL;
136 //ExifLog *log = NULL;
138 // open image with libexif
139 ExifData *ed = exif_data_new_from_file ( filename );
141 // Detect EXIF load failure
143 // return with no Waypoint
151 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_VERSION_ID);
152 // Confirm this has a GPS Id - normally "2.0.0.0" or "2.2.0.0"
153 if ( ! ( ee && ee->components == 4 ) )
155 // Could test for these versions explicitly but may have byte order issues...
156 //if ( ! ( ee->data[0] == 2 && ee->data[2] == 0 && ee->data[3] == 0 ) )
160 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_MAP_DATUM);
161 if ( ! ( ee && ee->components > 0 && ee->format == EXIF_FORMAT_ASCII ) )
164 // If map datum specified - only deal in WGS-84 - the defacto standard
165 if ( ee && ee->components > 0 ) {
166 exif_entry_get_value ( ee, str, 128 );
167 if ( strncmp (str, "WGS-84", 6) )
172 // Lat & Long is necessary to form a waypoint.
174 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LATITUDE);
175 if ( ! ( ee && ee->components == 3 && ee->format == EXIF_FORMAT_RATIONAL ) )
178 ll.lat = Rational2Double ( ee->data,
179 exif_format_get_size(ee->format),
180 exif_data_get_byte_order(ed) );
182 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LATITUDE_REF);
184 exif_entry_get_value ( ee, str, 128 );
189 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LONGITUDE);
190 if ( ! ( ee && ee->components == 3 && ee->format == EXIF_FORMAT_RATIONAL ) )
193 ll.lon = Rational2Double ( ee->data,
194 exif_format_get_size(ee->format),
195 exif_data_get_byte_order(ed) );
197 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LONGITUDE_REF);
199 exif_entry_get_value ( ee, str, 128 );
205 // Not worried if none of the other fields exist, as can default the values to something
208 gdouble alt = VIK_DEFAULT_ALTITUDE;
209 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_ALTITUDE);
210 if ( ee && ee->components == 1 && ee->format == EXIF_FORMAT_RATIONAL ) {
211 alt = Rational2Double ( ee->data,
213 exif_data_get_byte_order(ed) );
215 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_ALTITUDE_REF);
216 if ( ee && ee->components == 1 && ee->format == EXIF_FORMAT_BYTE && ee->data[0] == 1 )
221 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_0], EXIF_TAG_XP_TITLE);
223 exif_entry_get_value ( ee, str, 128 );
224 *name = g_strdup ( str );
228 // Now create Waypoint with acquired information
230 wp = vik_waypoint_new();
232 // Set info from exif values
234 vik_coord_load_from_latlon ( &(wp->coord), vcmode, &ll );
238 wp->comment = geotag_get_exif_comment ( ed );
240 vik_waypoint_set_image ( wp, filename );
243 // Finished with EXIF
244 exif_data_free ( ed );
250 * a_geotag_waypoint_positioned:
251 * @filename: The image file to process
252 * @coord: The location for positioning the Waypoint
253 * @name: Returns a name for the Waypoint (can be NULL)
254 * @waypoint: An existing waypoint to update (can be NULL to generate a new waypoint)
256 * Returns: An allocated waypoint if the input waypoint is NULL,
257 * otherwise the passed in waypoint is updated
259 * Here EXIF processing is used to get non position related information (i.e. just the comment)
262 VikWaypoint* a_geotag_waypoint_positioned ( const gchar *filename, VikCoord coord, gdouble alt, gchar **name, VikWaypoint *wp )
266 // Need to create waypoint
267 wp = vik_waypoint_new();
273 ExifData *ed = exif_data_new_from_file ( filename );
275 // Set info from exif values
277 wp->comment = geotag_get_exif_comment ( ed );
282 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_0], EXIF_TAG_XP_TITLE);
284 exif_entry_get_value ( ee, str, 128 );
285 *name = g_strdup ( str );
288 // Finished with EXIF
289 exif_data_free ( ed );
292 vik_waypoint_set_image ( wp, filename );
298 * a_geotag_get_exif_date_from_file:
299 * @filename: The image file to process
300 * @has_GPS_info: Returns whether the file has existing GPS information
302 * Returns: An allocated string with the date and time in EXIF_DATE_FORMAT, otherwise NULL if some kind of failure
304 * Here EXIF processing is used to get time information
307 gchar* a_geotag_get_exif_date_from_file ( const gchar *filename, gboolean *has_GPS_info )
309 gchar* datetime = NULL;
311 ExifData *ed = exif_data_new_from_file ( filename );
313 // Detect EXIF load failure
320 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_ORIGINAL);
322 exif_entry_get_value ( ee, str, 128 );
323 datetime = g_strdup ( str );
327 *has_GPS_info = FALSE;
329 ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_VERSION_ID);
330 // Confirm this has a GPS Id - normally "2.0.0.0" or "2.2.0.0"
331 if ( ee && ee->components == 4 )
332 *has_GPS_info = TRUE;
334 exif_data_free ( ed );
340 /**! If the entry doesn't exist, create it.
341 * Based on exif command line action_create_value function in exif 0.6.20
343 static ExifEntry* my_exif_create_value (ExifData *ed, ExifTag tag, ExifIfd ifd)
345 ExifEntry *e = exif_content_get_entry (ed->ifd[ifd], tag);
347 e = exif_entry_new ();
348 exif_content_add_entry (ed->ifd[ifd], e);
350 exif_entry_initialize (e, tag);
352 // exif_entry_initialize doesn't seem to do much, especially for the GPS tags
353 // so have to setup fields ourselves:
356 if ( tag == EXIF_TAG_GPS_VERSION_ID ) {
357 e->format = EXIF_FORMAT_BYTE;
359 e->size = sizeof (char) * e->components;
362 e->data = g_malloc (e->size);
364 if ( tag == EXIF_TAG_GPS_MAP_DATUM ||
365 tag == EXIF_TAG_GPS_LATITUDE_REF || tag == EXIF_TAG_GPS_LONGITUDE_REF ||
366 tag == EXIF_TAG_GPS_PROCESSING_METHOD ) {
367 e->format = EXIF_FORMAT_ASCII;
368 // NB Allocation is handled later on when the actual string used is known
370 if ( tag == EXIF_TAG_GPS_LATITUDE || tag == EXIF_TAG_GPS_LONGITUDE ) {
371 e->format = EXIF_FORMAT_RATIONAL;
373 e->size = sizeof (ExifRational) * e->components;
376 e->data = g_malloc (e->size);
378 if ( tag == EXIF_TAG_GPS_ALTITUDE ) {
379 e->format = EXIF_FORMAT_RATIONAL;
381 e->size = sizeof (ExifRational) * e->components;
384 e->data = g_malloc (e->size);
386 if ( tag == EXIF_TAG_GPS_ALTITUDE_REF ) {
388 e->size = sizeof (char) * e->components;
391 e->data = g_malloc (e->size);
393 /* The entry has been added to the IFD, so we can unref it */
394 //exif_entry_unref(e);
395 // Crashes later on, when saving to jpeg if the above unref is enabled!!
396 // ?Some other malloc problem somewhere?
401 /** Heavily based on convert_arg_to_entry from exif command line tool.
402 * But without ExifLog, exitting, use of g_* io functions
403 * and can take a gdouble value instead of a string
405 static void convert_to_entry (const char *set_value, gdouble gdvalue, ExifEntry *e, ExifByteOrder o)
407 unsigned int i, numcomponents;
408 char *value_p = NULL;
411 * ASCII strings are handled separately,
412 * since they don't require any conversion.
414 if (e->format == EXIF_FORMAT_ASCII ||
415 e->tag == EXIF_TAG_USER_COMMENT) {
416 if (e->data) g_free (e->data);
417 e->components = strlen (set_value) + 1;
418 if (e->tag == EXIF_TAG_USER_COMMENT)
419 e->components += 8 - 1;
420 e->size = sizeof (char) * e->components;
421 e->data = g_malloc (e->size);
423 g_warning (_("Not enough memory."));
426 if (e->tag == EXIF_TAG_USER_COMMENT) {
427 /* assume ASCII charset */
428 /* TODO: get this from the current locale */
429 memcpy ((char *) e->data, "ASCII\0\0\0", 8);
430 memcpy ((char *) e->data + 8, set_value,
433 strcpy ((char *) e->data, set_value);
438 * Make sure we can handle this entry
440 if ((e->components == 0) && *set_value) {
441 g_warning (_("Setting a value for this tag is unsupported!"));
445 gboolean use_string = (set_value != NULL);
447 /* Copy the string so we can modify it */
448 buf = g_strdup (set_value);
451 value_p = strtok (buf, " ");
454 numcomponents = e->components;
455 for (i = 0; i < numcomponents; ++i) {
460 g_warning (_("Too few components specified (need %d, found %d)\n"), numcomponents, i);
463 if (!isdigit(*value_p) && (*value_p != '+') && (*value_p != '-')) {
464 g_warning (_("Numeric value expected\n"));
469 s = exif_format_get_size (e->format);
471 case EXIF_FORMAT_ASCII:
472 g_warning (_("This shouldn't happen!"));
475 case EXIF_FORMAT_SHORT:
476 exif_set_short (e->data + (s * i), o, atoi (value_p));
478 case EXIF_FORMAT_SSHORT:
479 exif_set_sshort (e->data + (s * i), o, atoi (value_p));
481 case EXIF_FORMAT_RATIONAL: {
485 if ( use_string && value_p )
486 val = fabs (atol (value_p));
488 val = fabs (gdvalue);
491 // One (or first) part rational
493 // Sneak peek into tag as location tags need rounding down to give just the degrees part
494 if ( e->tag == EXIF_TAG_GPS_LATITUDE || e->tag == EXIF_TAG_GPS_LONGITUDE ) {
495 er.numerator = (ExifLong) floor ( val );
496 er.denominator = 1.0;
499 // I don't see any point in doing anything too complicated here,
500 // such as trying to work out the 'best' denominator
501 // For the moment use KISS principle.
502 // Fix a precision of 1/100 metre as that's more than enough for GPS accuracy especially altitudes!
503 er.denominator = 100.0;
504 er.numerator = (ExifLong) (val * er.denominator);
508 // Now for Location 3 part rationals do Mins and Seconds format
510 // Rounded down minutes
512 er.denominator = 1.0;
513 er.numerator = (ExifLong) ( (int) floor ( ( val - floor (val) ) * 60.0 ) );
518 er.denominator = 100.0;
520 // Fractional minute.
521 double FracPart = ((val - floor(val)) * 60) - (double)(int) floor ( ( val - floor (val) ) * 60.0 );
522 er.numerator = (ExifLong) ( (int)floor(FracPart * 6000) ); // Convert to seconds.
524 exif_set_rational (e->data + (s * i), o, er );
527 case EXIF_FORMAT_LONG:
528 exif_set_long (e->data + (s * i), o, atol (value_p));
530 case EXIF_FORMAT_SLONG:
531 exif_set_slong (e->data + (s * i), o, atol (value_p));
533 case EXIF_FORMAT_BYTE:
534 case EXIF_FORMAT_SBYTE:
535 case EXIF_FORMAT_UNDEFINED: /* treat as byte array */
536 e->data[s * i] = atoi (value_p);
538 case EXIF_FORMAT_FLOAT:
539 case EXIF_FORMAT_DOUBLE:
540 case EXIF_FORMAT_SRATIONAL:
542 g_warning (_("Not yet implemented!"));
547 value_p = strtok (NULL, " ");
555 g_warning (_("Warning; Too many components specified!"));
559 * a_geotag_write_exif_gps:
560 * @filename: The image file to save information in
561 * @coord: The location
562 * @alt: The elevation
564 * Returns: A value indicating success: 0, or some other value for failure
567 gint a_geotag_write_exif_gps ( const gchar *filename, VikCoord coord, gdouble alt, gboolean no_change_mtime )
569 gint result = 0; // OK so far...
571 // Save mtime for later use
572 struct stat stat_save;
573 if ( no_change_mtime )
574 stat ( filename, &stat_save );
577 Appears libexif doesn't actually support writing EXIF data directly to files
578 Thus embed command line exif writing method within Viking
579 (for example this is done by Enlightment - http://www.enlightenment.org/ )
580 This appears to be JPEG only, but is probably 99% of our use case
581 Alternatively consider using libexiv2 and C++...
584 // Actual EXIF settings here...
587 /* Parse the JPEG file. */
588 jdata = jpeg_data_new ();
589 jpeg_data_load_file (jdata, filename);
591 // Get current values
592 ExifData *ed = exif_data_new_from_file ( filename );
594 ed = exif_data_new ();
596 // Update ExifData with our new settings
599 // I don't understand it, but when saving the 'ed' nothing gets set after putting in the GPS ID tag - so it must come last
600 // (unless of course there is some bug in the setting of the ID, that prevents subsequent tags)
603 ee = my_exif_create_value (ed, EXIF_TAG_GPS_ALTITUDE, EXIF_IFD_GPS);
604 convert_to_entry ( NULL, alt, ee, exif_data_get_byte_order(ed) );
606 // byte 0 meaning "sea level" or 1 if the value is negative.
607 ee = my_exif_create_value (ed, EXIF_TAG_GPS_ALTITUDE_REF, EXIF_IFD_GPS);
608 convert_to_entry ( alt < 0.0 ? "1" : "0", 0.0, ee, exif_data_get_byte_order(ed) );
610 ee = my_exif_create_value (ed, EXIF_TAG_GPS_PROCESSING_METHOD, EXIF_IFD_GPS);
611 // see http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/GPS.html
612 convert_to_entry ( "MANUAL", 0.0, ee, exif_data_get_byte_order(ed) );
614 ee = my_exif_create_value (ed, EXIF_TAG_GPS_MAP_DATUM, EXIF_IFD_GPS);
615 convert_to_entry ( "WGS-84", 0.0, ee, exif_data_get_byte_order(ed) );
618 vik_coord_to_latlon ( &coord, &ll );
620 ee = my_exif_create_value (ed, EXIF_TAG_GPS_LATITUDE_REF, EXIF_IFD_GPS);
622 convert_to_entry ( ll.lat < 0.0 ? "S" : "N", 0.0, ee, exif_data_get_byte_order(ed) );
624 ee = my_exif_create_value (ed, EXIF_TAG_GPS_LATITUDE, EXIF_IFD_GPS);
625 convert_to_entry ( NULL, ll.lat, ee, exif_data_get_byte_order(ed) );
627 ee = my_exif_create_value (ed, EXIF_TAG_GPS_LONGITUDE_REF, EXIF_IFD_GPS);
629 convert_to_entry ( ll.lon < 0.0 ? "W" : "E", 0.0, ee, exif_data_get_byte_order(ed) );
631 ee = my_exif_create_value (ed, EXIF_TAG_GPS_LONGITUDE, EXIF_IFD_GPS);
632 convert_to_entry ( NULL, ll.lon, ee, exif_data_get_byte_order(ed) );
634 ee = my_exif_create_value (ed, EXIF_TAG_GPS_VERSION_ID, EXIF_IFD_GPS);
635 //convert_to_entry ( "2 0 0 0", 0.0, ee, exif_data_get_byte_order(ed) );
636 convert_to_entry ( "2 2 0 0", 0.0, ee, exif_data_get_byte_order(ed) );
638 jpeg_data_set_exif_data (jdata, ed);
641 /* Save the modified image. */
642 result = jpeg_data_save_file (jdata, filename);
644 // Convert result from 1 for success, 0 for failure into our scheme
647 jpeg_data_unref (jdata);
650 // Epic fail - file probably not a JPEG
654 if ( no_change_mtime ) {
655 // Restore mtime, using the saved value
656 struct stat stat_tmp;
658 stat ( filename, &stat_tmp );
659 utb.actime = stat_tmp.st_atime;
660 utb.modtime = stat_save.st_mtime;
661 utime ( filename, &utb );