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