configure --without-exiv2
[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 char *exif_item_get_tag_name(ExifItem *item)
495 {
496         if (!item || !item->marker) return NULL;
497         return g_strdup(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                 gchar *tag = exif_item_get_tag_name(item);
698                 printf("exif tag %s data size mismatch\n", tag);
699                 g_free(tag);
700                 return;
701                 }
702
703         switch (item->format)
704                 {
705                 case EXIF_FORMAT_UNKNOWN:
706                         break;
707                 case EXIF_FORMAT_BYTE_UNSIGNED:
708                 case EXIF_FORMAT_BYTE:
709                 case EXIF_FORMAT_UNDEFINED:
710                         memcpy(dest, src, len);
711                         break;
712                 case EXIF_FORMAT_STRING:
713                         memcpy(dest, src, len);
714                         /* string is NULL terminated, make sure this is true */
715                         if (((char *)dest)[len - 1] != '\0') ((char *)dest)[len - 1] = '\0';
716                         break;
717                 case EXIF_FORMAT_SHORT_UNSIGNED:
718                 case EXIF_FORMAT_SHORT:
719                         for (i = 0; i < ne; i++)
720                                 {
721                                 ((guint16 *)dest)[i] = exif_byte_get_int16(src + i * bs, bo);
722                                 }
723                         break;
724                 case EXIF_FORMAT_LONG_UNSIGNED:
725                 case EXIF_FORMAT_LONG:
726                         if (src_format == EXIF_FORMAT_SHORT_UNSIGNED ||
727                             src_format == EXIF_FORMAT_SHORT)
728                                 {
729                                 /* a short fits into a long, so allow it */
730                                 gint ss;
731
732                                 ss = ExifFormatList[src_format].size;
733                                 for (i = 0; i < ne; i++)
734                                         {
735                                         ((gint32 *)dest)[i] =
736                                                 (gint32)exif_byte_get_int16(src + i * ss, bo);
737                                         }
738                                 }
739                         else
740                                 {
741                                 for (i = 0; i < ne; i++)
742                                         {
743                                         ((gint32 *)dest)[i] =
744                                                 exif_byte_get_int32(src + i * bs, bo);
745                                         }
746                                 }
747                         break;
748                 case EXIF_FORMAT_RATIONAL_UNSIGNED:
749                 case EXIF_FORMAT_RATIONAL:
750                         for (i = 0; i < ne; i++)
751                                 {
752                                 rational_from_data(&((ExifRational *)dest)[i], src + i * bs, bo);
753                                 }
754                         break;
755                 case EXIF_FORMAT_FLOAT:
756                         for (i = 0; i < ne; i++)
757                                 {
758                                 ((float *)dest)[i] = exif_byte_get_int32(src + i * bs, bo);
759                                 }
760                         break;
761                 case EXIF_FORMAT_DOUBLE:
762                         for (i = 0; i < ne; i++)
763                                 {
764                                 ExifRational r;
765
766                                 rational_from_data(&r, src + i * bs, bo);
767                                 if (r.den) ((double *)dest)[i] = (double)r.num / r.den;
768                                 }
769                         break;
770                 }
771 }
772
773 static gint exif_parse_IFD_entry(ExifData *exif, unsigned char *tiff, guint offset,
774                                  guint size, ExifByteOrder bo,
775                                  gint level,
776                                  const ExifMarker *list)
777 {
778         guint tag;
779         guint format;
780         guint count;
781         guint data_val;
782         guint data_offset;
783         guint data_length;
784         const ExifMarker *marker;
785         ExifItem *item;
786
787         tag = exif_byte_get_int16(tiff + offset + EXIF_TIFD_OFFSET_TAG, bo);
788         format = exif_byte_get_int16(tiff + offset + EXIF_TIFD_OFFSET_FORMAT, bo);
789         count = exif_byte_get_int32(tiff + offset + EXIF_TIFD_OFFSET_COUNT, bo);
790         data_val = exif_byte_get_int32(tiff + offset + EXIF_TIFD_OFFSET_DATA, bo);
791
792         /* Check tag type. If it does not match, either the format is wrong,
793          * either it is a unknown tag; so it is not really an error.
794          */
795         marker = exif_marker_from_tag(tag, list);
796         if (!marker)
797                 {
798                 if (format >= EXIF_FORMAT_COUNT)
799                         {
800                         printf("warning: exif tag 0x%4x has invalid format %d\n", tag, format);
801                         return 0;
802                         }
803                 /* allow non recognized tags to be displayed */
804                 marker = &ExifUnknownMarkersList[format];
805                 }
806         if (marker->format != format)
807                 {
808                 /* Some cameras got mixed up signed/unsigned_rational
809                  * eg KODAK DC4800 on object_distance tag
810                  *
811                  * FIXME: what exactly is this test trying to do?
812                  * ok, so this test is to allow the case of swapped signed/unsigned mismatch to leak through?
813                  */
814                 if (!(marker->format == EXIF_FORMAT_RATIONAL_UNSIGNED && format == EXIF_FORMAT_RATIONAL) &&
815                     !(marker->format == EXIF_FORMAT_RATIONAL && format == EXIF_FORMAT_RATIONAL_UNSIGNED) &&
816                         /* short fits into a long so allow this mismatch
817                          * as well (some tags allowed to be unsigned short _or_ unsigned long)
818                          */
819                     !(marker->format == EXIF_FORMAT_LONG_UNSIGNED && format == EXIF_FORMAT_SHORT_UNSIGNED) )
820                         {
821                         if (format < EXIF_FORMAT_COUNT)
822                                 {
823                                 printf("warning: exif tag %s format mismatch, found %s exif spec requests %s\n",
824                                         marker->key, ExifFormatList[format].short_name,
825                                         ExifFormatList[marker->format].short_name);
826                                 }
827                         else
828                                 {
829                                 printf("warning: exif tag %s format mismatch, found unknown id %d exif spec requests %d (%s)\n",
830                                         marker->key, format, marker->format,
831                                         ExifFormatList[marker->format].short_name);
832                                 }
833                         return 0;
834                         }
835                 }
836
837         /* Where is the data, is it available?
838          */
839         if (marker->components > 0 && marker->components != count)
840                 {
841                 printf("warning: exif tag %s has %d elements, exif spec requests %d\n",
842                         marker->key, count, marker->components);
843                 }
844
845         data_length = ExifFormatList[marker->format].size * count;
846         if (data_length > 4)
847                 {
848                 data_offset = data_val;
849                 if (size < data_offset + data_length)
850                         {
851                         printf("warning: exif tag %s data will overrun end of file, ignored.\n", marker->key);
852                         return -1;
853                         }
854                 }
855         else
856                 {
857                 data_offset = offset + EXIF_TIFD_OFFSET_DATA;
858                 }
859
860         item = exif_item_new(marker->format, tag, count, marker);
861         exif_item_copy_data(item, tiff + data_offset, data_length, format, bo);
862         exif->items = g_list_prepend(exif->items, item);
863
864         if (list == ExifKnownMarkersList)
865                 {
866                 switch (item->tag)
867                         {
868                         case TAG_EXIFOFFSET:
869                                 exif_parse_IFD_table(exif, tiff, data_val, size, bo, level + 1, list);
870                                 break;
871                         case TAG_EXIFMAKERNOTE:
872                                 format_exif_makernote_parse(exif, tiff, data_val, size, bo);
873                                 break;
874                         }
875                 }
876
877         return 0;
878 }
879
880 gint exif_parse_IFD_table(ExifData *exif,
881                           unsigned char *tiff, guint offset,
882                           guint size, ExifByteOrder bo,
883                           gint level,
884                           const ExifMarker *list)
885 {
886         guint count;
887         guint i;
888
889         /* limit damage from infinite loops */
890         if (level > EXIF_TIFF_MAX_LEVELS) return -1;
891
892         /* We should be able to read number of entries in IFD0) */
893         if (size < offset + 2) return -1;
894
895         count = exif_byte_get_int16(tiff + offset, bo);
896         offset += 2;
897
898         /* Entries and next IFD offset must be readable */
899         if (size < offset + count * EXIF_TIFD_SIZE + 4) return -1;
900
901         for (i = 0; i < count; i++)
902                 {
903                 exif_parse_IFD_entry(exif, tiff, offset + i * EXIF_TIFD_SIZE, size, bo, level, list);
904                 }
905
906         return 0;
907 }
908
909 /*
910  *-------------------------------------------------------------------
911  * file formats
912  *-------------------------------------------------------------------
913  */
914
915 gint exif_tiff_directory_offset(unsigned char *data, const guint len,
916                                 guint *offset, ExifByteOrder *bo)
917 {
918         if (len < 8) return FALSE;
919
920         if (memcmp(data, "II", 2) == 0)
921                 {
922                 *bo = EXIF_BYTE_ORDER_INTEL;
923                 }
924         else if (memcmp(data, "MM", 2) == 0)
925                 {
926                 *bo = EXIF_BYTE_ORDER_MOTOROLA;
927                 }
928         else
929                 {
930                 return FALSE;
931                 }
932
933         if (exif_byte_get_int16(data + 2, *bo) != 0x002A)
934                 {
935                 return FALSE;
936                 }
937
938         *offset = exif_byte_get_int32(data + 4, *bo);
939
940         return (*offset < len);
941 }
942
943 gint exif_tiff_parse(ExifData *exif, unsigned char *tiff, guint size, ExifMarker *list)
944 {
945         ExifByteOrder bo;
946         guint offset;
947
948         if (!exif_tiff_directory_offset(tiff, size, &offset, &bo)) return -1;
949
950         return exif_parse_IFD_table(exif, tiff, offset, size, bo, 0, list);
951 }
952
953 /*
954  *-------------------------------------------------------------------
955  * jpeg marker utils
956  *-------------------------------------------------------------------
957  */
958
959 #define JPEG_MARKER             0xFF
960 #define JPEG_MARKER_SOI         0xD8
961 #define JPEG_MARKER_EOI         0xD9
962 #define JPEG_MARKER_APP1        0xE1
963 #define JPEG_MARKER_APP2        0xE2
964
965 /* jpeg container format:
966      all data markers start with 0XFF
967      2 byte long file start and end markers: 0xFFD8(SOI) and 0XFFD9(EOI)
968      4 byte long data segment markers in format: 0xFFTTSSSSNNN...
969        FF:   1 byte standard marker identifier
970        TT:   1 byte data type
971        SSSS: 2 bytes in Motorola byte alignment for length of the data.
972              This value includes these 2 bytes in the count, making actual
973              length of NN... == SSSS - 2.
974        NNN.: the data in this segment
975  */
976
977 static gint exif_jpeg_segment_find(unsigned char *data, guint size,
978                                    guchar app_marker, const gchar *magic, guint magic_len,
979                                    guint *seg_offset, guint *seg_length)
980 {
981         guchar marker = 0;
982         guint offset = 0;
983         guint length = 0;
984
985         while (marker != app_marker &&
986                marker != JPEG_MARKER_EOI)
987                 {
988                 offset += length;
989                 length = 2;
990
991                 if (offset + 2 >= size ||
992                     data[offset] != JPEG_MARKER) return FALSE;
993
994                 marker = data[offset + 1];
995                 if (marker != JPEG_MARKER_SOI &&
996                     marker != JPEG_MARKER_EOI)
997                         {
998                         if (offset + 4 >= size) return FALSE;
999                         length += exif_byte_get_int16(data + offset + 2, EXIF_BYTE_ORDER_MOTOROLA);
1000                         }
1001                 }
1002
1003         if (marker == app_marker &&
1004             offset + length < size &&
1005             length >= 4 + magic_len &&
1006             memcmp(data + offset + 4, magic, magic_len) == 0)
1007                 {
1008                 *seg_offset = offset + 4;
1009                 *seg_length = length - 4;
1010                 return TRUE;
1011                 }
1012
1013         return FALSE;
1014 }
1015
1016 static ExifMarker jpeg_color_marker = { 0x8773, EXIF_FORMAT_UNDEFINED, -1, "ColorProfile", NULL, NULL };
1017
1018 static gint exif_jpeg_parse_color(ExifData *exif, unsigned char *data, guint size)
1019 {
1020         guint seg_offset = 0;
1021         guint seg_length = 0;
1022         guint chunk_offset[255];
1023         guint chunk_length[255];
1024         guint chunk_count = 0;
1025
1026         /* For jpeg/jfif, ICC color profile data can be in more than one segment.
1027            the data is in APP2 data segments that start with "ICC_PROFILE\x00\xNN\xTT"
1028            NN = segment number for data
1029            TT = total number of ICC segments (TT in each ICC segment should match)
1030          */
1031
1032         while (exif_jpeg_segment_find(data + seg_offset + seg_length,
1033                                       size - seg_offset - seg_length,
1034                                       JPEG_MARKER_APP2,
1035                                       "ICC_PROFILE\x00", 12,
1036                                       &seg_offset, &seg_length))
1037                 {
1038                 guchar chunk_num;
1039                 guchar chunk_tot;
1040
1041                 if (seg_length < 14) return FALSE;
1042
1043                 chunk_num = data[seg_offset + 12];
1044                 chunk_tot = data[seg_offset + 13];
1045
1046                 if (chunk_num == 0 || chunk_tot == 0) return FALSE;
1047
1048                 if (chunk_count == 0)
1049                         {
1050                         guint i;
1051
1052                         chunk_count = (guint)chunk_tot;
1053                         for (i = 0; i < chunk_count; i++) chunk_offset[i] = 0;
1054                         for (i = 0; i < chunk_count; i++) chunk_length[i] = 0;
1055                         }
1056
1057                 if (chunk_tot != chunk_count ||
1058                     chunk_num > chunk_count) return FALSE;
1059
1060                 chunk_num--;
1061                 chunk_offset[chunk_num] = seg_offset + 14;
1062                 chunk_length[chunk_num] = seg_length - 14;
1063                 }
1064
1065         if (chunk_count > 0)
1066                 {
1067                 ExifItem *item;
1068                 unsigned char *cp_data;
1069                 guint cp_length = 0;
1070                 guint i;
1071
1072                 for (i = 0; i < chunk_count; i++) cp_length += chunk_length[i];
1073                 cp_data = g_malloc(cp_length);
1074
1075                 for (i = 0; i < chunk_count; i++)
1076                         {
1077                         if (chunk_offset[i] == 0)
1078                                 {
1079                                 /* error, we never saw this chunk */
1080                                 g_free(cp_data);
1081                                 return FALSE;
1082                                 }
1083                         memcpy(cp_data, data + chunk_offset[i], chunk_length[i]);
1084                         }
1085
1086                 item = exif_item_new(jpeg_color_marker.format, jpeg_color_marker.tag, 1,
1087                                      &jpeg_color_marker);
1088                 g_free(item->data);
1089                 item->data = cp_data;
1090                 item->elements = cp_length;
1091                 item->data_len = cp_length;
1092                 exif->items = g_list_prepend(exif->items, item);
1093
1094                 return TRUE;
1095                 }
1096
1097         return FALSE;
1098 }
1099
1100 static gint exif_jpeg_parse(ExifData *exif,
1101                             unsigned char *data, guint size,
1102                             ExifMarker *list, gint parse_color)
1103 {
1104         guint seg_offset = 0;
1105         guint seg_length = 0;
1106         gint res = -1;
1107
1108         if (size < 4 ||
1109             memcmp(data, "\xFF\xD8", 2) != 0)
1110                 {
1111                 return -2;
1112                 }
1113
1114         if (exif_jpeg_segment_find(data, size, JPEG_MARKER_APP1,
1115                                    "Exif\x00\x00", 6,
1116                                    &seg_offset, &seg_length))
1117                 {
1118                 res = exif_tiff_parse(exif, data + seg_offset + 6, seg_length - 6, list);
1119                 }
1120
1121         if (parse_color &&
1122             exif_jpeg_parse_color(exif, data, size))
1123                 {
1124                 res = 0;
1125                 }
1126
1127         return res;
1128 }
1129
1130
1131 /*
1132  *-------------------------------------------------------------------
1133  * misc
1134  *-------------------------------------------------------------------
1135  */
1136
1137
1138 ExifItem *exif_get_first_item(ExifData *exif)
1139 {
1140         if (exif->items) 
1141                 {
1142                 ExifItem *ret = (ExifItem *)exif->items->data;
1143                 exif->current = exif->items->next;
1144                 return ret;
1145                 }
1146         exif->current = NULL;
1147         return NULL;
1148 }
1149
1150 ExifItem *exif_get_next_item(ExifData *exif)
1151 {
1152         if (exif->current) 
1153                 {
1154                 ExifItem *ret = (ExifItem *)exif->current->data;
1155                 exif->current = exif->current->next;
1156                 return ret;
1157                 }
1158         return NULL;
1159 }
1160
1161
1162
1163 static gint map_file(const gchar *path, void **mapping, int *size)
1164 {
1165         int fd;
1166         struct stat fs;
1167
1168         if ((fd = open(path, O_RDONLY)) == -1)
1169                 {
1170                 perror(path);
1171                 return -1;
1172                 }
1173
1174         if (fstat(fd, &fs) == -1)
1175                 {
1176                 perror(path);
1177                 close(fd);
1178                 return -1;
1179                 }
1180
1181         *size = fs.st_size;
1182
1183         if ((*mapping = mmap(0, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
1184                 {
1185                 perror(path);
1186                 close(fd);
1187                 return -1;
1188                 }
1189
1190         close(fd);
1191         return 0;
1192 }
1193
1194 static gint unmap_file(void *mapping, int size)
1195 {
1196         if (munmap(mapping, size) == -1)
1197                 {
1198                 perror("munmap");
1199                 return -1;
1200                 }
1201
1202         return 0;
1203 }
1204
1205 void exif_free(ExifData *exif)
1206 {
1207         GList *work;
1208
1209         if (!exif) return;
1210
1211         work = exif->items;
1212         while (work)
1213                 {
1214                 ExifItem *item = work->data;
1215                 work = work->next;
1216                 exif_item_free(item);
1217                 }
1218
1219         g_list_free(exif->items);
1220         g_free(exif);
1221 }
1222
1223 ExifData *exif_read(gchar *path, gchar *sidecar_path, gint parse_color_profile)
1224 {
1225         ExifData *exif;
1226         void *f;
1227         int size, res;
1228         gchar *pathl;
1229
1230         if (!path) return NULL;
1231
1232         pathl = path_from_utf8(path);
1233         if (map_file(pathl, &f, &size) == -1)
1234                 {
1235                 g_free(pathl);
1236                 return NULL;
1237                 }
1238         g_free(pathl);
1239
1240         exif = g_new0(ExifData, 1);
1241         exif->items = NULL;
1242         exif->current = NULL;
1243
1244         if ((res = exif_jpeg_parse(exif, (unsigned char *)f, size,
1245                                    ExifKnownMarkersList,
1246                                    parse_color_profile)) == -2)
1247                 {
1248                 res = exif_tiff_parse(exif, (unsigned char *)f, size, ExifKnownMarkersList);
1249                 }
1250
1251         if (res != 0)
1252                 {
1253                 FormatRawExifType exif_type;
1254                 FormatRawExifParseFunc exif_parse_func;
1255                 guint32 offset = 0;
1256
1257                 exif_type = format_raw_exif_offset(f, size, &offset, &exif_parse_func);
1258                 switch (exif_type)
1259                         {
1260                         case FORMAT_RAW_EXIF_NONE:
1261                         default:
1262                                 break;
1263                         case FORMAT_RAW_EXIF_TIFF:
1264                                 res = exif_tiff_parse(exif, (unsigned char*)f + offset, size - offset,
1265                                                       ExifKnownMarkersList);
1266                                 break;
1267                         case FORMAT_RAW_EXIF_JPEG:
1268                                 res = exif_jpeg_parse(exif, (unsigned char*)f + offset, size - offset,
1269                                                       ExifKnownMarkersList, FALSE);
1270                                 break;
1271                         case FORMAT_RAW_EXIF_IFD_II:
1272                         case FORMAT_RAW_EXIF_IFD_MM:
1273                                 res = exif_parse_IFD_table(exif, (unsigned char*)f, offset, size - offset,
1274                                                            (exif_type == FORMAT_RAW_EXIF_IFD_II) ?
1275                                                                 EXIF_BYTE_ORDER_INTEL : EXIF_BYTE_ORDER_MOTOROLA,
1276                                                            0, ExifKnownMarkersList);
1277                                 break;
1278                         case FORMAT_RAW_EXIF_PROPRIETARY:
1279                                 if (exif_parse_func)
1280                                         {
1281                                         res = exif_parse_func((unsigned char*)f + offset, size - offset, exif);
1282                                         }
1283                                 break;
1284                         }
1285                 }
1286
1287         if (res != 0)
1288                 {
1289                 exif_free(exif);
1290                 exif = NULL;
1291                 }
1292
1293         unmap_file(f, size);
1294
1295         if (exif) exif->items = g_list_reverse(exif->items);
1296
1297 #if 0
1298         exif_write_data_list(exif, stdout, TRUE);
1299         exif_write_data_list(exif, stdout, FALSE);
1300 #endif
1301
1302         return exif;
1303 }
1304
1305 ExifItem *exif_get_item(ExifData *exif, const gchar *key)
1306 {
1307         GList *work;
1308
1309         if (!key) return NULL;
1310
1311         work = exif->items;
1312         while (work)
1313                 {
1314                 ExifItem *item;
1315
1316                 item = work->data;
1317                 work = work->next;
1318                 if (item->marker->key && strcmp(key, item->marker->key) == 0) return item;
1319                 }
1320         return NULL;
1321 }
1322
1323 #define EXIF_DATA_AS_TEXT_MAX_COUNT 16
1324
1325 gchar *exif_item_get_string(ExifItem *item, int idx)
1326 {
1327         return exif_item_get_data_as_text(item);
1328 }
1329
1330
1331 gchar *exif_item_get_data_as_text(ExifItem *item)
1332 {
1333         const ExifMarker *marker;
1334         gpointer data;
1335         GString *string;
1336         gchar *text;
1337         gint ne;
1338         gint i;
1339
1340         if (!item) return NULL;
1341
1342         marker = item->marker;
1343         if (!marker) return NULL;
1344
1345         data = item->data;
1346         ne = item->elements;
1347         if (ne > EXIF_DATA_AS_TEXT_MAX_COUNT) ne = EXIF_DATA_AS_TEXT_MAX_COUNT;
1348         string = g_string_new("");
1349         switch (item->format)
1350                 {
1351                 case EXIF_FORMAT_UNKNOWN:
1352                         break;
1353                 case EXIF_FORMAT_BYTE_UNSIGNED:
1354                 case EXIF_FORMAT_BYTE:
1355                 case EXIF_FORMAT_UNDEFINED:
1356                         if (ne == 1 && marker->list)
1357                                 {
1358                                 gchar *result;
1359                                 unsigned char val;
1360
1361                                 if (item->format == EXIF_FORMAT_BYTE_UNSIGNED ||
1362                                     item->format == EXIF_FORMAT_UNDEFINED)
1363                                         {
1364                                         val = ((unsigned char *)data)[0];
1365                                         }
1366                                 else
1367                                         {
1368                                         val = (unsigned char)(((signed char *)data)[0]);
1369                                         }
1370
1371                                 result = exif_text_list_find_value(marker->list, (guint)val);
1372                                 string = g_string_append(string, result);
1373                                 g_free(result);
1374                                 }
1375                         else
1376                                 {
1377                                 string = string_append_raw_bytes(string, data, ne);
1378                                 }
1379                         break;
1380                 case EXIF_FORMAT_STRING:
1381                         string = g_string_append(string, (gchar *)(item->data));
1382                         break;
1383                 case EXIF_FORMAT_SHORT_UNSIGNED:
1384                         if (ne == 1 && marker->list)
1385                                 {
1386                                 gchar *result;
1387
1388                                 result = exif_text_list_find_value(marker->list, ((guint16 *)data)[0]);
1389                                 string = g_string_append(string, result);
1390                                 g_free(result);
1391                                 }
1392                         else for (i = 0; i < ne; i++)
1393                                 {
1394                                 g_string_append_printf(string, "%s%hd", (i > 0) ? ", " : "",
1395                                                         ((guint16 *)data)[i]);
1396                                 }
1397                         break;
1398                 case EXIF_FORMAT_LONG_UNSIGNED:
1399                         for (i = 0; i < ne; i++)
1400                                 {
1401                                 g_string_append_printf(string, "%s%ld", (i > 0) ? ", " : "",
1402                                                         (unsigned long int)((guint32 *)data)[i]);
1403                                 }
1404                         break;
1405                 case EXIF_FORMAT_RATIONAL_UNSIGNED:
1406                         for (i = 0; i < ne; i++)
1407                                 {
1408                                 ExifRational *r;
1409
1410                                 r = &((ExifRational *)data)[i];
1411                                 g_string_append_printf(string, "%s%ld/%ld", (i > 0) ? ", " : "",
1412                                                         (unsigned long)r->num, (unsigned long)r->den);
1413                                 }
1414                         break;
1415                 case EXIF_FORMAT_SHORT:
1416                         for (i = 0; i < ne; i++)
1417                                 {
1418                                 g_string_append_printf(string, "%s%hd", (i > 0) ? ", " : "",
1419                                                         ((gint16 *)data)[i]);
1420                                 }
1421                         break;
1422                 case EXIF_FORMAT_LONG:
1423                         for (i = 0; i < ne; i++)
1424                                 {
1425                                 g_string_append_printf(string, "%s%ld", (i > 0) ? ", " : "",
1426                                                         (long int)((gint32 *)data)[i]);
1427                                 }
1428                         break;
1429                 case EXIF_FORMAT_RATIONAL:
1430                         for (i = 0; i < ne; i++)
1431                                 {
1432                                 ExifRational *r;
1433
1434                                 r = &((ExifRational *)data)[i];
1435                                 g_string_append_printf(string, "%s%ld/%ld", (i > 0) ? ", " : "",
1436                                                         (long)r->num, (long)r->den);
1437                                 }
1438                         break;
1439                 case EXIF_FORMAT_FLOAT:
1440                         for (i = 0; i < ne; i++)
1441                                 {
1442                                 g_string_append_printf(string, "%s%f", (i > 0) ? ", " : "",
1443                                                         ((float *)data)[i]);
1444                                 }
1445                         break;
1446                 case EXIF_FORMAT_DOUBLE:
1447                         for (i = 0; i < ne; i++)
1448                                 {
1449                                 g_string_append_printf(string, "%s%f", (i > 0) ? ", " : "",
1450                                                         ((double *)data)[i]);
1451                                 }
1452                         break;
1453                 }
1454
1455         if (item->elements > EXIF_DATA_AS_TEXT_MAX_COUNT &&
1456             item->format != EXIF_FORMAT_STRING)
1457                 {
1458                 g_string_append(string, " ...");
1459                 }
1460
1461         text = string->str;
1462         g_string_free(string, FALSE);
1463
1464         return text;
1465 }
1466
1467 gint exif_item_get_integer(ExifItem *item, gint *value)
1468 {
1469         if (!item) return FALSE;
1470
1471         switch (item->format)
1472                 {
1473                 case EXIF_FORMAT_SHORT:
1474                         *value = (gint)(((gint16 *)(item->data))[0]);
1475                         return TRUE;
1476                         break;
1477                 case EXIF_FORMAT_SHORT_UNSIGNED:
1478                         *value = (gint)(((guint16 *)(item->data))[0]);
1479                         return TRUE;
1480                         break;
1481                 case EXIF_FORMAT_LONG:
1482                         *value = (gint)(((gint32 *)(item->data))[0]);
1483                         return TRUE;
1484                         break;
1485                 case EXIF_FORMAT_LONG_UNSIGNED:
1486                         /* FIXME: overflow possible */
1487                         *value = (gint)(((guint32 *)(item->data))[0]);
1488                         return TRUE;
1489                 default:
1490                         /* all other type return FALSE */
1491                         break;
1492                 }
1493         return FALSE;
1494 }
1495
1496
1497 ExifRational *exif_item_get_rational(ExifItem *item, gint *sign)
1498 {
1499         if (!item) return NULL;
1500
1501         if (item->format == EXIF_FORMAT_RATIONAL ||
1502             item->format == EXIF_FORMAT_RATIONAL_UNSIGNED)
1503                 {
1504                 if (sign) *sign = (item->format == EXIF_FORMAT_RATIONAL);
1505                 return &((ExifRational *)(item->data))[0];
1506                 }
1507
1508         return NULL;
1509 }
1510
1511
1512
1513 const gchar *exif_get_tag_description_by_key(const gchar *key)
1514 {
1515         gint i;
1516
1517         if (!key) return NULL;
1518
1519         i = 0;
1520         while (ExifKnownMarkersList[i].tag > 0)
1521                 {
1522                 if (strcmp(key, ExifKnownMarkersList[i].key) == 0) return _(ExifKnownMarkersList[i].description);
1523                 i++;
1524                 }
1525
1526         return NULL;
1527 }
1528
1529 static void exif_write_item(FILE *f, ExifItem *item)
1530 {
1531         gchar *text;
1532
1533         text = exif_item_get_data_as_text(item);
1534         if (text)
1535                 {
1536                 gchar *tag = exif_item_get_tag_name(item);
1537                 fprintf(f, "%4x %9s %30s %s\n", item->tag, ExifFormatList[item->format].short_name,
1538                         tag, text);
1539                 g_free(tag);
1540                 }
1541         g_free(text);
1542 }
1543
1544 void exif_write_data_list(ExifData *exif, FILE *f, gint human_readable_list)
1545 {
1546         if (!f || !exif) return;
1547
1548         fprintf(f, " tag   format                             key value\n");
1549         fprintf(f, "----------------------------------------------------\n");
1550
1551         if (human_readable_list)
1552                 {
1553                 gint i;
1554
1555                 i = 0;
1556                 while (ExifFormattedList[i].key)
1557                         {
1558                         gchar *text;
1559
1560                         text = exif_get_formatted_by_key(exif, ExifFormattedList[i].key, NULL);
1561                         if (text)
1562                                 {
1563                                 fprintf(f, "     %9s %30s %s\n", "string", ExifFormattedList[i].key, text);
1564                                 }
1565                         i++;
1566                         }
1567                 }
1568         else
1569                 {
1570                 GList *work;
1571
1572                 work = exif->items;
1573                 while (work)
1574                         {
1575                         ExifItem *item;
1576
1577                         item = work->data;
1578                         work = work->next;
1579
1580                         exif_write_item(f, item);
1581                         }
1582                 }
1583         fprintf(f, "----------------------------------------------------\n");
1584 }
1585
1586 int exif_write(ExifData *exif)
1587 {
1588         printf("Not compiled with EXIF write support");
1589         return 0;
1590 }
1591
1592 ExifItem *exif_add_item(ExifData *exif, const gchar *key)
1593 {
1594         return NULL;
1595 }
1596
1597 int exif_item_delete(ExifData *exif, ExifItem *item)
1598 {
1599         return 0;
1600 }
1601
1602 int exif_item_set_string(ExifItem *item, const char *str)
1603 {
1604         return 0;
1605 }
1606
1607
1608
1609 #endif 
1610 /* not HAVE_EXIV2 */