more exiv2 fixes
[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
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,               "Exif.Image.ImageDescription",  N_("Image description"), NULL },
292 { 0x010f, EXIF_FORMAT_STRING, -1,               "Exif.Image.Make",                      "Camera make", NULL },
293 { 0x0110, EXIF_FORMAT_STRING, -1,               "Exif.Image.Model",             "Camera model", NULL },
294 { 0x0112, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Image.Orientation",               N_("Orientation"), ExifOrientationList },
295 { 0x011a, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Image.XResolution",               "X resolution", NULL },
296 { 0x011b, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Image.YResolution",               "Y Resolution", NULL },
297 { 0x0128, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Image.ResolutionUnit",    "Resolution units", ExifUnitList },
298 { 0x0131, EXIF_FORMAT_STRING, -1,               "Exif.Image.Software",          "Firmware", NULL },
299 { 0x0132, EXIF_FORMAT_STRING, 20,               "Exif.Image.DateTime",          N_("Date"), NULL },
300 { 0x013e, EXIF_FORMAT_RATIONAL_UNSIGNED, 2,     "Exif.Image.WhitePoint",                "White point", NULL },
301 { 0x013f, EXIF_FORMAT_RATIONAL_UNSIGNED, 6,     "Exif.Image.PrimaryChromaticities","Primary chromaticities", NULL },
302 { 0x0211, EXIF_FORMAT_RATIONAL_UNSIGNED, 3,     "Exif.Image.YCbCrCoefficients", "YCbCy coefficients", NULL },
303 { 0x0213, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Image.YCbCrPositioning",  "YCbCr positioning", ExifYCbCrPosList },
304 { 0x0214, EXIF_FORMAT_RATIONAL_UNSIGNED, 6,     "Exif.Image.ReferenceBlackWhite",       "Black white reference", NULL },
305 { 0x8298, EXIF_FORMAT_STRING, -1,               "Exif.Image.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,     "Exif.Photo.ExposureTime",              "Exposure time (seconds)", NULL },
309 { 0x829d, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.FNumber",           "FNumber", NULL },
310 { 0x8822, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.ExposureProgram",   N_("Exposure program"), ExifExposureProgramList },
311 { 0x8824, EXIF_FORMAT_STRING, -1,               "Exif.Photo.SpectralSensitivity",       "Spectral Sensitivity", NULL },
312 { 0x8827, EXIF_FORMAT_SHORT_UNSIGNED, -1,       "Exif.Photo.ISOSpeedRatings",   N_("ISO sensitivity"), NULL },
313 { 0x8828, EXIF_FORMAT_UNDEFINED, -1,            "Exif.Photo.OECF",                      "Optoelectric conversion factor", NULL },
314 { 0x9000, EXIF_FORMAT_UNDEFINED, 4,             "Exif.Photo.ExifVersion",               "Exif version", NULL },
315 { 0x9003, EXIF_FORMAT_STRING, 20,               "Exif.Photo.DateTimeOriginal",  N_("Date original"), NULL },
316 { 0x9004, EXIF_FORMAT_STRING, 20,               "Exif.Photo.DateTimeDigitized", N_("Date digitized"), NULL },
317 { 0x9101, EXIF_FORMAT_UNDEFINED, -1,            "Exif.Photo.ComponentsConfiguration","Pixel format", NULL },
318 { 0x9102, EXIF_FORMAT_RATIONAL_UNSIGNED,1,      "Exif.Photo.CompressedBitsPerPixel","Compression ratio", NULL },
319 { 0x9201, EXIF_FORMAT_RATIONAL, 1,              "Exif.Photo.ShutterSpeedValue", N_("Shutter speed"), NULL },
320 { 0x9202, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.ApertureValue",     N_("Aperture"), NULL },
321 { 0x9203, EXIF_FORMAT_RATIONAL, 1,              "Exif.Photo.BrightnessValue",   "Brightness", NULL },
322 { 0x9204, EXIF_FORMAT_RATIONAL, 1,              "Exif.Photo.ExposureBiasValue", N_("Exposure bias"), NULL },
323 { 0x9205, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.MaxApertureValue",  "Maximum aperture", NULL },
324 { 0x9206, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.SubjectDistance",   N_("Subject distance"), NULL },
325 { 0x9207, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.MeteringMode",              N_("Metering mode"), ExifMeteringModeList },
326 { 0x9208, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.LightSource",               N_("Light source"), ExifLightSourceList },
327 { 0x9209, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.Flash",             N_("Flash"), ExifFlashList },
328 { 0x920a, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.FocalLength",               N_("Focal length"), NULL },
329 { 0x9214, EXIF_FORMAT_SHORT_UNSIGNED, -1,       "Exif.Photo.SubjectArea",               "Subject area", NULL },
330 { 0x927c, EXIF_FORMAT_UNDEFINED, -1,            "Exif.Photo.MakerNote",         "MakerNote", NULL },
331 { 0x9286, EXIF_FORMAT_UNDEFINED, -1,            "Exif.Photo.UserComment",               "UserComment", NULL },
332 { 0x9290, EXIF_FORMAT_STRING, -1,               "Exif.Photo.SubSecTime",                "Subsecond time", NULL },
333 { 0x9291, EXIF_FORMAT_STRING, -1,               "Exif.Photo.SubSecTimeOriginal",        "Subsecond time original", NULL },
334 { 0x9292, EXIF_FORMAT_STRING, -1,               "Exif.Photo.SubSecTimeDigitized",       "Subsecond time digitized", NULL },
335 { 0xa000, EXIF_FORMAT_UNDEFINED, 4,             "FlashPixVersion",      "FlashPix version", NULL },
336 { 0xa001, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.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,               "Exif.Photo.RelatedSoundFile",  "Audio data", NULL },
341 { 0xa005, EXIF_FORMAT_LONG_UNSIGNED, 1,         "ExifInteroperabilityOffset", "ExifR98 extension", NULL },
342 { 0xa20b, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.FlashEnergy",               "Flash strength", NULL },
343 { 0xa20c, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.SpatialFrequencyResponse","Spatial frequency response", NULL },
344 { 0xa20e, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.FocalPlaneXResolution", "X Pixel density", NULL },
345 { 0xa20f, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.FocalPlaneYResolution", "Y Pixel density", NULL },
346 { 0xa210, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.FocalPlaneResolutionUnit", "Pixel density units", ExifUnitList },
347 { 0x0214, EXIF_FORMAT_SHORT_UNSIGNED, 2,        "Exif.Photo.SubjectLocation",   "Subject location", NULL },
348 { 0xa215, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.ExposureIndex",     N_("ISO sensitivity"), NULL },
349 { 0xa217, EXIF_FORMAT_SHORT_UNSIGNED, -1,       "Exif.Photo.SensingMethod",     "Sensor type", ExifSensorList },
350 { 0xa300, EXIF_FORMAT_UNDEFINED, 1,             "Exif.Photo.FileSource",                "Source type", ExifSourceList },
351 { 0xa301, EXIF_FORMAT_UNDEFINED, 1,             "Exif.Photo.SceneType",         "Scene type", ExifSceneList },
352 { 0xa302, EXIF_FORMAT_UNDEFINED, -1,            "Exif.Image.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,        "Exif.Photo.CustomRendered",    "Render process", ExifCustRenderList },
355 { 0xa402, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.ExposureMode",              "Exposure mode", ExifExposureModeList },
356 { 0xa403, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.WhiteBalance",              "White balance", ExifWhiteBalanceList },
357 { 0xa404, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Photo.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,        "Exif.Photo.GainControl",               "Gain control", ExifGainControlList },
361 { 0xa408, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.Contrast",          "Contrast", ExifContrastList },
362 { 0xa409, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.Saturation",                "Saturation", ExifSaturationList },
363 { 0xa40a, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.Sharpness",         "Sharpness", ExifSharpnessList },
364 { 0xa40b, EXIF_FORMAT_UNDEFINED, -1,            "Exif.Photo.DeviceSettingDescription","Device setting", NULL },
365 { 0xa40c, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "Exif.Photo.SubjectDistanceRange",      "Subject range", ExifSubjectRangeList },
366 { 0xa420, EXIF_FORMAT_STRING, -1,               "Exif.Photo.ImageUniqueID",     "Image serial number", NULL },
367         /* place known, but undocumented or lesser used tags here */
368 { 0x00fe, EXIF_FORMAT_LONG_UNSIGNED, 1,         "Exif.Image.NewSubfileType",    NULL, NULL },
369 { 0x00ff, EXIF_FORMAT_SHORT_UNSIGNED, 1,        "SubfileType",          NULL, NULL },
370 { 0x012d, EXIF_FORMAT_SHORT_UNSIGNED, 3,        "Exif.Image.TransferFunction",  NULL, NULL },
371 { 0x013b, EXIF_FORMAT_STRING, -1,               "Exif.Image.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,        "Exif.Image.SubIFDs",           NULL, NULL },
378 { 0x015b, EXIF_FORMAT_UNDEFINED, -1,            "JPEGTables",           NULL, NULL },
379 { 0x828d, EXIF_FORMAT_SHORT_UNSIGNED, 2,        "Exif.Image.CFARepeatPatternDim",       NULL, NULL },
380 { 0x828e, EXIF_FORMAT_BYTE_UNSIGNED, -1,        "Exif.Image.CFAPattern",                NULL, NULL },
381 { 0x828f, EXIF_FORMAT_RATIONAL_UNSIGNED, 1,     "Exif.Image.BatteryLevel",              NULL, NULL },
382 { 0x83bb, EXIF_FORMAT_LONG_UNSIGNED, -1,        "IPTC/NAA",             NULL, NULL },
383 { 0x8773, EXIF_FORMAT_UNDEFINED, -1,            "ColorProfile",         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,     "Exif.Photo.FlashEnergy",               NULL, NULL },
389 { 0x920c, EXIF_FORMAT_UNDEFINED, -1,            "Exif.Photo.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,     "Exif.Photo.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 static const ExifMarker *exif_marker_from_tag(guint16 tag, const ExifMarker *list);
417
418 /*
419  *-----------------------------------------------------------------------------
420  * ExifItem
421  *-----------------------------------------------------------------------------
422  */
423
424 ExifItem *exif_item_new(ExifFormatType format, guint tag,
425                         guint elements, const ExifMarker *marker)
426 {
427         ExifItem *item;
428
429         item = g_new0(ExifItem, 1);
430         item->format = format;
431         item->tag = tag;
432         item->marker = marker;
433         item->elements = elements;
434         item->data = NULL;
435         item->data_len = 0;
436
437         switch (format)
438                 {
439                 case EXIF_FORMAT_UNKNOWN:
440                         /* unknown, data is NULL */
441                         return item;
442                         break;
443                 case EXIF_FORMAT_BYTE_UNSIGNED:
444                         item->data_len = sizeof(char) * elements;
445                         break;
446                 case EXIF_FORMAT_STRING:
447                         item->data_len = sizeof(char) * elements;
448                         break;
449                 case EXIF_FORMAT_SHORT_UNSIGNED:
450                         item->data_len = sizeof(guint16) * elements;
451                         break;
452                 case EXIF_FORMAT_LONG_UNSIGNED:
453                         item->data_len = sizeof(guint32) * elements;
454                         break;
455                 case EXIF_FORMAT_RATIONAL_UNSIGNED:
456                         item->data_len = sizeof(ExifRational) * elements;
457                         break;
458                 case EXIF_FORMAT_BYTE:
459                         item->data_len = sizeof(char) * elements;
460                         break;
461                 case EXIF_FORMAT_UNDEFINED:
462                         item->data_len = sizeof(char) * elements;
463                         break;
464                 case EXIF_FORMAT_SHORT:
465                         item->data_len = sizeof(gint16) * elements;
466                         break;
467                 case EXIF_FORMAT_LONG:
468                         item->data_len = sizeof(gint32) * elements;
469                         break;
470                 case EXIF_FORMAT_RATIONAL:
471                         item->data_len = sizeof(ExifRational) * elements;
472                         break;
473                 case EXIF_FORMAT_FLOAT:
474                         item->data_len = sizeof(float) * elements;
475                         break;
476                 case EXIF_FORMAT_DOUBLE:
477                         item->data_len = sizeof(double) * elements;
478                         break;
479                 }
480
481         item->data = g_malloc0(item->data_len);
482
483         return item;
484 }
485
486 static void exif_item_free(ExifItem *item)
487 {
488         if (!item) return;
489
490         g_free(item->data);
491         g_free(item);
492 }
493
494 const char *exif_item_get_tag_name(ExifItem *item)
495 {
496         if (!item || !item->marker) return NULL;
497         return item->marker->key;
498 }
499
500 guint exif_item_get_tag_id(ExifItem *item)
501 {
502         return item->tag;
503 }
504
505 guint exif_item_get_elements(ExifItem *item)
506 {
507         return item->elements;
508 }
509
510 char *exif_item_get_data(ExifItem *item, guint *data_len)
511 {
512         if (data_len)
513                 *data_len = item->data_len;
514         return item->data;
515 }
516
517 guint exif_item_get_format_id(ExifItem *item)
518 {
519         return item->format;
520 }
521
522
523 char *exif_item_get_description(ExifItem *item)
524 {
525         if (!item || !item->marker) return NULL;
526         return g_strdup(_(item->marker->description));
527 }
528
529 const char *exif_item_get_format_name(ExifItem *item, gint brief)
530 {
531         if (!item || !item->marker) return NULL; 
532         return (brief) ? ExifFormatList[item->format].short_name : ExifFormatList[item->format].description;
533 }
534
535 static GString *string_append_raw_bytes(GString *string, gpointer data, gint ne)
536 {
537         gint i;
538
539         for (i = 0 ; i < ne; i++)
540                 {
541                 unsigned char c = ((char *)data)[i];
542                 if (c < 32 || c > 127) c = '.';
543                 g_string_append_printf(string, "%c", c);
544                 }
545         string = g_string_append(string, " : ");
546         for (i = 0 ; i < ne; i++)
547                 {
548                 const gchar *spacer;
549                 if (i > 0)
550                         {
551                         if (i%8 == 0)
552                                 {
553                                 spacer = " - ";
554                                 }
555                         else
556                                 {
557                                 spacer = " ";
558                                 }
559                         }
560                 else
561                         {
562                         spacer = "";
563                         }
564                 g_string_append_printf(string, "%s%02x", spacer, ((char *)data)[i]);
565                 }
566
567         return string;
568 }
569
570
571 gchar *exif_text_list_find_value(ExifTextList *list, guint value)
572 {
573         gchar *result = NULL;
574         gint i;
575
576         i = 0;
577         while (!result && list[i].value >= 0)
578                 {
579                 if (value == list[i].value) result = g_strdup(_(list[i].description));
580                 i++;
581                 }
582         if (!result) result = g_strdup_printf("%d (%s)", value, _("unknown"));
583
584         return result;
585 }
586
587
588 /*
589  *-------------------------------------------------------------------
590  * byte order utils
591  *-------------------------------------------------------------------
592  */
593
594 /* note: the align_buf is used to avoid alignment issues (on sparc) */
595
596 guint16 exif_byte_get_int16(unsigned char *f, ExifByteOrder bo)
597 {
598         guint16 align_buf;
599
600         memcpy(&align_buf, f, sizeof(guint16));
601
602         if (bo == EXIF_BYTE_ORDER_INTEL)
603                 return GUINT16_FROM_LE(align_buf);
604         else
605                 return GUINT16_FROM_BE(align_buf);
606 }
607
608 guint32 exif_byte_get_int32(unsigned char *f, ExifByteOrder bo)
609 {
610         guint32 align_buf;
611
612         memcpy(&align_buf, f, sizeof(guint32));
613
614         if (bo == EXIF_BYTE_ORDER_INTEL)
615                 return GUINT32_FROM_LE(align_buf);
616         else
617                 return GUINT32_FROM_BE(align_buf);
618 }
619
620 void exif_byte_put_int16(unsigned char *f, guint16 n, ExifByteOrder bo)
621 {
622         guint16 align_buf;
623
624         if (bo == EXIF_BYTE_ORDER_INTEL)
625                 {
626                 align_buf = GUINT16_TO_LE(n);
627                 }
628         else
629                 {
630                 align_buf = GUINT16_TO_BE(n);
631                 }
632
633         memcpy(f, &align_buf, sizeof(guint16));
634 }
635
636 void exif_byte_put_int32(unsigned char *f, guint32 n, ExifByteOrder bo)
637 {
638         guint32 align_buf;
639
640         if (bo == EXIF_BYTE_ORDER_INTEL)
641                 {
642                 align_buf = GUINT32_TO_LE(n);
643                 }
644         else
645                 {
646                 align_buf = GUINT32_TO_BE(n);
647                 }
648
649         memcpy(f, &align_buf, sizeof(guint32));
650 }
651
652
653 /*
654  *-------------------------------------------------------------------
655  * IFD utils
656  *-------------------------------------------------------------------
657  */
658
659 static const ExifMarker *exif_marker_from_tag(guint16 tag, const ExifMarker *list)
660 {
661         gint i = 0;
662
663         if (!list) return NULL;
664
665         while (list[i].tag != 0 && list[i].tag != tag)
666                 {
667                 i++;
668                 }
669
670         return (list[i].tag == 0 ? NULL : &list[i]);
671 }
672
673 static void rational_from_data(ExifRational *r, void *src, ExifByteOrder bo)
674 {
675         r->num = exif_byte_get_int32(src, bo);
676         r->den = exif_byte_get_int32(src + sizeof(guint32), bo);
677 }
678
679 /* src_format and item->format must be compatible
680  * and not overrun src or item->data.
681  */
682 void exif_item_copy_data(ExifItem *item, void *src, guint len,
683                          ExifFormatType src_format, ExifByteOrder bo)
684 {
685         gint bs;
686         gint ne;
687         gpointer dest;
688         gint i;
689
690         bs = ExifFormatList[item->format].size;
691         ne = item->elements;
692         dest = item->data;
693
694         if (!dest ||
695             ExifFormatList[src_format].size * ne > len)
696                 {
697                 printf("exif tag %s data size mismatch\n", exif_item_get_tag_name(item));
698                 return;
699                 }
700
701         switch (item->format)
702                 {
703                 case EXIF_FORMAT_UNKNOWN:
704                         break;
705                 case EXIF_FORMAT_BYTE_UNSIGNED:
706                 case EXIF_FORMAT_BYTE:
707                 case EXIF_FORMAT_UNDEFINED:
708                         memcpy(dest, src, len);
709                         break;
710                 case EXIF_FORMAT_STRING:
711                         memcpy(dest, src, len);
712                         /* string is NULL terminated, make sure this is true */
713                         if (((char *)dest)[len - 1] != '\0') ((char *)dest)[len - 1] = '\0';
714                         break;
715                 case EXIF_FORMAT_SHORT_UNSIGNED:
716                 case EXIF_FORMAT_SHORT:
717                         for (i = 0; i < ne; i++)
718                                 {
719                                 ((guint16 *)dest)[i] = exif_byte_get_int16(src + i * bs, bo);
720                                 }
721                         break;
722                 case EXIF_FORMAT_LONG_UNSIGNED:
723                 case EXIF_FORMAT_LONG:
724                         if (src_format == EXIF_FORMAT_SHORT_UNSIGNED ||
725                             src_format == EXIF_FORMAT_SHORT)
726                                 {
727                                 /* a short fits into a long, so allow it */
728                                 gint ss;
729
730                                 ss = ExifFormatList[src_format].size;
731                                 for (i = 0; i < ne; i++)
732                                         {
733                                         ((gint32 *)dest)[i] =
734                                                 (gint32)exif_byte_get_int16(src + i * ss, bo);
735                                         }
736                                 }
737                         else
738                                 {
739                                 for (i = 0; i < ne; i++)
740                                         {
741                                         ((gint32 *)dest)[i] =
742                                                 exif_byte_get_int32(src + i * bs, bo);
743                                         }
744                                 }
745                         break;
746                 case EXIF_FORMAT_RATIONAL_UNSIGNED:
747                 case EXIF_FORMAT_RATIONAL:
748                         for (i = 0; i < ne; i++)
749                                 {
750                                 rational_from_data(&((ExifRational *)dest)[i], src + i * bs, bo);
751                                 }
752                         break;
753                 case EXIF_FORMAT_FLOAT:
754                         for (i = 0; i < ne; i++)
755                                 {
756                                 ((float *)dest)[i] = exif_byte_get_int32(src + i * bs, bo);
757                                 }
758                         break;
759                 case EXIF_FORMAT_DOUBLE:
760                         for (i = 0; i < ne; i++)
761                                 {
762                                 ExifRational r;
763
764                                 rational_from_data(&r, src + i * bs, bo);
765                                 if (r.den) ((double *)dest)[i] = (double)r.num / r.den;
766                                 }
767                         break;
768                 }
769 }
770
771 static gint exif_parse_IFD_entry(ExifData *exif, unsigned char *tiff, guint offset,
772                                  guint size, ExifByteOrder bo,
773                                  gint level,
774                                  const ExifMarker *list)
775 {
776         guint tag;
777         guint format;
778         guint count;
779         guint data_val;
780         guint data_offset;
781         guint data_length;
782         const ExifMarker *marker;
783         ExifItem *item;
784
785         tag = exif_byte_get_int16(tiff + offset + EXIF_TIFD_OFFSET_TAG, bo);
786         format = exif_byte_get_int16(tiff + offset + EXIF_TIFD_OFFSET_FORMAT, bo);
787         count = exif_byte_get_int32(tiff + offset + EXIF_TIFD_OFFSET_COUNT, bo);
788         data_val = exif_byte_get_int32(tiff + offset + EXIF_TIFD_OFFSET_DATA, bo);
789
790         /* Check tag type. If it does not match, either the format is wrong,
791          * either it is a unknown tag; so it is not really an error.
792          */
793         marker = exif_marker_from_tag(tag, list);
794         if (!marker)
795                 {
796                 if (format >= EXIF_FORMAT_COUNT)
797                         {
798                         printf("warning: exif tag 0x%4x has invalid format %d\n", tag, format);
799                         return 0;
800                         }
801                 /* allow non recognized tags to be displayed */
802                 marker = &ExifUnknownMarkersList[format];
803                 }
804         if (marker->format != format)
805                 {
806                 /* Some cameras got mixed up signed/unsigned_rational
807                  * eg KODAK DC4800 on object_distance tag
808                  *
809                  * FIXME: what exactly is this test trying to do?
810                  * ok, so this test is to allow the case of swapped signed/unsigned mismatch to leak through?
811                  */
812                 if (!(marker->format == EXIF_FORMAT_RATIONAL_UNSIGNED && format == EXIF_FORMAT_RATIONAL) &&
813                     !(marker->format == EXIF_FORMAT_RATIONAL && format == EXIF_FORMAT_RATIONAL_UNSIGNED) &&
814                         /* short fits into a long so allow this mismatch
815                          * as well (some tags allowed to be unsigned short _or_ unsigned long)
816                          */
817                     !(marker->format == EXIF_FORMAT_LONG_UNSIGNED && format == EXIF_FORMAT_SHORT_UNSIGNED) )
818                         {
819                         if (format < EXIF_FORMAT_COUNT)
820                                 {
821                                 printf("warning: exif tag %s format mismatch, found %s exif spec requests %s\n",
822                                         marker->key, ExifFormatList[format].short_name,
823                                         ExifFormatList[marker->format].short_name);
824                                 }
825                         else
826                                 {
827                                 printf("warning: exif tag %s format mismatch, found unknown id %d exif spec requests %d (%s)\n",
828                                         marker->key, format, marker->format,
829                                         ExifFormatList[marker->format].short_name);
830                                 }
831                         return 0;
832                         }
833                 }
834
835         /* Where is the data, is it available?
836          */
837         if (marker->components > 0 && marker->components != count)
838                 {
839                 printf("warning: exif tag %s has %d elements, exif spec requests %d\n",
840                         marker->key, count, marker->components);
841                 }
842
843         data_length = ExifFormatList[marker->format].size * count;
844         if (data_length > 4)
845                 {
846                 data_offset = data_val;
847                 if (size < data_offset + data_length)
848                         {
849                         printf("warning: exif tag %s data will overrun end of file, ignored.\n", marker->key);
850                         return -1;
851                         }
852                 }
853         else
854                 {
855                 data_offset = offset + EXIF_TIFD_OFFSET_DATA;
856                 }
857
858         item = exif_item_new(marker->format, tag, count, marker);
859         exif_item_copy_data(item, tiff + data_offset, data_length, format, bo);
860         exif->items = g_list_prepend(exif->items, item);
861
862         if (list == ExifKnownMarkersList)
863                 {
864                 switch (item->tag)
865                         {
866                         case TAG_EXIFOFFSET:
867                                 exif_parse_IFD_table(exif, tiff, data_val, size, bo, level + 1, list);
868                                 break;
869                         case TAG_EXIFMAKERNOTE:
870                                 format_exif_makernote_parse(exif, tiff, data_val, size, bo);
871                                 break;
872                         }
873                 }
874
875         return 0;
876 }
877
878 gint exif_parse_IFD_table(ExifData *exif,
879                           unsigned char *tiff, guint offset,
880                           guint size, ExifByteOrder bo,
881                           gint level,
882                           const ExifMarker *list)
883 {
884         guint count;
885         guint i;
886
887         /* limit damage from infinite loops */
888         if (level > EXIF_TIFF_MAX_LEVELS) return -1;
889
890         /* We should be able to read number of entries in IFD0) */
891         if (size < offset + 2) return -1;
892
893         count = exif_byte_get_int16(tiff + offset, bo);
894         offset += 2;
895
896         /* Entries and next IFD offset must be readable */
897         if (size < offset + count * EXIF_TIFD_SIZE + 4) return -1;
898
899         for (i = 0; i < count; i++)
900                 {
901                 exif_parse_IFD_entry(exif, tiff, offset + i * EXIF_TIFD_SIZE, size, bo, level, list);
902                 }
903
904         return 0;
905 }
906
907 /*
908  *-------------------------------------------------------------------
909  * file formats
910  *-------------------------------------------------------------------
911  */
912
913 gint exif_tiff_directory_offset(unsigned char *data, const guint len,
914                                 guint *offset, ExifByteOrder *bo)
915 {
916         if (len < 8) return FALSE;
917
918         if (memcmp(data, "II", 2) == 0)
919                 {
920                 *bo = EXIF_BYTE_ORDER_INTEL;
921                 }
922         else if (memcmp(data, "MM", 2) == 0)
923                 {
924                 *bo = EXIF_BYTE_ORDER_MOTOROLA;
925                 }
926         else
927                 {
928                 return FALSE;
929                 }
930
931         if (exif_byte_get_int16(data + 2, *bo) != 0x002A)
932                 {
933                 return FALSE;
934                 }
935
936         *offset = exif_byte_get_int32(data + 4, *bo);
937
938         return (*offset < len);
939 }
940
941 gint exif_tiff_parse(ExifData *exif, unsigned char *tiff, guint size, ExifMarker *list)
942 {
943         ExifByteOrder bo;
944         guint offset;
945
946         if (!exif_tiff_directory_offset(tiff, size, &offset, &bo)) return -1;
947
948         return exif_parse_IFD_table(exif, tiff, offset, size, bo, 0, list);
949 }
950
951 /*
952  *-------------------------------------------------------------------
953  * jpeg marker utils
954  *-------------------------------------------------------------------
955  */
956
957 #define JPEG_MARKER             0xFF
958 #define JPEG_MARKER_SOI         0xD8
959 #define JPEG_MARKER_EOI         0xD9
960 #define JPEG_MARKER_APP1        0xE1
961 #define JPEG_MARKER_APP2        0xE2
962
963 /* jpeg container format:
964      all data markers start with 0XFF
965      2 byte long file start and end markers: 0xFFD8(SOI) and 0XFFD9(EOI)
966      4 byte long data segment markers in format: 0xFFTTSSSSNNN...
967        FF:   1 byte standard marker identifier
968        TT:   1 byte data type
969        SSSS: 2 bytes in Motorola byte alignment for length of the data.
970              This value includes these 2 bytes in the count, making actual
971              length of NN... == SSSS - 2.
972        NNN.: the data in this segment
973  */
974
975 static gint exif_jpeg_segment_find(unsigned char *data, guint size,
976                                    guchar app_marker, const gchar *magic, guint magic_len,
977                                    guint *seg_offset, guint *seg_length)
978 {
979         guchar marker = 0;
980         guint offset = 0;
981         guint length = 0;
982
983         while (marker != app_marker &&
984                marker != JPEG_MARKER_EOI)
985                 {
986                 offset += length;
987                 length = 2;
988
989                 if (offset + 2 >= size ||
990                     data[offset] != JPEG_MARKER) return FALSE;
991
992                 marker = data[offset + 1];
993                 if (marker != JPEG_MARKER_SOI &&
994                     marker != JPEG_MARKER_EOI)
995                         {
996                         if (offset + 4 >= size) return FALSE;
997                         length += exif_byte_get_int16(data + offset + 2, EXIF_BYTE_ORDER_MOTOROLA);
998                         }
999                 }
1000
1001         if (marker == app_marker &&
1002             offset + length < size &&
1003             length >= 4 + magic_len &&
1004             memcmp(data + offset + 4, magic, magic_len) == 0)
1005                 {
1006                 *seg_offset = offset + 4;
1007                 *seg_length = length - 4;
1008                 return TRUE;
1009                 }
1010
1011         return FALSE;
1012 }
1013
1014 static ExifMarker jpeg_color_marker = { 0x8773, EXIF_FORMAT_UNDEFINED, -1, "ColorProfile", NULL, NULL };
1015
1016 static gint exif_jpeg_parse_color(ExifData *exif, unsigned char *data, guint size)
1017 {
1018         guint seg_offset = 0;
1019         guint seg_length = 0;
1020         guint chunk_offset[255];
1021         guint chunk_length[255];
1022         guint chunk_count = 0;
1023
1024         /* For jpeg/jfif, ICC color profile data can be in more than one segment.
1025            the data is in APP2 data segments that start with "ICC_PROFILE\x00\xNN\xTT"
1026            NN = segment number for data
1027            TT = total number of ICC segments (TT in each ICC segment should match)
1028          */
1029
1030         while (exif_jpeg_segment_find(data + seg_offset + seg_length,
1031                                       size - seg_offset - seg_length,
1032                                       JPEG_MARKER_APP2,
1033                                       "ICC_PROFILE\x00", 12,
1034                                       &seg_offset, &seg_length))
1035                 {
1036                 guchar chunk_num;
1037                 guchar chunk_tot;
1038
1039                 if (seg_length < 14) return FALSE;
1040
1041                 chunk_num = data[seg_offset + 12];
1042                 chunk_tot = data[seg_offset + 13];
1043
1044                 if (chunk_num == 0 || chunk_tot == 0) return FALSE;
1045
1046                 if (chunk_count == 0)
1047                         {
1048                         guint i;
1049
1050                         chunk_count = (guint)chunk_tot;
1051                         for (i = 0; i < chunk_count; i++) chunk_offset[i] = 0;
1052                         for (i = 0; i < chunk_count; i++) chunk_length[i] = 0;
1053                         }
1054
1055                 if (chunk_tot != chunk_count ||
1056                     chunk_num > chunk_count) return FALSE;
1057
1058                 chunk_num--;
1059                 chunk_offset[chunk_num] = seg_offset + 14;
1060                 chunk_length[chunk_num] = seg_length - 14;
1061                 }
1062
1063         if (chunk_count > 0)
1064                 {
1065                 ExifItem *item;
1066                 unsigned char *cp_data;
1067                 guint cp_length = 0;
1068                 guint i;
1069
1070                 for (i = 0; i < chunk_count; i++) cp_length += chunk_length[i];
1071                 cp_data = g_malloc(cp_length);
1072
1073                 for (i = 0; i < chunk_count; i++)
1074                         {
1075                         if (chunk_offset[i] == 0)
1076                                 {
1077                                 /* error, we never saw this chunk */
1078                                 g_free(cp_data);
1079                                 return FALSE;
1080                                 }
1081                         memcpy(cp_data, data + chunk_offset[i], chunk_length[i]);
1082                         }
1083
1084                 item = exif_item_new(jpeg_color_marker.format, jpeg_color_marker.tag, 1,
1085                                      &jpeg_color_marker);
1086                 g_free(item->data);
1087                 item->data = cp_data;
1088                 item->elements = cp_length;
1089                 item->data_len = cp_length;
1090                 exif->items = g_list_prepend(exif->items, item);
1091
1092                 return TRUE;
1093                 }
1094
1095         return FALSE;
1096 }
1097
1098 static gint exif_jpeg_parse(ExifData *exif,
1099                             unsigned char *data, guint size,
1100                             ExifMarker *list, gint parse_color)
1101 {
1102         guint seg_offset = 0;
1103         guint seg_length = 0;
1104         gint res = -1;
1105
1106         if (size < 4 ||
1107             memcmp(data, "\xFF\xD8", 2) != 0)
1108                 {
1109                 return -2;
1110                 }
1111
1112         if (exif_jpeg_segment_find(data, size, JPEG_MARKER_APP1,
1113                                    "Exif\x00\x00", 6,
1114                                    &seg_offset, &seg_length))
1115                 {
1116                 res = exif_tiff_parse(exif, data + seg_offset + 6, seg_length - 6, list);
1117                 }
1118
1119         if (parse_color &&
1120             exif_jpeg_parse_color(exif, data, size))
1121                 {
1122                 res = 0;
1123                 }
1124
1125         return res;
1126 }
1127
1128
1129 /*
1130  *-------------------------------------------------------------------
1131  * misc
1132  *-------------------------------------------------------------------
1133  */
1134
1135
1136 ExifItem *exif_get_first_item(ExifData *exif)
1137 {
1138         if (exif->items) 
1139                 {
1140                 ExifItem *ret = (ExifItem *)exif->items->data;
1141                 exif->current = exif->items->next;
1142                 return ret;
1143                 }
1144         exif->current = NULL;
1145         return NULL;
1146 }
1147
1148 ExifItem *exif_get_next_item(ExifData *exif)
1149 {
1150         if (exif->current) 
1151                 {
1152                 ExifItem *ret = (ExifItem *)exif->current->data;
1153                 exif->current = exif->current->next;
1154                 return ret;
1155                 }
1156         return NULL;
1157 }
1158
1159
1160
1161 static gint map_file(const gchar *path, void **mapping, int *size)
1162 {
1163         int fd;
1164         struct stat fs;
1165
1166         if ((fd = open(path, O_RDONLY)) == -1)
1167                 {
1168                 perror(path);
1169                 return -1;
1170                 }
1171
1172         if (fstat(fd, &fs) == -1)
1173                 {
1174                 perror(path);
1175                 close(fd);
1176                 return -1;
1177                 }
1178
1179         *size = fs.st_size;
1180
1181         if ((*mapping = mmap(0, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
1182                 {
1183                 perror(path);
1184                 close(fd);
1185                 return -1;
1186                 }
1187
1188         close(fd);
1189         return 0;
1190 }
1191
1192 static gint unmap_file(void *mapping, int size)
1193 {
1194         if (munmap(mapping, size) == -1)
1195                 {
1196                 perror("munmap");
1197                 return -1;
1198                 }
1199
1200         return 0;
1201 }
1202
1203 void exif_free(ExifData *exif)
1204 {
1205         GList *work;
1206
1207         if (!exif) return;
1208
1209         work = exif->items;
1210         while (work)
1211                 {
1212                 ExifItem *item = work->data;
1213                 work = work->next;
1214                 exif_item_free(item);
1215                 }
1216
1217         g_list_free(exif->items);
1218         g_free(exif);
1219 }
1220
1221 ExifData *exif_read(gchar *path, gint parse_color_profile)
1222 {
1223         ExifData *exif;
1224         void *f;
1225         int size, res;
1226         gchar *pathl;
1227
1228         if (!path) return NULL;
1229
1230         pathl = path_from_utf8(path);
1231         if (map_file(pathl, &f, &size) == -1)
1232                 {
1233                 g_free(pathl);
1234                 return NULL;
1235                 }
1236         g_free(pathl);
1237
1238         exif = g_new0(ExifData, 1);
1239         exif->items = NULL;
1240         exif->current = NULL;
1241
1242         if ((res = exif_jpeg_parse(exif, (unsigned char *)f, size,
1243                                    ExifKnownMarkersList,
1244                                    parse_color_profile)) == -2)
1245                 {
1246                 res = exif_tiff_parse(exif, (unsigned char *)f, size, ExifKnownMarkersList);
1247                 }
1248
1249         if (res != 0)
1250                 {
1251                 FormatRawExifType exif_type;
1252                 FormatRawExifParseFunc exif_parse_func;
1253                 guint32 offset = 0;
1254
1255                 exif_type = format_raw_exif_offset(f, size, &offset, &exif_parse_func);
1256                 switch (exif_type)
1257                         {
1258                         case FORMAT_RAW_EXIF_NONE:
1259                         default:
1260                                 break;
1261                         case FORMAT_RAW_EXIF_TIFF:
1262                                 res = exif_tiff_parse(exif, (unsigned char*)f + offset, size - offset,
1263                                                       ExifKnownMarkersList);
1264                                 break;
1265                         case FORMAT_RAW_EXIF_JPEG:
1266                                 res = exif_jpeg_parse(exif, (unsigned char*)f + offset, size - offset,
1267                                                       ExifKnownMarkersList, FALSE);
1268                                 break;
1269                         case FORMAT_RAW_EXIF_IFD_II:
1270                         case FORMAT_RAW_EXIF_IFD_MM:
1271                                 res = exif_parse_IFD_table(exif, (unsigned char*)f, offset, size - offset,
1272                                                            (exif_type == FORMAT_RAW_EXIF_IFD_II) ?
1273                                                                 EXIF_BYTE_ORDER_INTEL : EXIF_BYTE_ORDER_MOTOROLA,
1274                                                            0, ExifKnownMarkersList);
1275                                 break;
1276                         case FORMAT_RAW_EXIF_PROPRIETARY:
1277                                 if (exif_parse_func)
1278                                         {
1279                                         res = exif_parse_func((unsigned char*)f + offset, size - offset, exif);
1280                                         }
1281                                 break;
1282                         }
1283                 }
1284
1285         if (res != 0)
1286                 {
1287                 exif_free(exif);
1288                 exif = NULL;
1289                 }
1290
1291         unmap_file(f, size);
1292
1293         if (exif) exif->items = g_list_reverse(exif->items);
1294
1295 #if 0
1296         exif_write_data_list(exif, stdout, TRUE);
1297         exif_write_data_list(exif, stdout, FALSE);
1298 #endif
1299
1300         return exif;
1301 }
1302
1303 ExifItem *exif_get_item(ExifData *exif, const gchar *key)
1304 {
1305         GList *work;
1306
1307         if (!key) return NULL;
1308
1309         work = exif->items;
1310         while (work)
1311                 {
1312                 ExifItem *item;
1313
1314                 item = work->data;
1315                 work = work->next;
1316                 if (item->marker->key && strcmp(key, item->marker->key) == 0) return item;
1317                 }
1318         return NULL;
1319 }
1320
1321 #define EXIF_DATA_AS_TEXT_MAX_COUNT 16
1322
1323 gchar *exif_item_get_data_as_text(ExifItem *item)
1324 {
1325         const ExifMarker *marker;
1326         gpointer data;
1327         GString *string;
1328         gchar *text;
1329         gint ne;
1330         gint i;
1331
1332         if (!item) return NULL;
1333
1334         marker = item->marker;
1335         if (!marker) return NULL;
1336
1337         data = item->data;
1338         ne = item->elements;
1339         if (ne > EXIF_DATA_AS_TEXT_MAX_COUNT) ne = EXIF_DATA_AS_TEXT_MAX_COUNT;
1340         string = g_string_new("");
1341         switch (item->format)
1342                 {
1343                 case EXIF_FORMAT_UNKNOWN:
1344                         break;
1345                 case EXIF_FORMAT_BYTE_UNSIGNED:
1346                 case EXIF_FORMAT_BYTE:
1347                 case EXIF_FORMAT_UNDEFINED:
1348                         if (ne == 1 && marker->list)
1349                                 {
1350                                 gchar *result;
1351                                 unsigned char val;
1352
1353                                 if (item->format == EXIF_FORMAT_BYTE_UNSIGNED ||
1354                                     item->format == EXIF_FORMAT_UNDEFINED)
1355                                         {
1356                                         val = ((unsigned char *)data)[0];
1357                                         }
1358                                 else
1359                                         {
1360                                         val = (unsigned char)(((signed char *)data)[0]);
1361                                         }
1362
1363                                 result = exif_text_list_find_value(marker->list, (guint)val);
1364                                 string = g_string_append(string, result);
1365                                 g_free(result);
1366                                 }
1367                         else
1368                                 {
1369                                 string = string_append_raw_bytes(string, data, ne);
1370                                 }
1371                         break;
1372                 case EXIF_FORMAT_STRING:
1373                         string = g_string_append(string, (gchar *)(item->data));
1374                         break;
1375                 case EXIF_FORMAT_SHORT_UNSIGNED:
1376                         if (ne == 1 && marker->list)
1377                                 {
1378                                 gchar *result;
1379
1380                                 result = exif_text_list_find_value(marker->list, ((guint16 *)data)[0]);
1381                                 string = g_string_append(string, result);
1382                                 g_free(result);
1383                                 }
1384                         else for (i = 0; i < ne; i++)
1385                                 {
1386                                 g_string_append_printf(string, "%s%hd", (i > 0) ? ", " : "",
1387                                                         ((guint16 *)data)[i]);
1388                                 }
1389                         break;
1390                 case EXIF_FORMAT_LONG_UNSIGNED:
1391                         for (i = 0; i < ne; i++)
1392                                 {
1393                                 g_string_append_printf(string, "%s%ld", (i > 0) ? ", " : "",
1394                                                         (unsigned long int)((guint32 *)data)[i]);
1395                                 }
1396                         break;
1397                 case EXIF_FORMAT_RATIONAL_UNSIGNED:
1398                         for (i = 0; i < ne; i++)
1399                                 {
1400                                 ExifRational *r;
1401
1402                                 r = &((ExifRational *)data)[i];
1403                                 g_string_append_printf(string, "%s%ld/%ld", (i > 0) ? ", " : "",
1404                                                         (unsigned long)r->num, (unsigned long)r->den);
1405                                 }
1406                         break;
1407                 case EXIF_FORMAT_SHORT:
1408                         for (i = 0; i < ne; i++)
1409                                 {
1410                                 g_string_append_printf(string, "%s%hd", (i > 0) ? ", " : "",
1411                                                         ((gint16 *)data)[i]);
1412                                 }
1413                         break;
1414                 case EXIF_FORMAT_LONG:
1415                         for (i = 0; i < ne; i++)
1416                                 {
1417                                 g_string_append_printf(string, "%s%ld", (i > 0) ? ", " : "",
1418                                                         (long int)((gint32 *)data)[i]);
1419                                 }
1420                         break;
1421                 case EXIF_FORMAT_RATIONAL:
1422                         for (i = 0; i < ne; i++)
1423                                 {
1424                                 ExifRational *r;
1425
1426                                 r = &((ExifRational *)data)[i];
1427                                 g_string_append_printf(string, "%s%ld/%ld", (i > 0) ? ", " : "",
1428                                                         (long)r->num, (long)r->den);
1429                                 }
1430                         break;
1431                 case EXIF_FORMAT_FLOAT:
1432                         for (i = 0; i < ne; i++)
1433                                 {
1434                                 g_string_append_printf(string, "%s%f", (i > 0) ? ", " : "",
1435                                                         ((float *)data)[i]);
1436                                 }
1437                         break;
1438                 case EXIF_FORMAT_DOUBLE:
1439                         for (i = 0; i < ne; i++)
1440                                 {
1441                                 g_string_append_printf(string, "%s%f", (i > 0) ? ", " : "",
1442                                                         ((double *)data)[i]);
1443                                 }
1444                         break;
1445                 }
1446
1447         if (item->elements > EXIF_DATA_AS_TEXT_MAX_COUNT &&
1448             item->format != EXIF_FORMAT_STRING)
1449                 {
1450                 g_string_append(string, " ...");
1451                 }
1452
1453         text = string->str;
1454         g_string_free(string, FALSE);
1455
1456         return text;
1457 }
1458
1459 gint exif_item_get_integer(ExifItem *item, gint *value)
1460 {
1461         if (!item) return FALSE;
1462
1463         switch (item->format)
1464                 {
1465                 case EXIF_FORMAT_SHORT:
1466                         *value = (gint)(((gint16 *)(item->data))[0]);
1467                         return TRUE;
1468                         break;
1469                 case EXIF_FORMAT_SHORT_UNSIGNED:
1470                         *value = (gint)(((guint16 *)(item->data))[0]);
1471                         return TRUE;
1472                         break;
1473                 case EXIF_FORMAT_LONG:
1474                         *value = (gint)(((gint32 *)(item->data))[0]);
1475                         return TRUE;
1476                         break;
1477                 case EXIF_FORMAT_LONG_UNSIGNED:
1478                         /* FIXME: overflow possible */
1479                         *value = (gint)(((guint32 *)(item->data))[0]);
1480                         return TRUE;
1481                 default:
1482                         /* all other type return FALSE */
1483                         break;
1484                 }
1485         return FALSE;
1486 }
1487
1488 gint exif_get_integer(ExifData *exif, const gchar *key, gint *value)
1489 {
1490         ExifItem *item;
1491
1492         item = exif_get_item(exif, key);
1493         return exif_item_get_integer(item, value);
1494 }
1495
1496 ExifRational *exif_item_get_rational(ExifItem *item, gint *sign)
1497 {
1498         if (!item) return NULL;
1499
1500         if (item->format == EXIF_FORMAT_RATIONAL ||
1501             item->format == EXIF_FORMAT_RATIONAL_UNSIGNED)
1502                 {
1503                 if (sign) *sign = (item->format == EXIF_FORMAT_RATIONAL);
1504                 return &((ExifRational *)(item->data))[0];
1505                 }
1506
1507         return NULL;
1508 }
1509
1510 ExifRational *exif_get_rational(ExifData *exif, const gchar *key, gint *sign)
1511 {
1512         ExifItem *item;
1513
1514         item = exif_get_item(exif, key);
1515         return exif_item_get_rational(item, sign);
1516 }
1517
1518
1519 gchar *exif_get_data_as_text(ExifData *exif, const gchar *key)
1520 {
1521         ExifItem *item;
1522         gchar *text;
1523         gint key_valid;
1524
1525         if (!key) return NULL;
1526
1527         text = exif_get_formatted_by_key(exif, key, &key_valid);
1528         if (key_valid) return text;
1529
1530         item = exif_get_item(exif, key);
1531         if (item) return exif_item_get_data_as_text(item);
1532
1533         return NULL;
1534 }
1535
1536 const gchar *exif_get_tag_description_by_key(const gchar *key)
1537 {
1538         gint i;
1539
1540         if (!key) return NULL;
1541
1542         i = 0;
1543         while (ExifKnownMarkersList[i].tag > 0)
1544                 {
1545                 if (strcmp(key, ExifKnownMarkersList[i].key) == 0) return _(ExifKnownMarkersList[i].description);
1546                 i++;
1547                 }
1548
1549         return NULL;
1550 }
1551
1552 static void exif_write_item(FILE *f, ExifItem *item)
1553 {
1554         gchar *text;
1555
1556         text = exif_item_get_data_as_text(item);
1557         if (text)
1558                 {
1559                 fprintf(f, "%4x %9s %30s %s\n", item->tag, ExifFormatList[item->format].short_name,
1560                         exif_item_get_tag_name(item), text);
1561                 }
1562         g_free(text);
1563 }
1564
1565 void exif_write_data_list(ExifData *exif, FILE *f, gint human_readable_list)
1566 {
1567         if (!f || !exif) return;
1568
1569         fprintf(f, " tag   format                             key value\n");
1570         fprintf(f, "----------------------------------------------------\n");
1571
1572         if (human_readable_list)
1573                 {
1574                 gint i;
1575
1576                 i = 0;
1577                 while (ExifFormattedList[i].key)
1578                         {
1579                         gchar *text;
1580
1581                         text = exif_get_formatted_by_key(exif, ExifFormattedList[i].key, NULL);
1582                         if (text)
1583                                 {
1584                                 fprintf(f, "     %9s %30s %s\n", "string", ExifFormattedList[i].key, text);
1585                                 }
1586                         i++;
1587                         }
1588                 }
1589         else
1590                 {
1591                 GList *work;
1592
1593                 work = exif->items;
1594                 while (work)
1595                         {
1596                         ExifItem *item;
1597
1598                         item = work->data;
1599                         work = work->next;
1600
1601                         exif_write_item(f, item);
1602                         }
1603                 }
1604         fprintf(f, "----------------------------------------------------\n");
1605 }
1606
1607 #endif 
1608 /* not HAVE_EXIV2 */