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