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