Sat Jun 4 22:24:00 2005 John Ellis <johne@verizon.net>
[geeqie.git] / src / exif.c
1 /*
2  *  GQView
3  *  (C) 2004 John Ellis
4  *
5  *  Authors:
6  *    Support for Exif file format, originally written by Eric Swalens.    
7  *    Modified by Quy Tonthat
8  *
9  *    Reimplemented with generic data storage by John Ellis (Nov 2003)
10  *
11  *  The tags were added with information from the FREE document:
12  *     http://www.ba.wakwak.com/~tsuruzoh/Computer/Digicams/exif-e.html
13  *
14  *  For the official Exif Format, please refer to:
15  *     http://www.exif.org
16  *     http://www.exif.org/specifications.html (PDF spec sheets)
17  *
18  *  Notes:
19  *     Additional tag formats should be added to the proper
20  *     location in ExifKnownMarkersList[].
21  *
22  *     Human readable ouput (that needs additional processing of data to
23  *     be useable) can be defined by adding a key to ExifFormattedList[],
24  *     then handling that tag in the function exif_get_formatted_by_key().
25  *     The human readable formatted keys must begin with the character 'f'.
26  *
27  *  Unsupported at this time:
28  *     IFD1 (thumbnail)
29  *     MakerNote
30  *     GPSInfo
31  *
32  *  TODO:
33  *     Convert data to useable form in the ??_as_text function for:
34  *        ComponentsConfiguration
35  *        UserComment (convert this to UTF-8?)
36  *
37
38     This program is free software; you can redistribute it and/or modify
39     it under the terms of the GNU General Public License as published by
40     the Free Software Foundation; either version 2 of the License, or
41     (at your option) any later version.
42
43     This program is distributed in the hope that it will be useful,
44     but WITHOUT ANY WARRANTY; without even the implied warranty of
45     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
46     GNU General Public License for more details.
47
48     You should have received a copy of the GNU General Public License
49     along with this program; if not, write to the Free Software
50     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
51 */
52
53 #ifdef HAVE_CONFIG_H
54 #  include "config.h"
55 #endif
56
57 #include <stdio.h>
58 #include <inttypes.h>   /* stdint.h is not available on all systems... */
59 #include <string.h>
60 #include <fcntl.h>
61 #include <unistd.h>
62 #include <sys/types.h>
63 #include <sys/stat.h>
64 #include <sys/mman.h>
65 #include <math.h>
66  
67 #include <glib.h>
68
69 #include "intl.h"
70
71 #include "exif.h"
72
73 #include "format_raw.h"
74 #include "ui_fileops.h"
75
76
77 /*
78  *-----------------------------------------------------------------------------
79  * Tag formats
80  *-----------------------------------------------------------------------------
81  */
82
83 ExifFormatAttrib ExifFormatList[] = {
84         { EXIF_FORMAT_UNKNOWN,          1, "unknown",   "unknown" },
85         { EXIF_FORMAT_BYTE_UNSIGNED,    1, "ubyte",     "unsigned byte" },
86         { EXIF_FORMAT_STRING,           1, "string",    "string" },
87         { EXIF_FORMAT_SHORT_UNSIGNED,   2, "ushort",    "unsigned short" },
88         { EXIF_FORMAT_LONG_UNSIGNED,    4, "ulong",     "unsigned long" },
89         { EXIF_FORMAT_RATIONAL_UNSIGNED,8, "urational", "unsigned rational" },
90         { EXIF_FORMAT_BYTE,             1, "byte",      "byte" },
91         { EXIF_FORMAT_UNDEFINED,        1, "undefined", "undefined" },
92         { EXIF_FORMAT_SHORT,            2, "sshort",    "signed short" },
93         { EXIF_FORMAT_LONG,             4, "slong",     "signed long" },
94         { EXIF_FORMAT_RATIONAL,         8, "srational", "signed rational" },
95         { EXIF_FORMAT_FLOAT,            4, "float",     "float" },
96         { EXIF_FORMAT_DOUBLE,           8, "double",    "double" },
97         { -1, 0, NULL }
98 };
99
100 /* tags that are special, or need special treatment */
101 #define TAG_EXIFOFFSET          0x8769
102 #define TAG_EXIFMAKERNOTE       0x927c
103
104
105 /*
106  *-----------------------------------------------------------------------------
107  * Data
108  *-----------------------------------------------------------------------------
109  */
110
111 static ExifTextList ExifOrientationList[] = {
112         { EXIF_ORIENTATION_UNKNOWN,     N_("unknown") },
113         { EXIF_ORIENTATION_TOP_LEFT,    N_("top left") },
114         { EXIF_ORIENTATION_TOP_RIGHT,   N_("top right") },
115         { EXIF_ORIENTATION_BOTTOM_RIGHT,N_("bottom right") },
116         { EXIF_ORIENTATION_BOTTOM_LEFT, N_("bottom left") },
117         { EXIF_ORIENTATION_LEFT_TOP,    N_("left top") },
118         { EXIF_ORIENTATION_RIGHT_TOP,   N_("right top") },
119         { EXIF_ORIENTATION_RIGHT_BOTTOM,N_("right bottom") },
120         { EXIF_ORIENTATION_LEFT_BOTTOM, N_("left bottom") },
121         EXIF_TEXT_LIST_END
122 };
123
124 static ExifTextList ExifUnitList[] = {
125         { EXIF_UNIT_UNKNOWN,    N_("unknown") },
126         { EXIF_UNIT_NOUNIT,     "" },
127         { EXIF_UNIT_INCH,       N_("inch") },
128         { EXIF_UNIT_CENTIMETER, N_("centimeter") },
129         EXIF_TEXT_LIST_END
130 };
131
132 static ExifTextList ExifYCbCrPosList[] = {
133         { 1,    "center" },
134         { 2,    "datum" },
135         EXIF_TEXT_LIST_END
136 };
137
138 static ExifTextList ExifMeteringModeList[] = {
139         { 0,    N_("unknown") },
140         { 1,    N_("average") },
141         { 2,    N_("center weighted") },
142         { 3,    N_("spot") },
143         { 4,    N_("multi-spot") },
144         { 5,    N_("multi-segment") },
145         { 6,    N_("partial") },
146         { 255,  N_("other") },
147         EXIF_TEXT_LIST_END
148 };
149
150 static ExifTextList ExifExposureProgramList[] = {
151         { 0,    N_("not defined") },
152         { 1,    N_("manual") },
153         { 2,    N_("normal") },
154         { 3,    N_("aperture") },
155         { 4,    N_("shutter") },
156         { 5,    N_("creative") },
157         { 6,    N_("action") },
158         { 7,    N_("portrait") },
159         { 8,    N_("landscape") },
160         EXIF_TEXT_LIST_END
161 };
162
163 static ExifTextList ExifLightSourceList[] = {
164         { 0,    N_("unknown") },
165         { 1,    N_("daylight") },
166         { 2,    N_("fluorescent") },
167         { 3,    N_("tungsten (incandescent)") },
168         { 4,    N_("flash") },
169         { 9,    "fine weather" },
170         { 10,   "cloudy weather" },
171         { 11,   "shade" },
172         { 12,   "daylight fluorescent" },
173         { 13,   "day white fluorescent" },
174         { 14,   "cool white fluorescent" },
175         { 15,   "while fluorescent" },
176         { 17,   "standard light A" },
177         { 18,   "standard light B" },
178         { 19,   "standard light C" },
179         { 20,   "D55" },
180         { 21,   "D65" },
181         { 22,   "D75" },
182         { 23,   "D50" },
183         { 24,   "ISO studio tungsten" },
184         { 255,  N_("other") },
185         EXIF_TEXT_LIST_END
186 };
187
188 static ExifTextList ExifFlashList[] = {
189         { 0,    N_("no") },
190         { 1,    N_("yes") },
191         { 5,    N_("yes, not detected by strobe") },
192         { 7,    N_("yes, detected by strobe") },
193         EXIF_TEXT_LIST_END
194 };
195
196 static ExifTextList ExifColorSpaceList[] = {
197         { 1,    "sRGB" },
198         { 65535,"uncalibrated" },
199         EXIF_TEXT_LIST_END
200 };
201
202 static ExifTextList ExifSensorList[] = {
203         { 1,    "not defined" },
204         { 2,    "1 chip color area" },
205         { 2,    "2 chip color area" },
206         { 4,    "3 chip color area" },
207         { 5,    "color sequential area" },
208         { 7,    "trilinear" },
209         { 8,    "color sequential linear" },
210         EXIF_TEXT_LIST_END
211 };
212
213 static ExifTextList ExifSourceList[] = {
214         { 3,    "digital still camera" },
215         EXIF_TEXT_LIST_END
216 };
217
218 static ExifTextList ExifSceneList[] = {
219         { 1,    "direct photo" },
220         EXIF_TEXT_LIST_END
221 };
222
223 static ExifTextList ExifCustRenderList[] = {
224         { 0,    "normal" },
225         { 1,    "custom" },
226         EXIF_TEXT_LIST_END
227 };
228
229 static ExifTextList ExifExposureModeList[] = {
230         { 0,    "auto" },
231         { 1,    "manual" },
232         { 2,    "auto bracket" },
233         EXIF_TEXT_LIST_END
234 };
235
236 static ExifTextList ExifWhiteBalanceList[] = {
237         { 0,    "auto" },
238         { 1,    "manual" },
239         EXIF_TEXT_LIST_END
240 };
241
242 static ExifTextList ExifSceneCaptureList[] = {
243         { 0,    "standard" },
244         { 1,    "landscape" },
245         { 2,    "portrait" },
246         { 3,    "night scene" },
247         EXIF_TEXT_LIST_END
248 };
249
250 static ExifTextList ExifGainControlList[] = {
251         { 0,    "none" },
252         { 1,    "low gain up" },
253         { 2,    "high gain up" },
254         { 3,    "low gain down" },
255         { 4,    "high gain down" },
256         EXIF_TEXT_LIST_END
257 };
258
259 static ExifTextList ExifContrastList[] = {
260         { 0,    "normal" },
261         { 1,    "soft" },
262         { 2,    "hard" },
263         EXIF_TEXT_LIST_END
264 };
265
266 static ExifTextList ExifSaturationList[] = {
267         { 0,    "normal" },
268         { 1,    "low" },
269         { 2,    "high" },
270         EXIF_TEXT_LIST_END
271 };
272
273 static ExifTextList ExifSharpnessList[] = {
274         { 0,    "normal" },
275         { 1,    "soft" },
276         { 2,    "hard" },
277         EXIF_TEXT_LIST_END
278 };
279
280 static ExifTextList ExifSubjectRangeList[] = {
281         { 0,    "unknown" },
282         { 1,    "macro" },
283         { 2,    "close" },
284         { 3,    "distant" },
285         EXIF_TEXT_LIST_END
286 };
287
288 ExifMarker ExifKnownMarkersList[] = {
289 { 0x010e, EXIF_FORMAT_STRING, -1,               "ImageDescription",     N_("Image description"), NULL },
290 { 0x010f, EXIF_FORMAT_STRING, -1,               "Make",                 "Camera make", NULL },
291 { 0x0110, EXIF_FORMAT_STRING, -1,               "Model",                "Camera model", NULL },
292 { 0x0112, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Orientation",          N_("Orientation"), ExifOrientationList },
293 { 0x011a, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "XResolution",          "X resolution", NULL },
294 { 0x011b, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "YResolution",          "Y Resolution", NULL },
295 { 0x0128, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "ResolutionUnit",       "Resolution units", ExifUnitList },
296 { 0x0131, EXIF_FORMAT_STRING, -1,               "Software",             "Firmware", NULL },
297 { 0x0132, EXIF_FORMAT_STRING, 20,               "DateTime",             N_("Date"), NULL },
298 { 0x013e, EXIF_FORMAT_RATIONAL_UNSIGNED, 2,     "WhitePoint",           "White point", NULL },
299 { 0x013f, EXIF_FORMAT_RATIONAL_UNSIGNED, 6,     "PrimaryChromaticities","Primary chromaticities", NULL },
300 { 0x0211, EXIF_FORMAT_RATIONAL_UNSIGNED, 3,     "YCbCrCoefficients",    "YCbCy coefficients", NULL },
301 { 0x0213, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "YCbCrPositioning",     "YCbCr positioning", ExifYCbCrPosList },
302 { 0x0214, EXIF_FORMAT_RATIONAL_UNSIGNED, 6,     "ReferenceBlackWhite",  "Black white reference", NULL },
303 { 0x8298, EXIF_FORMAT_STRING, -1,               "Copyright",            N_("Copyright"), NULL },
304 { 0x8769, EXIF_FORMAT_LONG_UNSIGNED, 1,         "ExifOffset",           "SubIFD Exif offset", NULL },
305         /* subIFD follows */
306 { 0x829a, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "ExposureTime",         "Exposure time (seconds)", NULL },
307 { 0x829d, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "FNumber",              "FNumber", NULL },
308 { 0x8822, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "ExposureProgram",      N_("Exposure program"), ExifExposureProgramList },
309 { 0x8824, EXIF_FORMAT_STRING, -1,               "SpectralSensitivity",  "Spectral Sensitivity", NULL },
310 { 0x8827, EXIF_FORMAT_SHORT_UNSIGNED, -1,       "ISOSpeedRatings",      N_("ISO sensitivity"), NULL },
311 { 0x8828, EXIF_FORMAT_UNDEFINED, -1,            "OECF",                 "Optoelectric conversion factor", NULL },
312 { 0x9000, EXIF_FORMAT_UNDEFINED, 4,             "ExifVersion",          "Exif version", NULL },
313 { 0x9003, EXIF_FORMAT_STRING, 20,               "DateTimeOriginal",     N_("Date original"), NULL },
314 { 0x9004, EXIF_FORMAT_STRING, 20,               "DateTimeDigitized",    N_("Date digitized"), NULL },
315 { 0x9101, EXIF_FORMAT_UNDEFINED, -1,            "ComponentsConfiguration","Pixel format", NULL },
316 { 0x9102, EXIF_FORMAT_RATIONAL_UNSIGNED,1,      "CompressedBitsPerPixel","Compression ratio", NULL },
317 { 0x9201, EXIF_FORMAT_RATIONAL, 1,              "ShutterSpeedValue",    N_("Shutter speed"), NULL },
318 { 0x9202, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "ApertureValue",        N_("Aperture"), NULL },
319 { 0x9203, EXIF_FORMAT_RATIONAL, 1,              "BrightnessValue",      "Brightness", NULL },
320 { 0x9204, EXIF_FORMAT_RATIONAL, 1,              "ExposureBiasValue",    N_("Exposure bias"), NULL },
321 { 0x9205, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "MaxApertureValue",     "Maximum aperture", NULL },
322 { 0x9206, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "SubjectDistance",      N_("Subject distance"), NULL },
323 { 0x9207, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "MeteringMode",         N_("Metering mode"), ExifMeteringModeList },
324 { 0x9208, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "LightSource",          N_("Light source"), ExifLightSourceList },
325 { 0x9209, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Flash",                N_("Flash"), ExifFlashList },
326 { 0x920a, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "FocalLength",          N_("Focal length"), NULL },
327 { 0x9214, EXIF_FORMAT_SHORT_UNSIGNED, -1,       "SubjectArea",          "Subject area", NULL },
328 { 0x927c, EXIF_FORMAT_UNDEFINED, -1,            "MakerNote",            "MakerNote", NULL },
329 { 0x9286, EXIF_FORMAT_UNDEFINED, -1,            "UserComment",          "UserComment", NULL },
330 { 0x9290, EXIF_FORMAT_STRING, -1,               "SubsecTime",           "Subsecond time", NULL },
331 { 0x9291, EXIF_FORMAT_STRING, -1,               "SubsecTimeOriginal",   "Subsecond time original", NULL },
332 { 0x9292, EXIF_FORMAT_STRING, -1,               "SubsecTimeDigitized",  "Subsecond time digitized", NULL },
333 { 0xa000, EXIF_FORMAT_UNDEFINED, 4,             "FlashPixVersion",      "FlashPix version", NULL },
334 { 0xa001, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "ColorSpace",           "Colorspace", ExifColorSpaceList },
335         /* ExifImageWidth, ExifImageHeight can also be unsigned short */
336 { 0xa002, EXIF_FORMAT_LONG_UNSIGNED, 1,         "ExifImageWidth",       N_("Width"), NULL },
337 { 0xa003, EXIF_FORMAT_LONG_UNSIGNED, 1,         "ExifImageHeight",      N_("Height"), NULL },
338 { 0xa004, EXIF_FORMAT_STRING, -1,               "RelatedSoundFile",     "Audio data", NULL },
339 { 0xa005, EXIF_FORMAT_LONG_UNSIGNED, 1,         "ExifInteroperabilityOffset", "ExifR98 extension", NULL },
340 { 0xa20b, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "FlashEnergy",          "Flash strength", NULL },
341 { 0xa20c, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "SpatialFrequencyResponse","Spatial frequency response", NULL },
342 { 0xa20e, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "FocalPlaneXResolution", "X Pixel density", NULL },
343 { 0xa20f, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "FocalPlaneYResolution", "Y Pixel density", NULL },
344 { 0xa210, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "FocalPlaneResolutionUnit", "Pixel density units", ExifUnitList },
345 { 0x0214, EXIF_FORMAT_SHORT_UNSIGNED, 2,        "SubjectLocation",      "Subject location", NULL },
346 { 0xa215, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "ExposureIndex",        N_("ISO sensitivity"), NULL },
347 { 0xa217, EXIF_FORMAT_SHORT_UNSIGNED, -1,       "SensingMethod",        "Sensor type", ExifSensorList },
348 { 0xa300, EXIF_FORMAT_UNDEFINED, 1,             "FileSource",           "Source type", ExifSourceList },
349 { 0xa301, EXIF_FORMAT_UNDEFINED, 1,             "SceneType",            "Scene type", ExifSceneList },
350 { 0xa302, EXIF_FORMAT_UNDEFINED, -1,            "CFAPattern",           "Color filter array pattern", NULL },
351         /* tags a4xx were added for Exif 2.2 (not just these - some above, as well) */
352 { 0xa401, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "CustomRendered",       "Render process", ExifCustRenderList },
353 { 0xa402, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "ExposureMode",         "Exposure mode", ExifExposureModeList },
354 { 0xa403, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "WhiteBalance",         "White balance", ExifWhiteBalanceList },
355 { 0xa404, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "DigitalZoomRatio",     "Digital zoom ratio", NULL },
356 { 0xa405, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "FocalLength35mmFilm",  "Focal length (35mm)", NULL },
357 { 0xa406, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "SceneCapturetype",     "Scene capture type", ExifSceneCaptureList },
358 { 0xa407, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "GainControl",          "Gain control", ExifGainControlList },
359 { 0xa408, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Contrast",             "Contrast", ExifContrastList },
360 { 0xa409, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Saturation",           "Saturation", ExifSaturationList },
361 { 0xa40a, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Sharpness",            "Sharpness", ExifSharpnessList },
362 { 0xa40b, EXIF_FORMAT_UNDEFINED, -1,            "DeviceSettingDescription","Device setting", NULL },
363 { 0xa40c, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "SubjectDistanceRange", "Subject range", ExifSubjectRangeList },
364 { 0xa420, EXIF_FORMAT_STRING, -1,               "ImageUniqueID",        "Image serial number", NULL },
365         /* place known, but undocumented or lesser used tags here */
366 { 0x00fe, EXIF_FORMAT_LONG_UNSIGNED, 1,         "NewSubfileType",       NULL, NULL },
367 { 0x00ff, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "SubfileType",          NULL, NULL },
368 { 0x012d, EXIF_FORMAT_SHORT_UNSIGNED, 3,        "TransferFunction",     NULL, NULL },
369 { 0x013b, EXIF_FORMAT_STRING, -1,               "Artist",               "Artist", NULL },
370 { 0x013d, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Predictor",            NULL, NULL },
371 { 0x0142, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "TileWidth",            NULL, NULL },
372 { 0x0143, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "TileLength",           NULL, NULL },
373 { 0x0144, EXIF_FORMAT_LONG_UNSIGNED, -1,        "TileOffsets",          NULL, NULL },
374 { 0x0145, EXIF_FORMAT_SHORT_UNSIGNED, -1,       "TileByteCounts",       NULL, NULL },
375 { 0x014a, EXIF_FORMAT_LONG_UNSIGNED, -1,        "SubIFDs",              NULL, NULL },
376 { 0x015b, EXIF_FORMAT_UNDEFINED, -1,            "JPEGTables",           NULL, NULL },
377 { 0x828d, EXIF_FORMAT_SHORT_UNSIGNED, 2,        "CFARepeatPatternDim",  NULL, NULL },
378 { 0x828e, EXIF_FORMAT_BYTE_UNSIGNED, -1,        "CFAPattern",           NULL, NULL },
379 { 0x828f, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "BatteryLevel",         NULL, NULL },
380 { 0x83bb, EXIF_FORMAT_LONG_UNSIGNED, -1,        "IPTC/NAA",             NULL, NULL },
381 { 0x8773, EXIF_FORMAT_UNDEFINED, -1,            "InterColorProfile",    NULL, NULL },
382 { 0x8825, EXIF_FORMAT_LONG_UNSIGNED, 1,         "GPSInfo",              "SubIFD GPS offset", NULL },
383 { 0x8829, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Interlace",            NULL, NULL },
384 { 0x882a, EXIF_FORMAT_SHORT, 1,                 "TimeZoneOffset",       NULL, NULL },
385 { 0x882b, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "SelfTimerMode",        NULL, NULL },
386 { 0x920b, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "FlashEnergy",          NULL, NULL },
387 { 0x920c, EXIF_FORMAT_UNDEFINED, -1,            "SpatialFrequencyResponse", NULL, NULL },
388 { 0x920d, EXIF_FORMAT_UNDEFINED, -1,            "Noise",                NULL, NULL },
389 { 0x9211, EXIF_FORMAT_LONG_UNSIGNED, 1,         "ImageNumber",          NULL, NULL },
390 { 0x9212, EXIF_FORMAT_STRING, 1,                "SecurityClassification", NULL, NULL },
391 { 0x9213, EXIF_FORMAT_STRING, -1,               "ImageHistory",         NULL, NULL },
392 { 0x9215, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "ExposureIndex",        NULL, NULL },
393 { 0x9216, EXIF_FORMAT_BYTE_UNSIGNED, 4,         "TIFF/EPStandardID",    NULL, NULL },
394
395 EXIF_MARKER_LIST_END
396 };
397
398 ExifMarker ExifUnknownMarkersList[] = {
399 { 0x0000, EXIF_FORMAT_UNKNOWN, 0,               "unknown",      NULL, NULL },
400 { 0x0000, EXIF_FORMAT_BYTE_UNSIGNED, -1,        "unknown",      NULL, NULL },
401 { 0x0000, EXIF_FORMAT_STRING, -1,               "unknown",      NULL, NULL },
402 { 0x0000, EXIF_FORMAT_SHORT_UNSIGNED, -1,       "unknown",      NULL, NULL },
403 { 0x0000, EXIF_FORMAT_LONG_UNSIGNED, -1,        "unknown",      NULL, NULL },
404 { 0x0000, EXIF_FORMAT_RATIONAL_UNSIGNED, -1,    "unknown",      NULL, NULL },
405 { 0x0000, EXIF_FORMAT_BYTE, -1,                 "unknown",      NULL, NULL },
406 { 0x0000, EXIF_FORMAT_UNDEFINED, -1,            "unknown",      NULL, NULL },
407 { 0x0000, EXIF_FORMAT_SHORT, -1,                "unknown",      NULL, NULL },
408 { 0x0000, EXIF_FORMAT_LONG, -1,                 "unknown",      NULL, NULL },
409 { 0x0000, EXIF_FORMAT_RATIONAL, -1,             "unknown",      NULL, NULL },
410 { 0x0000, EXIF_FORMAT_FLOAT, -1,                "unknown",      NULL, NULL },
411 { 0x0000, EXIF_FORMAT_DOUBLE, -1,               "unknown",      NULL, NULL },
412 };
413
414 /* human readable key list */
415
416 ExifFormattedText ExifFormattedList[] = {
417         { "fCamera",            N_("Camera") },
418         { "fDateTime",          N_("Date") },
419         { "fShutterSpeed",      N_("Shutter speed") },
420         { "fAperture",          N_("Aperture") },
421         { "fExposureBias",      N_("Exposure bias") },
422         { "fISOSpeedRating",    N_("ISO sensitivity") },
423         { "fFocalLength",       N_("Focal length") },
424         { "fSubjectDistance",   N_("Subject distance") },
425         { "fFlash",             N_("Flash") },
426         { "fResolution",        N_("Resolution") },
427         { NULL, NULL }
428 };
429
430
431 /*
432  *-----------------------------------------------------------------------------
433  * misc
434  *-----------------------------------------------------------------------------
435  */
436
437 #define MARKER_UNKNOWN          0x00
438 #define MARKER_SOI              0xD8
439 #define MARKER_APP1             0xE1
440
441 /* These data structs are packed to make sure the
442  * byte alignment matches the on-disk data format.
443  */
444 typedef struct __attribute__((packed)) {
445         char            byte_order[2];
446         uint16_t        magic;
447         uint32_t        IFD_offset;
448 } TIFFHeader;
449  
450 typedef struct __attribute__((packed)) {
451         uint16_t        tag;
452         uint16_t        format;
453         uint32_t        nb;
454         uint32_t        data;
455 } IFDEntry;
456
457
458 static const ExifMarker *exif_marker_from_tag(guint16 tag, const ExifMarker *list);
459
460 /*
461  *-----------------------------------------------------------------------------
462  * ExifItem
463  *-----------------------------------------------------------------------------
464  */
465
466 ExifItem *exif_item_new(ExifFormatType format, guint tag,
467                         guint elements, const ExifMarker *marker)
468 {
469         ExifItem *item;
470
471         item = g_new0(ExifItem, 1);
472         item->format = format;
473         item->tag = tag;
474         item->marker = marker;
475         item->elements = elements;
476         item->data = NULL;
477         item->data_len = 0;
478
479         switch (format)
480                 {
481                 case EXIF_FORMAT_UNKNOWN:
482                         /* unknown, data is NULL */
483                         return item;
484                         break;
485                 case EXIF_FORMAT_BYTE_UNSIGNED:
486                         item->data_len = sizeof(char) * elements;
487                         break;
488                 case EXIF_FORMAT_STRING:
489                         item->data_len = sizeof(char) * elements;
490                         break;
491                 case EXIF_FORMAT_SHORT_UNSIGNED:
492                         item->data_len = sizeof(guint16) * elements;
493                         break;
494                 case EXIF_FORMAT_LONG_UNSIGNED:
495                         item->data_len = sizeof(guint32) * elements;
496                         break;
497                 case EXIF_FORMAT_RATIONAL_UNSIGNED:
498                         item->data_len = sizeof(ExifRational) * elements;
499                         break;
500                 case EXIF_FORMAT_BYTE:
501                         item->data_len = sizeof(char) * elements;
502                         break;
503                 case EXIF_FORMAT_UNDEFINED:
504                         item->data_len = sizeof(char) * elements;
505                         break;
506                 case EXIF_FORMAT_SHORT:
507                         item->data_len = sizeof(gint16) * elements;
508                         break;
509                 case EXIF_FORMAT_LONG:
510                         item->data_len = sizeof(gint32) * elements;
511                         break;
512                 case EXIF_FORMAT_RATIONAL:
513                         item->data_len = sizeof(ExifRational) * elements;
514                         break;
515                 case EXIF_FORMAT_FLOAT:
516                         item->data_len = sizeof(float) * elements;
517                         break;
518                 case EXIF_FORMAT_DOUBLE:
519                         item->data_len = sizeof(double) * elements;
520                         break;
521                 }
522
523         item->data = g_malloc0(item->data_len);
524
525         return item;
526 }
527
528 static void exif_item_free(ExifItem *item)
529 {
530         if (!item) return;
531
532         g_free(item->data);
533         g_free(item);
534 }
535
536 const char *exif_item_get_tag_name(ExifItem *item)
537 {
538         if (!item || !item->marker) return NULL;
539         return item->marker->key;
540 }
541
542 const char *exif_item_get_description(ExifItem *item)
543 {
544         if (!item || !item->marker) return NULL;
545         return _(item->marker->description);
546 }
547
548 const char *exif_item_get_format_name(ExifItem *item, gint brief)
549 {
550         if (!item || !item->marker) return NULL; 
551         return (brief) ? ExifFormatList[item->format].short_name : ExifFormatList[item->format].description;
552 }
553
554
555 #define UNDEFINED_TEXT_BYTE_COUNT 16
556
557 static GString *string_append_raw_bytes(GString *string, gpointer data, gint ne)
558 {
559         gint i;
560
561         for (i = 0 ; i < ne && i < UNDEFINED_TEXT_BYTE_COUNT; i++)
562                 {
563                 unsigned char c = ((char *)data)[i];
564                 if (c < 32 || c > 127) c = '.';
565                 g_string_append_printf(string, "%c", c);
566                 }
567         string = g_string_append(string, " : ");
568         for (i = 0 ; i < ne && i < UNDEFINED_TEXT_BYTE_COUNT; i++)
569                 {
570                 const gchar *spacer;
571                 if (i > 0)
572                         {
573                         if (i%8 == 0)
574                                 {
575                                 spacer = " - ";
576                                 }
577                         else
578                                 {
579                                 spacer = " ";
580                                 }
581                         }
582                 else
583                         {
584                         spacer = "";
585                         }
586                 g_string_append_printf(string, "%s%02x", spacer, ((char *)data)[i]);
587                 }
588         if (i >= UNDEFINED_TEXT_BYTE_COUNT) g_string_append_printf(string, " (%d bytes)", ne);
589
590         return string;
591 }
592
593 static gchar *text_list_find_value(ExifTextList *list, guint value)
594 {
595         gchar *result = NULL;
596         gint i;
597
598         i = 0;
599         while (!result && list[i].value >= 0)
600                 {
601                 if (value == list[i].value) result = g_strdup(_(list[i].description));
602                 i++;
603                 }
604         if (!result) result = g_strdup_printf("%d (%s)", value, _("unknown"));
605
606         return result;
607 }
608
609 /*
610  *-------------------------------------------------------------------
611  * byte size utils
612  *-------------------------------------------------------------------
613  */
614
615 guint16 exif_byte_get_int16(unsigned char *f, ExifByteOrder bo)
616 {
617         if (bo == EXIF_BYTE_ORDER_INTEL)
618                 return GUINT16_FROM_LE(*(guint16*)f);
619         else
620                 return GUINT16_FROM_BE(*(guint16*)f);
621 }
622
623 guint32 exif_byte_get_int32(unsigned char *f, ExifByteOrder bo)
624 {
625         if (bo == EXIF_BYTE_ORDER_INTEL)
626                 return GUINT32_FROM_LE(*(guint32*)f);
627         else
628                 return GUINT32_FROM_BE(*(guint32*)f);
629 }
630
631 guint16 exif_byte_swab_int16(guint16 n, ExifByteOrder bo)
632 {
633 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
634         if (bo == EXIF_BYTE_ORDER_MOTOROLA)
635 #else
636         if (bo == EXIF_BYTE_ORDER_INTEL)
637 #endif
638                 return GUINT16_SWAP_LE_BE(n);
639         else
640                 return n;
641 }
642
643 guint32 exif_byte_swab_int32(guint32 n, ExifByteOrder bo)
644 {
645 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
646         if (bo == EXIF_BYTE_ORDER_MOTOROLA)
647 #else
648         if (bo == EXIF_BYTE_ORDER_INTEL)
649 #endif
650                 return GUINT32_SWAP_LE_BE(n);
651         else
652                 return n;
653 }
654
655 /*
656  *-------------------------------------------------------------------
657  * marker utils
658  *-------------------------------------------------------------------
659  */
660
661 static int get_marker_size(unsigned char *f)
662 {
663         /* Size is always in Motorola byte order */
664         return exif_byte_get_int16(f+2, EXIF_BYTE_ORDER_MOTOROLA);
665 }
666
667 static int goto_next_marker(unsigned char **f, int *size, int *marker)
668 {
669         int marker_size = 2;
670
671         *marker = MARKER_UNKNOWN;
672
673         /* It is safe to access the marker and its size since we have checked
674          * the SOI and this function guaranties the whole next marker is
675          * available
676          */
677         if (*(*f+1) != MARKER_SOI)
678                 {
679                 marker_size += get_marker_size(*f);
680                 }
681
682         *size -= marker_size;
683
684         /* size should be at least 4, so we can read the marker and its size
685          * and check data are actually available
686          */
687         if (*size < 4) return -1;
688
689         /* Jump to the next marker and be sure it begins with 0xFF
690          */
691         *f += marker_size;
692         if (**f != 0xFF) return -1;
693
694         if (get_marker_size(*f)+2 > *size) return -1;
695
696         *marker = *(*f+1);
697
698         return 0;
699 }
700
701 /*
702  *-------------------------------------------------------------------
703  * IFD utils
704  *-------------------------------------------------------------------
705  */
706
707 static const ExifMarker *exif_marker_from_tag(guint16 tag, const ExifMarker *list)
708 {
709         gint i = 0;
710
711         if (!list) return NULL;
712
713         while (list[i].tag != 0 && list[i].tag != tag)
714                 {
715                 i++;
716                 }
717
718         return (list[i].tag == 0 ? NULL : &list[i]);
719 }
720
721 static void rational_from_data(ExifRational *r, void *src, ExifByteOrder byte_order)
722 {
723         r->num = exif_byte_swab_int32(*(guint32*)src, byte_order);
724         r->den = exif_byte_swab_int32(*(guint32*)(src + sizeof(guint32)), byte_order);
725 }
726
727 void exif_item_copy_data(ExifItem *item, void *src, guint len,
728                          ExifFormatType src_format, ExifByteOrder byte_order)
729 {
730         gint bs;
731         gint ne;
732         gpointer dest;
733         gint i;
734
735         bs = ExifFormatList[item->format].size;
736         ne = item->elements;
737         dest = item->data;
738
739         if (!dest || len > item->data_len)
740                 {
741                 printf("exif tag %s data size mismatch\n", exif_item_get_tag_name(item));
742                 return;
743                 }
744
745         switch (item->format)
746                 {
747                 case EXIF_FORMAT_UNKNOWN:
748                         break;
749                 case EXIF_FORMAT_BYTE_UNSIGNED:
750                 case EXIF_FORMAT_BYTE:
751                 case EXIF_FORMAT_UNDEFINED:
752                         memcpy(dest, src, len);
753                         break;
754                 case EXIF_FORMAT_STRING:
755                         memcpy(dest, src, len);
756                         /* string is NULL terminated, make sure this is true */
757                         if (((char *)dest)[len - 1] != '\0') ((char *)dest)[len - 1] = '\0';
758                         break;
759                 case EXIF_FORMAT_SHORT_UNSIGNED:
760                 case EXIF_FORMAT_SHORT:
761                         for (i = 0; i < ne; i++)
762                                 {
763                                 ((guint16 *)dest)[i] = exif_byte_swab_int16(*(guint16*)(src + i * bs), byte_order);
764                                 }
765                         break;
766                 case EXIF_FORMAT_LONG_UNSIGNED:
767                 case EXIF_FORMAT_LONG:
768                         if (src_format == EXIF_FORMAT_SHORT_UNSIGNED ||
769                             src_format == EXIF_FORMAT_SHORT)
770                                 {
771                                 /* a short fits into a long, so allow it */
772                                 int ss;
773
774                                 ss = ExifFormatList[src_format].size;
775                                 for (i = 0; i < ne; i++)
776                                         {
777                                         ((gint32 *)dest)[i] =
778                                                 (gint32)exif_byte_swab_int16(*(guint16*)(src + i * ss), byte_order);
779                                         }
780                                 }
781                         else
782                                 {
783                                 for (i = 0; i < ne; i++)
784                                         {
785                                         ((gint32 *)dest)[i] =
786                                                 exif_byte_swab_int32(*(guint32*)(src + i * bs), byte_order);
787                                         }
788                                 }
789                         break;
790                 case EXIF_FORMAT_RATIONAL_UNSIGNED:
791                 case EXIF_FORMAT_RATIONAL:
792                         for (i = 0; i < ne; i++)
793                                 {
794                                 rational_from_data(&((ExifRational *)dest)[i], src + i * bs, byte_order);
795                                 }
796                         break;
797                 case EXIF_FORMAT_FLOAT:
798                         for (i = 0; i < ne; i++)
799                                 {
800                                 ((float *)dest)[i] = exif_byte_swab_int32(*(guint32*)(src + i * bs), byte_order);
801                                 }
802                         break;
803                 case EXIF_FORMAT_DOUBLE:
804                         for (i = 0; i < ne; i++)
805                                 {
806                                 ExifRational r;
807
808                                 rational_from_data(&r, src + i * bs, byte_order);
809                                 if (r.den) ((double *)dest)[i] = (double)r.num / r.den;
810                                 }
811                         break;
812                 }
813 }
814
815 static gint exif_parse_IFD_entry(ExifData *exif, unsigned char *tiff, guint offset,
816                                  guint size, ExifByteOrder byte_order,
817                                  const ExifMarker *list)
818 {
819         IFDEntry *ent = (IFDEntry*)(tiff+offset);
820         guint32 swabed_data;
821         void *data;
822         guint data_len;
823         const ExifMarker *marker;
824         ExifItem *item;
825
826         ent->tag = exif_byte_swab_int16(ent->tag, byte_order);
827         ent->format = exif_byte_swab_int16(ent->format, byte_order);
828         ent->nb = exif_byte_swab_int32(ent->nb, byte_order);
829         swabed_data = exif_byte_swab_int32(ent->data, byte_order);
830
831         /* Check tag type. If it does not match, either the format is wrong,
832          * either it is a unknown tag; so it is not really an error.
833          */
834         marker = exif_marker_from_tag(ent->tag, list);
835         if (!marker)
836                 {
837                 if (ent->format > EXIF_FORMAT_DOUBLE)
838                         {
839                         printf("warning: exif tag 0x%4x has invalid format %d\n", ent->tag, ent->format);
840                         return 0;
841                         }
842                 /* allow non recognized tags to be displayed */
843                 marker = &ExifUnknownMarkersList[ent->format];
844                 }
845         if (marker->format != ent->format)
846                 {
847                 /* Some cameras got mixed up signed/unsigned_rational
848                  * eg KODAK DC4800 on object_distance tag
849                  *
850                  * FIXME: what exactly is this test trying to do?
851                  * ok, so this test is to allow the case of swapped signed/unsigned mismatch to leak through?
852                  */
853                 if ( !(marker->format == EXIF_FORMAT_RATIONAL_UNSIGNED && ent->format == EXIF_FORMAT_RATIONAL) &&
854                      !(marker->format == EXIF_FORMAT_RATIONAL && ent->format == EXIF_FORMAT_RATIONAL_UNSIGNED) &&
855                         /* short fits into a long so allow this mismatch
856                          * as well (some tags allowed to be unsigned short _or_ unsigned long)
857                          */
858                      !(marker->format == EXIF_FORMAT_LONG_UNSIGNED && ent->format == EXIF_FORMAT_SHORT_UNSIGNED) )
859                         {
860                         if (ent->format <= EXIF_FORMAT_DOUBLE)
861                                 {
862                                 printf("warning: exif tag %s format mismatch, found %s exif spec requests %s\n",
863                                         marker->key, ExifFormatList[ent->format].short_name,
864                                         ExifFormatList[marker->format].short_name);
865                                 }
866                         else
867                                 {
868                                 printf("warning: exif tag %s format mismatch, found unknown id %d exif spec requests %d (%s)\n",
869                                         marker->key, ent->format, marker->format,
870                                         ExifFormatList[marker->format].short_name);
871                                 }
872                         return 0;
873                         }
874                 }
875
876         /* Where is the data, is it available?
877          */
878         if (marker->components > 0 && marker->components != ent->nb)
879                 {
880                 printf("warning: exif tag %s has %d elements, exif spec requests %d\n",
881                         marker->key, ent->nb, marker->components);
882                 }
883         data_len = ExifFormatList[marker->format].size * ent->nb;
884         if (data_len > sizeof(ent->data))
885                 {
886                 if (size < swabed_data+data_len)
887                         {
888                         printf("warning: exif tag %s will overrun IFD segment, ignored.\n", marker->key);
889                         return -1;
890                         }
891                 data = (void*)tiff + swabed_data;
892                 }
893         else
894                 {
895                 data = (void*)(&(ent->data));
896                 }
897
898         item = exif_item_new(marker->format, ent->tag, ent->nb, marker);
899         exif_item_copy_data(item, data, data_len, ent->format, byte_order);
900         exif->items = g_list_prepend(exif->items, item);
901
902         if (list == ExifKnownMarkersList)
903                 {
904                 switch (item->tag)
905                         {
906                         case TAG_EXIFOFFSET:
907                                 exif_parse_IFD_table(exif, tiff, swabed_data, size, byte_order, list);
908                                 break;
909                         case TAG_EXIFMAKERNOTE:
910                                 format_exif_makernote_parse(exif, tiff, swabed_data, size, byte_order);
911                                 break;
912                         }
913                 }
914
915         return 0;
916 }
917
918 gint exif_parse_IFD_table(ExifData *exif,
919                           unsigned char *tiff, guint offset,
920                           guint size, ExifByteOrder byte_order,
921                           const ExifMarker *list)
922 {
923         gint i, nb_entries;
924
925         /* We should be able to read number of entries in IFD0) */
926         if (size < offset+2) return -1;
927
928         nb_entries = exif_byte_get_int16(tiff+offset, byte_order);
929
930         /* Entries and next IFD offset must be readable */
931         if (size < offset+nb_entries*12+4) return -1;
932
933         for (i=0; i<nb_entries; ++i)
934                 {
935                 exif_parse_IFD_entry(exif, tiff, offset+2+i*sizeof(IFDEntry), size, byte_order, list);
936                 }
937
938         return 0;
939 }
940
941 /*
942  *-------------------------------------------------------------------
943  * file formats
944  *-------------------------------------------------------------------
945  */
946
947 gint exif_parse_TIFF(ExifData *exif, unsigned char *tiff, guint size, ExifMarker *list)
948 {
949         ExifByteOrder byte_order;
950         guint offset=0;
951
952         if (size < sizeof(TIFFHeader))
953                 {
954                 return -1;
955                 }
956
957         if (strncmp(((TIFFHeader*)tiff)->byte_order, "II", 2) == 0)
958                 {
959                 byte_order = EXIF_BYTE_ORDER_INTEL;
960                 }
961         else if (strncmp(((TIFFHeader*)tiff)->byte_order, "MM", 2) == 0)
962                 {
963                 byte_order = EXIF_BYTE_ORDER_MOTOROLA;
964                 }
965         else
966                 {
967                 return -1;
968                 }
969
970         if (exif_byte_swab_int16(((TIFFHeader*)tiff)->magic, byte_order) != 0x002A)
971                 {
972                 return -1;
973                 }
974
975         offset = exif_byte_swab_int32(((TIFFHeader*)tiff)->IFD_offset, byte_order);
976
977         return exif_parse_IFD_table(exif, tiff, offset, size, byte_order, list);
978 }
979
980 static gint exif_parse_JPEG(ExifData *exif, unsigned char *f, guint size, ExifMarker *list)
981 {
982         guint marker, marker_size;
983
984         if (size<2 || *f!=0xFF || *(f+1)!=MARKER_SOI)
985                 {
986                 return -2;
987                 }
988
989         do {
990                 if (goto_next_marker(&f, &size, &marker) == -1)
991                         {
992                         break;
993                         }
994         } while (marker != MARKER_APP1);
995
996         if (marker != MARKER_APP1)
997                 {
998                 return -2;
999                 }
1000
1001         marker_size = get_marker_size(f)-2;
1002                 
1003         if (marker_size<6 || strncmp((char*)f+4, "Exif\0\0", 6)!=0)
1004                 {
1005                 return -2;
1006                 }
1007
1008         return exif_parse_TIFF(exif, f+10, marker_size-6, list);
1009 }
1010
1011 static gint map_file(const gchar *path, void **mapping, int *size)
1012 {
1013         int fd;
1014         struct stat fs;
1015
1016         if ((fd = open(path, O_RDONLY)) == -1)
1017                 {
1018                 perror(path);
1019                 return -1;
1020                 }
1021
1022         if (fstat(fd, &fs) == -1)
1023                 {
1024                 perror(path);
1025                 close(fd);
1026                 return -1;
1027                 }
1028
1029         *size = fs.st_size;
1030
1031         if ((*mapping = mmap(0, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
1032                 {
1033                 perror(path);
1034                 close(fd);
1035                 return -1;
1036                 }
1037
1038         close(fd);
1039         return 0;
1040 }
1041
1042 static gint unmap_file(void *mapping, int size)
1043 {
1044         if (munmap(mapping, size) == -1)
1045                 {
1046                 perror("munmap");
1047                 return -1;
1048                 }
1049
1050         return 0;
1051 }
1052
1053 void exif_free(ExifData *exif)
1054 {
1055         GList *work;
1056
1057         if (!exif) return;
1058
1059         work = exif->items;
1060         while (work)
1061                 {
1062                 ExifItem *item = work->data;
1063                 work = work->next;
1064                 exif_item_free(item);
1065                 }
1066
1067         g_list_free(exif->items);
1068         g_free(exif);
1069 }
1070
1071 ExifData *exif_read(const gchar *path)
1072 {
1073         ExifData *exif;
1074         void *f;
1075         int size, res;
1076         gchar *pathl;
1077
1078         if (!path) return NULL;
1079
1080         pathl = path_from_utf8(path);
1081         if (map_file(pathl, &f, &size) == -1)
1082                 {
1083                 g_free(pathl);
1084                 return NULL;
1085                 }
1086         g_free(pathl);
1087
1088         exif = g_new0(ExifData, 1);
1089         exif->items = NULL;
1090
1091         if ((res = exif_parse_JPEG(exif, (unsigned char *)f, size, ExifKnownMarkersList)) == -2)
1092                 {
1093                 res = exif_parse_TIFF(exif, (unsigned char *)f, size, ExifKnownMarkersList);
1094                 }
1095
1096         if (res != 0)
1097                 {
1098                 guint32 offset = 0;
1099                 
1100                 if (format_raw_img_exif_offsets(f, size, NULL, &offset))
1101                         {
1102                         res = exif_parse_TIFF(exif, (unsigned char*)f + offset, size - offset, ExifKnownMarkersList);
1103                         }
1104                 }
1105
1106         if (res != 0)
1107                 {
1108                 exif_free(exif);
1109                 exif = NULL;
1110                 }
1111
1112         unmap_file(f, size);
1113
1114         if (exif) exif->items = g_list_reverse(exif->items);
1115
1116 #if 0
1117         exif_write_data_list(exif, stdout, TRUE);
1118         exif_write_data_list(exif, stdout, FALSE);
1119 #endif
1120
1121         return exif;
1122 }
1123
1124 ExifItem *exif_get_item(ExifData *exif, const gchar *key)
1125 {
1126         GList *work;
1127
1128         if (!key) return NULL;
1129
1130         work = exif->items;
1131         while (work)
1132                 {
1133                 ExifItem *item;
1134
1135                 item = work->data;
1136                 work = work->next;
1137                 if (item->marker->key && strcmp(key, item->marker->key) == 0) return item;
1138                 }
1139         return NULL;
1140 }
1141
1142 gchar *exif_item_get_data_as_text(ExifItem *item)
1143 {
1144         const ExifMarker *marker;
1145         gpointer data;
1146         GString *string;
1147         gchar *text;
1148         gint ne;
1149         gint i;
1150
1151         if (!item) return NULL;
1152
1153         marker = item->marker;
1154         if (!marker) return NULL;
1155
1156         data = item->data;
1157         ne = item->elements;
1158         string = g_string_new("");
1159         switch (item->format)
1160                 {
1161                 case EXIF_FORMAT_UNKNOWN:
1162                         break;
1163                 case EXIF_FORMAT_BYTE_UNSIGNED:
1164                 case EXIF_FORMAT_BYTE:
1165                 case EXIF_FORMAT_UNDEFINED:
1166                         if (ne == 1 && marker->list)
1167                                 {
1168                                 gchar *result;
1169                                 unsigned char val;
1170
1171                                 if (item->format == EXIF_FORMAT_BYTE_UNSIGNED ||
1172                                     item->format == EXIF_FORMAT_UNDEFINED)
1173                                         {
1174                                         val = ((unsigned char *)data)[0];
1175                                         }
1176                                 else
1177                                         {
1178                                         val = (unsigned char)(((signed char *)data)[0]);
1179                                         }
1180
1181                                 result = text_list_find_value(marker->list, (guint)val);
1182                                 string = g_string_append(string, result);
1183                                 g_free(result);
1184                                 }
1185                         else
1186                                 {
1187                                 string = string_append_raw_bytes(string, data, ne);
1188                                 }
1189                         break;
1190                 case EXIF_FORMAT_STRING:
1191                         string = g_string_append(string, (gchar *)(item->data));
1192                         break;
1193                 case EXIF_FORMAT_SHORT_UNSIGNED:
1194                         if (ne == 1 && marker->list)
1195                                 {
1196                                 gchar *result;
1197
1198                                 result = text_list_find_value(marker->list, ((unsigned short *)data)[0]);
1199                                 string = g_string_append(string, result);
1200                                 g_free(result);
1201                                 }
1202                         else for (i = 0; i < ne; i++)
1203                                 {
1204                                 g_string_append_printf(string, "%s%hd", (i > 0) ? ", " : "",
1205                                                         ((unsigned short *)data)[i]);
1206                                 }
1207                         break;
1208                 case EXIF_FORMAT_LONG_UNSIGNED:
1209                         for (i = 0; i < ne; i++)
1210                                 {
1211                                 g_string_append_printf(string, "%s%ld", (i > 0) ? ", " : "",
1212                                                         ((unsigned long *)data)[i]);
1213                                 }
1214                         break;
1215                 case EXIF_FORMAT_RATIONAL_UNSIGNED:
1216                         for (i = 0; i < ne; i++)
1217                                 {
1218                                 ExifRational *r;
1219
1220                                 r = &((ExifRational *)data)[i];
1221                                 g_string_append_printf(string, "%s%ld/%ld", (i > 0) ? ", " : "",
1222                                                         (unsigned long)r->num, (unsigned long)r->den);
1223                                 }
1224                         break;
1225                 case EXIF_FORMAT_SHORT:
1226                         for (i = 0; i < ne; i++)
1227                                 {
1228                                 g_string_append_printf(string, "%s%hd", (i > 0) ? ", " : "",
1229                                                         ((short *)data)[i]);
1230                                 }
1231                         break;
1232                 case EXIF_FORMAT_LONG:
1233                         for (i = 0; i < ne; i++)
1234                                 {
1235                                 g_string_append_printf(string, "%s%ld", (i > 0) ? ", " : "",
1236                                                         ((long *)data)[i]);
1237                                 }
1238                         break;
1239                 case EXIF_FORMAT_RATIONAL:
1240                         for (i = 0; i < ne; i++)
1241                                 {
1242                                 ExifRational *r;
1243
1244                                 r = &((ExifRational *)data)[i];
1245                                 g_string_append_printf(string, "%s%ld/%ld", (i > 0) ? ", " : "",
1246                                                         (long)r->num, (long)r->den);
1247                                 }
1248                         break;
1249                 case EXIF_FORMAT_FLOAT:
1250                         for (i = 0; i < ne; i++)
1251                                 {
1252                                 g_string_append_printf(string, "%s%f", (i > 0) ? ", " : "",
1253                                                         ((float *)data)[i]);
1254                                 }
1255                         break;
1256                 case EXIF_FORMAT_DOUBLE:
1257                         for (i = 0; i < ne; i++)
1258                                 {
1259                                 g_string_append_printf(string, "%s%f", (i > 0) ? ", " : "",
1260                                                         ((double *)data)[i]);
1261                                 }
1262                         break;
1263                 }
1264
1265         text = g_strdup(string->str);
1266         g_string_free(string, TRUE);
1267
1268         return text;
1269 }
1270
1271 gint exif_item_get_integer(ExifItem *item, gint *value)
1272 {
1273         if (!item) return FALSE;
1274
1275         switch (item->format)
1276                 {
1277                 case EXIF_FORMAT_SHORT:
1278                         *value = (gint)(((short *)(item->data))[0]);
1279                         return TRUE;
1280                         break;
1281                 case EXIF_FORMAT_SHORT_UNSIGNED:
1282                         *value = (gint)(((unsigned short *)(item->data))[0]);
1283                         return TRUE;
1284                         break;
1285                 case EXIF_FORMAT_LONG:
1286                         *value = (gint)(((long *)(item->data))[0]);
1287                         return TRUE;
1288                         break;
1289                 case EXIF_FORMAT_LONG_UNSIGNED:
1290                         /* FIXME: overflow possible */
1291                         *value = (gint)(((unsigned long *)(item->data))[0]);
1292                         return TRUE;
1293                 default:
1294                         /* all other type return FALSE */
1295                         break;
1296                 }
1297         return FALSE;
1298 }
1299
1300 gint exif_get_integer(ExifData *exif, const gchar *key, gint *value)
1301 {
1302         ExifItem *item;
1303
1304         item = exif_get_item(exif, key);
1305         return exif_item_get_integer(item, value);
1306 }
1307
1308 ExifRational *exif_item_get_rational(ExifItem *item, gint *sign)
1309 {
1310         if (!item) return NULL;
1311
1312         if (item->format == EXIF_FORMAT_RATIONAL ||
1313             item->format == EXIF_FORMAT_RATIONAL_UNSIGNED)
1314                 {
1315                 if (sign) *sign = (item->format == EXIF_FORMAT_RATIONAL);
1316                 return &((ExifRational *)(item->data))[0];
1317                 }
1318
1319         return NULL;
1320 }
1321
1322 ExifRational *exif_get_rational(ExifData *exif, const gchar *key, gint *sign)
1323 {
1324         ExifItem *item;
1325
1326         item = exif_get_item(exif, key);
1327         return exif_item_get_rational(item, sign);
1328 }
1329
1330 double exif_rational_to_double(ExifRational *r, gint sign)
1331 {
1332         if (!r || r->den == 0.0) return 0.0;
1333
1334         if (sign) return (double)((int)r->num) / (double)((int)r->den);
1335         return (double)r->num / r->den;
1336 }
1337
1338 static double exif_get_rational_as_double(ExifData *exif, const gchar *key)
1339 {
1340         ExifRational *r;
1341         gint sign;
1342
1343         r = exif_get_rational(exif, key, &sign);
1344         return exif_rational_to_double(r, sign);
1345 }
1346
1347 static GString *append_comma_text(GString *string, const gchar *text)
1348 {
1349         string = g_string_append(string, ", ");
1350         string = g_string_append(string, text);
1351
1352         return string;
1353 }
1354
1355 static gchar *exif_get_formatted_by_key(ExifData *exif, const gchar *key, gint *key_valid)
1356 {
1357         /* must begin with f, else not formatted */
1358         if (key[0] != 'f')
1359                 {
1360                 if (key_valid) *key_valid = FALSE;
1361                 return NULL;
1362                 }
1363
1364         if (key_valid) *key_valid = TRUE;
1365
1366         if (strcmp(key, "fCamera") == 0)
1367                 {
1368                 gchar *text;
1369                 gchar *make = exif_get_data_as_text(exif, "Make");
1370                 gchar *model = exif_get_data_as_text(exif, "Model");
1371                 gchar *software = exif_get_data_as_text(exif, "Software");
1372
1373                 text = g_strdup_printf("%s%s%s%s%s%s", (make) ? make : "", ((make) && (model)) ? " " : "",
1374                                                        (model) ? model : "",
1375                                                        (software) ? " (" : "",
1376                                                        (software) ? software : "",
1377                                                        (software) ? ")" : "");
1378
1379                 g_free(make);
1380                 g_free(model);
1381                 g_free(software);
1382                 return text;
1383                 }
1384         if (strcmp(key, "fDateTime") == 0)
1385                 {
1386                 gchar *text = exif_get_data_as_text(exif, "DateTimeOriginal");
1387                 gchar *subsec = NULL;
1388                 if (text) subsec = exif_get_data_as_text(exif, "SubsecTimeOriginal");
1389                 if (!text)
1390                         {
1391                         text = exif_get_data_as_text(exif, "DateTime");
1392                         if (text) subsec = exif_get_data_as_text(exif, "SubsecTime");
1393                         }
1394                 if (subsec)
1395                         {
1396                         gchar *tmp = text;
1397                         text = g_strconcat(tmp, ".", subsec, NULL);
1398                         g_free(tmp);
1399                         g_free(subsec);
1400                         }
1401                 return text;
1402                 }
1403         if (strcmp(key, "fShutterSpeed") == 0)
1404                 {
1405                 ExifRational *r;
1406
1407                 r = exif_get_rational(exif, "ExposureTime", NULL);
1408                 if (r && r->num && r->den)
1409                         {
1410                         double n = (double)r->den / (double)r->num;
1411                         return g_strdup_printf("%s%.0fs", n > 1.0 ? "1/" : "",
1412                                                           n > 1.0 ? n : 1.0 / n);
1413                         }
1414                 r = exif_get_rational(exif, "ShutterSpeedValue", NULL);
1415                 if (r && r->num  && r->den)
1416                         {
1417                         double n = pow(2.0, exif_rational_to_double(r, TRUE));
1418
1419                         /* Correct exposure time to avoid values like 1/91s (seen on Minolta DImage 7) */
1420                         if (n > 1.0 && (int)n - ((int)(n/10))*10 == 1) n--;
1421
1422                         return g_strdup_printf("%s%.0fs", n > 1.0 ? "1/" : "",
1423                                                           n > 1.0 ? floor(n) : 1.0 / n);        
1424                         }
1425                 return NULL;
1426                 }
1427         if (strcmp(key, "fAperture") == 0)
1428                 {
1429                 double n;
1430
1431                 n = exif_get_rational_as_double(exif, "FNumber");
1432                 if (n == 0.0) n = exif_get_rational_as_double(exif, "ApertureValue");
1433                 if (n == 0.0) return NULL;
1434
1435                 return g_strdup_printf("f/%.1f", n);
1436                 }
1437         if (strcmp(key, "fExposureBias") == 0)
1438                 {
1439                 ExifRational *r;
1440                 gint sign;
1441                 double n;
1442
1443                 r = exif_get_rational(exif, "ExposureBiasValue", &sign);
1444                 if (!r) return NULL;
1445
1446                 n = exif_rational_to_double(r, sign);
1447                 return g_strdup_printf("%+.1f", n);
1448                 }
1449         if (strcmp(key, "fFocalLength") == 0)
1450                 {
1451                 double n;
1452
1453                 n = exif_get_rational_as_double(exif, "FocalLength");
1454                 if (n == 0.0) return NULL;
1455                 return g_strdup_printf("%.2f mm", n);
1456                 }
1457         if (strcmp(key, "fISOSpeedRating") == 0)
1458                 {
1459                 gchar *text;
1460
1461                 text = exif_get_data_as_text(exif, "ISOSpeedRatings");
1462                 /* kodak may set this instead */
1463                 if (!text) text = exif_get_data_as_text(exif, "ExposureIndex");
1464                 return text;
1465                 }
1466         if (strcmp(key, "fSubjectDistance") == 0)
1467                 {
1468                 ExifRational *r;
1469                 gint sign;
1470                 double n;
1471
1472                 r = exif_get_rational(exif, "SubjectDistance", &sign);
1473                 if (!r) return NULL;
1474
1475                 if ((long)r->num == 0xffffffff) return g_strdup(_("infinity"));
1476                 if ((long)r->num == 0) return g_strdup(_("unknown"));
1477
1478                 n = exif_rational_to_double(r, sign);
1479                 if (n == 0.0) return _("unknown");
1480                 return g_strdup_printf("%.3f m", n);
1481                 }
1482         if (strcmp(key, "fFlash") == 0)
1483                 {
1484                 /* grr, flash is a bitmask... */
1485                 GString *string;
1486                 gchar *text;
1487                 gint n;
1488                 gint v;
1489
1490                 if (!exif_get_integer(exif, "Flash", &n)) return NULL;
1491
1492                 /* Exif 2.1 only defines first 3 bits */
1493                 if (n <= 0x07) return g_strdup(text_list_find_value(ExifFlashList, n));
1494
1495                 /* must be Exif 2.2 */
1496                 string = g_string_new("");
1497
1498                 /* flash fired (bit 0) */
1499                 string = g_string_append(string, (n & 0x01) ? _("yes") : _("no"));
1500
1501                 /* flash mode (bits 3, 4) */
1502                 v = (n >> 3) & 0x03;
1503                 if (v) string = append_comma_text(string, _("mode:"));
1504                 switch (v)
1505                         {
1506                         case 1:
1507                                 string = g_string_append(string, _("on"));
1508                                 break;
1509                         case 2:
1510                                 string = g_string_append(string, _("off"));
1511                                 break;
1512                         case 3:
1513                                 string = g_string_append(string, _("auto"));
1514                                 break;
1515                         }
1516
1517                 /* return light (bits 1, 2) */
1518                 v = (n >> 1) & 0x03;
1519                 if (v == 2) string = append_comma_text(string, _("not detected by strobe"));
1520                 if (v == 3) string = append_comma_text(string, _("detected by strobe"));
1521
1522                 /* we ignore flash function (bit 5) */
1523
1524                 /* red-eye (bit 6) */
1525                 if ((n >> 5) & 0x01) string = append_comma_text(string, _("red-eye reduction"));
1526
1527                 text = string->str;
1528                 g_string_free(string, FALSE);
1529                 return text;
1530                 }
1531         if (strcmp(key, "fResolution") == 0)
1532                 {
1533                 ExifRational *rx, *ry;
1534                 gchar *units;
1535                 gchar *text;
1536
1537                 rx = exif_get_rational(exif, "XResolution", NULL);
1538                 ry = exif_get_rational(exif, "YResolution", NULL);
1539                 if (!rx || !ry) return NULL;
1540
1541                 units = exif_get_data_as_text(exif, "ResolutionUnit");
1542                 text = g_strdup_printf("%0.f x %0.f (%s/%s)", rx->den ? (double)rx->num / rx->den : 1.0,
1543                                                               ry->den ? (double)ry->num / ry->den : 1.0,
1544                                                               _("dot"), (units) ? units : _("unknown"));
1545
1546                 g_free(units);
1547                 return text;
1548                 }
1549
1550         if (key_valid) *key_valid = FALSE;
1551         return NULL;
1552 }
1553
1554 gchar *exif_get_data_as_text(ExifData *exif, const gchar *key)
1555 {
1556         ExifItem *item;
1557         gchar *text;
1558         gint key_valid;
1559
1560         if (!key) return NULL;
1561
1562         text = exif_get_formatted_by_key(exif, key, &key_valid);
1563         if (key_valid) return text;
1564
1565         item = exif_get_item(exif, key);
1566         if (item) return exif_item_get_data_as_text(item);
1567
1568         return NULL;
1569 }
1570
1571 const gchar *exif_get_description_by_key(const gchar *key)
1572 {
1573         gint i;
1574
1575         if (!key) return NULL;
1576
1577         i = 0;
1578         while (ExifFormattedList[i].key != NULL)
1579                 {
1580                 if (strcmp(key, ExifFormattedList[i].key) == 0) return _(ExifFormattedList[i].description);
1581                 i++;
1582                 }
1583
1584         i = 0;
1585         while (ExifKnownMarkersList[i].tag > 0)
1586                 {
1587                 if (strcmp(key, ExifKnownMarkersList[i].key) == 0) return _(ExifKnownMarkersList[i].description);
1588                 i++;
1589                 }
1590
1591         return NULL;
1592 }
1593
1594 static void exif_write_item(FILE *f, ExifItem *item)
1595 {
1596         gchar *text;
1597
1598         text = exif_item_get_data_as_text(item);
1599         if (text)
1600                 {
1601                 fprintf(f, "%4x %9s %30s %s\n", item->tag, ExifFormatList[item->format].short_name,
1602                         exif_item_get_tag_name(item), text);
1603                 }
1604         g_free(text);
1605 }
1606
1607 void exif_write_data_list(ExifData *exif, FILE *f, gint human_readable_list)
1608 {
1609         if (!f || !exif) return;
1610
1611         fprintf(f, " tag   format                             key value\n");
1612         fprintf(f, "----------------------------------------------------\n");
1613
1614         if (human_readable_list)
1615                 {
1616                 gint i;
1617
1618                 i = 0;
1619                 while (ExifFormattedList[i].key)
1620                         {
1621                         gchar *text;
1622
1623                         text = exif_get_formatted_by_key(exif, ExifFormattedList[i].key, NULL);
1624                         if (text)
1625                                 {
1626                                 fprintf(f, "     %9s %30s %s\n", "string", ExifFormattedList[i].key, text);
1627                                 }
1628                         i++;
1629                         }
1630                 }
1631         else
1632                 {
1633                 GList *work;
1634
1635                 work = exif->items;
1636                 while (work)
1637                         {
1638                         ExifItem *item;
1639
1640                         item = work->data;
1641                         work = work->next;
1642
1643                         exif_write_item(f, item);
1644                         }
1645                 }
1646         fprintf(f, "----------------------------------------------------\n");
1647 }
1648