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