1 //--------------------------------------------------------------------------
2 // Program to pull the information out of various types of EXIF digital
3 // camera files and show it in a reasonably consistent way
4 //
5 // This module parses the very complicated exif structures.
6 //
7 // Matthias Wandel
8 //--------------------------------------------------------------------------
9 #include "jhead.h"
10 
11 #include <math.h>
12 #include <ctype.h>
13 #include <utils/Log.h>
14 
15 static unsigned char * DirWithThumbnailPtrs;
16 static double FocalplaneXRes;
17 static double FocalplaneUnits;
18 static int ExifImageWidth;
19 static int MotorolaOrder = 0;
20 
21 // for fixing the rotation.
22 static void * OrientationPtr[2];
23 static int    OrientationNumFormat[2];
24 int NumOrientations = 0;
25 
26 
27 // Define the line below to turn on poor man's debugging output
28 #undef SUPERDEBUG
29 
30 #ifdef SUPERDEBUG
31 #define printf ALOGE
32 #endif
33 
34 //--------------------------------------------------------------------------
35 // Table of Jpeg encoding process names
36 static const TagTable_t ProcessTable[] = {
37     { M_SOF0,   "Baseline", 0, 0},
38     { M_SOF1,   "Extended sequential", 0, 0},
39     { M_SOF2,   "Progressive", 0, 0},
40     { M_SOF3,   "Lossless", 0, 0},
41     { M_SOF5,   "Differential sequential", 0, 0},
42     { M_SOF6,   "Differential progressive", 0, 0},
43     { M_SOF7,   "Differential lossless", 0, 0},
44     { M_SOF9,   "Extended sequential, arithmetic coding", 0, 0},
45     { M_SOF10,  "Progressive, arithmetic coding", 0, 0},
46     { M_SOF11,  "Lossless, arithmetic coding", 0, 0},
47     { M_SOF13,  "Differential sequential, arithmetic coding", 0, 0},
48     { M_SOF14,  "Differential progressive, arithmetic coding", 0, 0},
49     { M_SOF15,  "Differential lossless, arithmetic coding", 0, 0},
50 };
51 
52 #define PROCESS_TABLE_SIZE  (sizeof(ProcessTable) / sizeof(TagTable_t))
53 
54 // 1 - "The 0th row is at the visual top of the image,    and the 0th column is the visual left-hand side."
55 // 2 - "The 0th row is at the visual top of the image,    and the 0th column is the visual right-hand side."
56 // 3 - "The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side."
57 // 4 - "The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side."
58 
59 // 5 - "The 0th row is the visual left-hand side of of the image,  and the 0th column is the visual top."
60 // 6 - "The 0th row is the visual right-hand side of of the image, and the 0th column is the visual top."
61 // 7 - "The 0th row is the visual right-hand side of of the image, and the 0th column is the visual bottom."
62 // 8 - "The 0th row is the visual left-hand side of of the image,  and the 0th column is the visual bottom."
63 
64 // Note: The descriptions here are the same as the name of the command line
65 // option to pass to jpegtran to right the image
66 
67 static const char * OrientTab[9] = {
68     "Undefined",
69     "Normal",           // 1
70     "flip horizontal",  // left right reversed mirror
71     "rotate 180",       // 3
72     "flip vertical",    // upside down mirror
73     "transpose",        // Flipped about top-left <--> bottom-right axis.
74     "rotate 90",        // rotate 90 cw to right it.
75     "transverse",       // flipped about top-right <--> bottom-left axis
76     "rotate 270",       // rotate 270 to right it.
77 };
78 
79 const int BytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8};
80 
81 //--------------------------------------------------------------------------
82 // Describes tag values
83 
84 #define TAG_INTEROP_INDEX          0x0001
85 #define TAG_INTEROP_VERSION        0x0002
86 #define TAG_IMAGE_WIDTH            0x0100
87 #define TAG_IMAGE_LENGTH           0x0101
88 #define TAG_BITS_PER_SAMPLE        0x0102
89 #define TAG_COMPRESSION            0x0103
90 #define TAG_PHOTOMETRIC_INTERP     0x0106
91 #define TAG_FILL_ORDER             0x010A
92 #define TAG_DOCUMENT_NAME          0x010D
93 #define TAG_IMAGE_DESCRIPTION      0x010E
94 #define TAG_MAKE                   0x010F
95 #define TAG_MODEL                  0x0110
96 #define TAG_SRIP_OFFSET            0x0111
97 #define TAG_ORIENTATION            0x0112
98 #define TAG_SAMPLES_PER_PIXEL      0x0115
99 #define TAG_ROWS_PER_STRIP         0x0116
100 #define TAG_STRIP_BYTE_COUNTS      0x0117
101 #define TAG_X_RESOLUTION           0x011A
102 #define TAG_Y_RESOLUTION           0x011B
103 #define TAG_PLANAR_CONFIGURATION   0x011C
104 #define TAG_RESOLUTION_UNIT        0x0128
105 #define TAG_TRANSFER_FUNCTION      0x012D
106 #define TAG_SOFTWARE               0x0131
107 #define TAG_DATETIME               0x0132
108 #define TAG_ARTIST                 0x013B
109 #define TAG_WHITE_POINT            0x013E
110 #define TAG_PRIMARY_CHROMATICITIES 0x013F
111 #define TAG_TRANSFER_RANGE         0x0156
112 #define TAG_JPEG_PROC              0x0200
113 #define TAG_THUMBNAIL_OFFSET       0x0201
114 #define TAG_THUMBNAIL_LENGTH       0x0202
115 #define TAG_Y_CB_CR_COEFFICIENTS   0x0211
116 #define TAG_Y_CB_CR_SUB_SAMPLING   0x0212
117 #define TAG_Y_CB_CR_POSITIONING    0x0213
118 #define TAG_REFERENCE_BLACK_WHITE  0x0214
119 #define TAG_RELATED_IMAGE_WIDTH    0x1001
120 #define TAG_RELATED_IMAGE_LENGTH   0x1002
121 #define TAG_CFA_REPEAT_PATTERN_DIM 0x828D
122 #define TAG_CFA_PATTERN1           0x828E
123 #define TAG_BATTERY_LEVEL          0x828F
124 #define TAG_COPYRIGHT              0x8298
125 #define TAG_EXPOSURETIME           0x829A
126 #define TAG_FNUMBER                0x829D
127 #define TAG_IPTC_NAA               0x83BB
128 #define TAG_EXIF_OFFSET            0x8769
129 #define TAG_INTER_COLOR_PROFILE    0x8773
130 #define TAG_EXPOSURE_PROGRAM       0x8822
131 #define TAG_SPECTRAL_SENSITIVITY   0x8824
132 #define TAG_GPSINFO                0x8825
133 #define TAG_ISO_EQUIVALENT         0x8827
134 #define TAG_OECF                   0x8828
135 #define TAG_EXIF_VERSION           0x9000
136 #define TAG_DATETIME_ORIGINAL      0x9003
137 #define TAG_DATETIME_DIGITIZED     0x9004
138 #define TAG_COMPONENTS_CONFIG      0x9101
139 #define TAG_CPRS_BITS_PER_PIXEL    0x9102
140 #define TAG_SHUTTERSPEED           0x9201
141 #define TAG_APERTURE               0x9202
142 #define TAG_BRIGHTNESS_VALUE       0x9203
143 #define TAG_EXPOSURE_BIAS          0x9204
144 #define TAG_MAXAPERTURE            0x9205
145 #define TAG_SUBJECT_DISTANCE       0x9206
146 #define TAG_METERING_MODE          0x9207
147 #define TAG_LIGHT_SOURCE           0x9208
148 #define TAG_FLASH                  0x9209
149 #define TAG_FOCALLENGTH            0x920A
150 #define TAG_MAKER_NOTE             0x927C
151 #define TAG_USERCOMMENT            0x9286
152 #define TAG_SUBSEC_TIME            0x9290
153 #define TAG_SUBSEC_TIME_ORIG       0x9291
154 #define TAG_SUBSEC_TIME_DIG        0x9292
155 
156 #define TAG_WINXP_TITLE            0x9c9b // Windows XP - not part of exif standard.
157 #define TAG_WINXP_COMMENT          0x9c9c // Windows XP - not part of exif standard.
158 #define TAG_WINXP_AUTHOR           0x9c9d // Windows XP - not part of exif standard.
159 #define TAG_WINXP_KEYWORDS         0x9c9e // Windows XP - not part of exif standard.
160 #define TAG_WINXP_SUBJECT          0x9c9f // Windows XP - not part of exif standard.
161 
162 #define TAG_FLASH_PIX_VERSION      0xA000
163 #define TAG_COLOR_SPACE            0xA001
164 #define TAG_EXIF_IMAGEWIDTH        0xA002
165 #define TAG_EXIF_IMAGELENGTH       0xA003
166 #define TAG_RELATED_AUDIO_FILE     0xA004
167 #define TAG_INTEROP_OFFSET         0xA005
168 #define TAG_FLASH_ENERGY           0xA20B
169 #define TAG_SPATIAL_FREQ_RESP      0xA20C
170 #define TAG_FOCAL_PLANE_XRES       0xA20E
171 #define TAG_FOCAL_PLANE_YRES       0xA20F
172 #define TAG_FOCAL_PLANE_UNITS      0xA210
173 #define TAG_SUBJECT_LOCATION       0xA214
174 #define TAG_EXPOSURE_INDEX         0xA215
175 #define TAG_SENSING_METHOD         0xA217
176 #define TAG_FILE_SOURCE            0xA300
177 #define TAG_SCENE_TYPE             0xA301
178 #define TAG_CFA_PATTERN            0xA302
179 #define TAG_CUSTOM_RENDERED        0xA401
180 #define TAG_EXPOSURE_MODE          0xA402
181 #define TAG_WHITEBALANCE           0xA403
182 #define TAG_DIGITALZOOMRATIO       0xA404
183 #define TAG_FOCALLENGTH_35MM       0xA405
184 #define TAG_SCENE_CAPTURE_TYPE     0xA406
185 #define TAG_GAIN_CONTROL           0xA407
186 #define TAG_CONTRAST               0xA408
187 #define TAG_SATURATION             0xA409
188 #define TAG_SHARPNESS              0xA40A
189 #define TAG_DISTANCE_RANGE         0xA40C
190 
191 // TODO: replace the ", 0" values in this table with the correct format, e.g. ", FMT_USHORT"
192 static const TagTable_t TagTable[] = {
193   { TAG_INTEROP_INDEX,          "InteropIndex", 0, 0},
194   { TAG_INTEROP_VERSION,        "InteropVersion", 0, 0},
195   { TAG_IMAGE_WIDTH,            "ImageWidth", FMT_USHORT, 1},
196   { TAG_IMAGE_LENGTH,           "ImageLength", FMT_USHORT, 1},
197   { TAG_BITS_PER_SAMPLE,        "BitsPerSample", FMT_USHORT, 3},
198   { TAG_COMPRESSION,            "Compression", FMT_USHORT, 1},
199   { TAG_PHOTOMETRIC_INTERP,     "PhotometricInterpretation", FMT_USHORT, 1},
200   { TAG_FILL_ORDER,             "FillOrder", 0, 0},
201   { TAG_DOCUMENT_NAME,          "DocumentName", 0, 0},
202   { TAG_IMAGE_DESCRIPTION,      "ImageDescription", 0, 0 },
203   { TAG_MAKE,                   "Make", FMT_STRING, -1},
204   { TAG_MODEL,                  "Model", FMT_STRING, -1},
205   { TAG_SRIP_OFFSET,            "StripOffsets", FMT_USHORT, 1},
206   { TAG_ORIENTATION,            "Orientation", FMT_USHORT, 1},
207   { TAG_SAMPLES_PER_PIXEL,      "SamplesPerPixel", FMT_USHORT, 3},
208   { TAG_ROWS_PER_STRIP,         "RowsPerStrip", FMT_USHORT, 1},
209   { TAG_STRIP_BYTE_COUNTS,      "StripByteCounts", FMT_USHORT, 1},
210   { TAG_X_RESOLUTION,           "XResolution", FMT_URATIONAL, 1},
211   { TAG_Y_RESOLUTION,           "YResolution", FMT_URATIONAL, 1},
212   { TAG_PLANAR_CONFIGURATION,   "PlanarConfiguration", FMT_USHORT, 1},
213   { TAG_RESOLUTION_UNIT,        "ResolutionUnit", FMT_USHORT, 1},
214   { TAG_TRANSFER_FUNCTION,      "TransferFunction", FMT_USHORT, 768},
215   { TAG_SOFTWARE,               "Software", FMT_STRING, -1},
216   { TAG_DATETIME,               "DateTime", FMT_STRING, 20},
217   { TAG_ARTIST,                 "Artist", FMT_STRING, -1},
218   { TAG_WHITE_POINT,            "WhitePoint", FMT_SRATIONAL, 2},
219   { TAG_PRIMARY_CHROMATICITIES, "PrimaryChromaticities", FMT_SRATIONAL, 6},
220   { TAG_TRANSFER_RANGE,         "TransferRange", 0, 0},
221   { TAG_JPEG_PROC,              "JPEGProc", 0, 0},
222   { TAG_THUMBNAIL_OFFSET,       "ThumbnailOffset", 0, 0},
223   { TAG_THUMBNAIL_LENGTH,       "ThumbnailLength", 0, 0},
224   { TAG_Y_CB_CR_COEFFICIENTS,   "YCbCrCoefficients", FMT_SRATIONAL, 3},
225   { TAG_Y_CB_CR_SUB_SAMPLING,   "YCbCrSubSampling", FMT_USHORT, 2},
226   { TAG_Y_CB_CR_POSITIONING,    "YCbCrPositioning", FMT_USHORT, 1},
227   { TAG_REFERENCE_BLACK_WHITE,  "ReferenceBlackWhite", FMT_SRATIONAL, 6},
228   { TAG_RELATED_IMAGE_WIDTH,    "RelatedImageWidth", 0, 0},
229   { TAG_RELATED_IMAGE_LENGTH,   "RelatedImageLength", 0, 0},
230   { TAG_CFA_REPEAT_PATTERN_DIM, "CFARepeatPatternDim", 0, 0},
231   { TAG_CFA_PATTERN1,           "CFAPattern", 0, 0},
232   { TAG_BATTERY_LEVEL,          "BatteryLevel", 0, 0},
233   { TAG_COPYRIGHT,              "Copyright", FMT_STRING, -1},
234   { TAG_EXPOSURETIME,           "ExposureTime", FMT_SRATIONAL, 1},
235   { TAG_FNUMBER,                "FNumber", FMT_SRATIONAL, 1},
236   { TAG_IPTC_NAA,               "IPTC/NAA", 0, 0},
237   { TAG_EXIF_OFFSET,            "ExifOffset", 0, 0},
238   { TAG_INTER_COLOR_PROFILE,    "InterColorProfile", 0, 0},
239   { TAG_EXPOSURE_PROGRAM,       "ExposureProgram", FMT_SSHORT, 1},
240   { TAG_SPECTRAL_SENSITIVITY,   "SpectralSensitivity", FMT_STRING, -1},
241   { TAG_GPSINFO,                "GPS Dir offset", 0, 0},
242   { TAG_ISO_EQUIVALENT,         "ISOSpeedRatings", FMT_SSHORT, -1},
243   { TAG_OECF,                   "OECF", 0, 0},
244   { TAG_EXIF_VERSION,           "ExifVersion", FMT_BYTE, 4},
245   { TAG_DATETIME_ORIGINAL,      "DateTimeOriginal", FMT_STRING, 20},
246   { TAG_DATETIME_DIGITIZED,     "DateTimeDigitized", FMT_STRING, 20},
247   { TAG_COMPONENTS_CONFIG,      "ComponentsConfiguration", FMT_BYTE, 4},
248   { TAG_CPRS_BITS_PER_PIXEL,    "CompressedBitsPerPixel", FMT_SRATIONAL, 1},
249   { TAG_SHUTTERSPEED,           "ShutterSpeedValue", FMT_SRATIONAL, 1},
250   { TAG_APERTURE,               "ApertureValue", FMT_URATIONAL, 1},
251   { TAG_BRIGHTNESS_VALUE,       "BrightnessValue", FMT_SRATIONAL, 1},
252   { TAG_EXPOSURE_BIAS,          "ExposureBiasValue", FMT_SRATIONAL, 1},
253   { TAG_MAXAPERTURE,            "MaxApertureValue", FMT_URATIONAL, 1},
254   { TAG_SUBJECT_DISTANCE,       "SubjectDistance", FMT_URATIONAL, 1},
255   { TAG_METERING_MODE,          "MeteringMode", FMT_USHORT, 1},
256   { TAG_LIGHT_SOURCE,           "LightSource", FMT_USHORT, 1},
257   { TAG_FLASH,                  "Flash", FMT_USHORT, 1},
258   { TAG_FOCALLENGTH,            "FocalLength", FMT_URATIONAL, 1},
259   { TAG_MAKER_NOTE,             "MakerNote", FMT_STRING, -1},
260   { TAG_USERCOMMENT,            "UserComment", FMT_STRING, -1},
261   { TAG_SUBSEC_TIME,            "SubSecTime", FMT_STRING, -1},
262   { TAG_SUBSEC_TIME_ORIG,       "SubSecTimeOriginal", FMT_STRING, -1},
263   { TAG_SUBSEC_TIME_DIG,        "SubSecTimeDigitized", FMT_STRING, -1},
264   { TAG_WINXP_TITLE,            "Windows-XP Title", 0, 0},
265   { TAG_WINXP_COMMENT,          "Windows-XP comment", 0, 0},
266   { TAG_WINXP_AUTHOR,           "Windows-XP author", 0, 0},
267   { TAG_WINXP_KEYWORDS,         "Windows-XP keywords", 0, 0},
268   { TAG_WINXP_SUBJECT,          "Windows-XP subject", 0, 0},
269   { TAG_FLASH_PIX_VERSION,      "FlashPixVersion", FMT_BYTE, 4},
270   { TAG_COLOR_SPACE,            "ColorSpace", FMT_USHORT, 1},
271   { TAG_EXIF_IMAGEWIDTH,        "ExifImageWidth", 0, 0},
272   { TAG_EXIF_IMAGELENGTH,       "ExifImageLength", 0, 0},
273   { TAG_RELATED_AUDIO_FILE,     "RelatedAudioFile", 0, 0},
274   { TAG_INTEROP_OFFSET,         "InteroperabilityOffset", 0, 0},
275   { TAG_FLASH_ENERGY,           "FlashEnergy", FMT_URATIONAL, 1},
276   { TAG_SPATIAL_FREQ_RESP,      "SpatialFrequencyResponse", FMT_STRING, -1},
277   { TAG_FOCAL_PLANE_XRES,       "FocalPlaneXResolution", FMT_URATIONAL, 1},
278   { TAG_FOCAL_PLANE_YRES,       "FocalPlaneYResolution", FMT_URATIONAL, 1},
279   { TAG_FOCAL_PLANE_UNITS,      "FocalPlaneResolutionUnit", FMT_USHORT, 1},
280   { TAG_SUBJECT_LOCATION,       "SubjectLocation", FMT_USHORT, 2},
281   { TAG_EXPOSURE_INDEX,         "ExposureIndex", FMT_URATIONAL, 1},
282   { TAG_SENSING_METHOD,         "SensingMethod", FMT_USHORT, 1},
283   { TAG_FILE_SOURCE,            "FileSource", 0, 1},
284   { TAG_SCENE_TYPE,             "SceneType", 0, 1},
285   { TAG_CFA_PATTERN,            "CFA Pattern", 0, -1},
286   { TAG_CUSTOM_RENDERED,        "CustomRendered", FMT_USHORT, 1},
287   { TAG_EXPOSURE_MODE,          "ExposureMode", FMT_USHORT, 1},
288   { TAG_WHITEBALANCE,           "WhiteBalance", FMT_USHORT, 1},
289   { TAG_DIGITALZOOMRATIO,       "DigitalZoomRatio", FMT_URATIONAL, 1},
290   { TAG_FOCALLENGTH_35MM,       "FocalLengthIn35mmFilm", FMT_USHORT, 1},
291   { TAG_SCENE_CAPTURE_TYPE,     "SceneCaptureType", FMT_USHORT, 1},
292   { TAG_GAIN_CONTROL,           "GainControl", FMT_URATIONAL, 1},
293   { TAG_CONTRAST,               "Contrast", FMT_USHORT, 1},
294   { TAG_SATURATION,             "Saturation", FMT_USHORT, 1},
295   { TAG_SHARPNESS,              "Sharpness", FMT_USHORT, 1},
296   { TAG_DISTANCE_RANGE,         "SubjectDistanceRange", FMT_USHORT, 1},
297 } ;
298 
299 #define TAG_TABLE_SIZE  (sizeof(TagTable) / sizeof(TagTable_t))
300 
TagNameToValue(const char * tagName)301 int TagNameToValue(const char* tagName)
302 {
303     unsigned int i;
304     for (i = 0; i < TAG_TABLE_SIZE; i++) {
305         if (strcmp(TagTable[i].Desc, tagName) == 0) {
306             printf("found tag %s val %d", TagTable[i].Desc, TagTable[i].Tag);
307             return TagTable[i].Tag;
308         }
309     }
310     printf("tag %s NOT FOUND", tagName);
311     return -1;
312 }
313 
IsDateTimeTag(unsigned short tag)314 int IsDateTimeTag(unsigned short tag)
315 {
316     return ((tag == TAG_DATETIME)? TRUE: FALSE);
317 }
318 
319 //--------------------------------------------------------------------------
320 // Convert a 16 bit unsigned value to file's native byte order
321 //--------------------------------------------------------------------------
Put16u(void * Short,unsigned short PutValue)322 static void Put16u(void * Short, unsigned short PutValue)
323 {
324     if (MotorolaOrder){
325         ((uchar *)Short)[0] = (uchar)(PutValue>>8);
326         ((uchar *)Short)[1] = (uchar)PutValue;
327     }else{
328         ((uchar *)Short)[0] = (uchar)PutValue;
329         ((uchar *)Short)[1] = (uchar)(PutValue>>8);
330     }
331 }
332 
333 //--------------------------------------------------------------------------
334 // Convert a 16 bit unsigned value from file's native byte order
335 //--------------------------------------------------------------------------
Get16u(void * Short)336 int Get16u(void * Short)
337 {
338     if (MotorolaOrder){
339         return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1];
340     }else{
341         return (((uchar *)Short)[1] << 8) | ((uchar *)Short)[0];
342     }
343 }
344 
345 //--------------------------------------------------------------------------
346 // Convert a 32 bit signed value from file's native byte order
347 //--------------------------------------------------------------------------
Get32s(void * Long)348 int Get32s(void * Long)
349 {
350     if (MotorolaOrder){
351         return  ((( char *)Long)[0] << 24) | (((uchar *)Long)[1] << 16)
352               | (((uchar *)Long)[2] << 8 ) | (((uchar *)Long)[3] << 0 );
353     }else{
354         return  ((( char *)Long)[3] << 24) | (((uchar *)Long)[2] << 16)
355               | (((uchar *)Long)[1] << 8 ) | (((uchar *)Long)[0] << 0 );
356     }
357 }
358 
359 //--------------------------------------------------------------------------
360 // Convert a 32 bit unsigned value to file's native byte order
361 //--------------------------------------------------------------------------
Put32u(void * Value,unsigned PutValue)362 void Put32u(void * Value, unsigned PutValue)
363 {
364     if (MotorolaOrder){
365         ((uchar *)Value)[0] = (uchar)(PutValue>>24);
366         ((uchar *)Value)[1] = (uchar)(PutValue>>16);
367         ((uchar *)Value)[2] = (uchar)(PutValue>>8);
368         ((uchar *)Value)[3] = (uchar)PutValue;
369     }else{
370         ((uchar *)Value)[0] = (uchar)PutValue;
371         ((uchar *)Value)[1] = (uchar)(PutValue>>8);
372         ((uchar *)Value)[2] = (uchar)(PutValue>>16);
373         ((uchar *)Value)[3] = (uchar)(PutValue>>24);
374     }
375 }
376 
377 //--------------------------------------------------------------------------
378 // Convert a 32 bit unsigned value from file's native byte order
379 //--------------------------------------------------------------------------
Get32u(void * Long)380 unsigned Get32u(void * Long)
381 {
382     return (unsigned)Get32s(Long) & 0xffffffff;
383 }
384 
385 //--------------------------------------------------------------------------
386 // Display a number as one of its many formats
387 //--------------------------------------------------------------------------
PrintFormatNumber(void * ValuePtr,int Format,int ByteCount)388 void PrintFormatNumber(void * ValuePtr, int Format, int ByteCount)
389 {
390     int s,n;
391 
392     for(n=0;n<16;n++){
393         switch(Format){
394             case FMT_SBYTE:
395             case FMT_BYTE:      printf("%02x",*(uchar *)ValuePtr); s=1;  break;
396             case FMT_USHORT:    printf("%d",Get16u(ValuePtr)); s=2;      break;
397             case FMT_ULONG:
398             case FMT_SLONG:     printf("%d",Get32s(ValuePtr)); s=4;      break;
399             case FMT_SSHORT:    printf("%hd",(signed short)Get16u(ValuePtr)); s=2; break;
400             case FMT_URATIONAL:
401             case FMT_SRATIONAL:
402                printf("%d/%d",Get32s(ValuePtr), Get32s(4+(char *)ValuePtr));
403                s = 8;
404                break;
405 
406             case FMT_SINGLE:    printf("%f",(double)*(float *)ValuePtr); s=8; break;
407             case FMT_DOUBLE:    printf("%f",*(double *)ValuePtr);        s=8; break;
408             default:
409                 printf("Unknown format %d:", Format);
410                 return;
411         }
412         ByteCount -= s;
413         if (ByteCount <= 0) break;
414         printf(", ");
415         ValuePtr = (void *)((char *)ValuePtr + s);
416 
417     }
418     if (n >= 16) printf("...");
419 }
420 
421 
422 //--------------------------------------------------------------------------
423 // Evaluate number, be it int, rational, or float from directory.
424 //--------------------------------------------------------------------------
ConvertAnyFormat(void * ValuePtr,int Format)425 double ConvertAnyFormat(void * ValuePtr, int Format)
426 {
427     double Value;
428     Value = 0;
429 
430     switch(Format){
431         case FMT_SBYTE:     Value = *(signed char *)ValuePtr;  break;
432         case FMT_BYTE:      Value = *(uchar *)ValuePtr;        break;
433 
434         case FMT_USHORT:    Value = Get16u(ValuePtr);          break;
435         case FMT_ULONG:     Value = Get32u(ValuePtr);          break;
436 
437         case FMT_URATIONAL:
438         case FMT_SRATIONAL:
439             {
440                 int Num,Den;
441                 Num = Get32s(ValuePtr);
442                 Den = Get32s(4+(char *)ValuePtr);
443                 if (Den == 0){
444                     Value = 0;
445                 }else{
446                     Value = (double)Num/Den;
447                 }
448                 break;
449             }
450 
451         case FMT_SSHORT:    Value = (signed short)Get16u(ValuePtr);  break;
452         case FMT_SLONG:     Value = Get32s(ValuePtr);                break;
453 
454         // Not sure if this is correct (never seen float used in Exif format)
455         case FMT_SINGLE:    Value = (double)*(float *)ValuePtr;      break;
456         case FMT_DOUBLE:    Value = *(double *)ValuePtr;             break;
457 
458         default:
459             ErrNonfatal("Illegal format code %d",Format,0);
460     }
461     return Value;
462 }
463 
464 //--------------------------------------------------------------------------
465 // Convert a double value into a signed or unsigned rational number.
466 //--------------------------------------------------------------------------
float2urat(double value,unsigned int max,unsigned int * numerator,unsigned int * denominator)467 static void float2urat(double value, unsigned int max, unsigned int *numerator,
468                        unsigned int *denominator) {
469     if (value <= 0) {
470         *numerator = 0;
471         *denominator = 1;
472         return;
473     }
474 
475     if (value > max) {
476         *numerator = max;
477         *denominator = 1;
478         return;
479     }
480 
481     // For values less than 1e-9, scale as much as possible
482     if (value < 1e-9) {
483         unsigned int n = (unsigned int)(value * max);
484         if (n == 0) {
485             *numerator = 0;
486             *denominator = 1;
487         } else {
488             *numerator = n;
489             *denominator = max;
490         }
491         return;
492     }
493 
494     // Try to use a denominator of 1e9, 1e8, ..., until the numerator fits
495     unsigned int d;
496     for (d = 1000000000; d >= 1; d /= 10) {
497         double s = value * d;
498         if (s <= max) {
499             // Remove the trailing zeros from both.
500             unsigned int n = (unsigned int)s;
501             while (n % 10 == 0 && d >= 10) {
502                 n /= 10;
503                 d /= 10;
504             }
505             *numerator = n;
506             *denominator = d;
507             return;
508         }
509     }
510 
511     // Shouldn't reach here because the denominator 1 should work
512     // above. But just in case.
513     *numerator = 0;
514     *denominator = 1;
515 }
516 
ConvertDoubleToURational(double value,unsigned int * numerator,unsigned int * denominator)517 static void ConvertDoubleToURational(double value, unsigned int *numerator,
518                                      unsigned int *denominator) {
519     float2urat(value, 0xFFFFFFFFU, numerator, denominator);
520 }
521 
ConvertDoubleToSRational(double value,int * numerator,int * denominator)522 static void ConvertDoubleToSRational(double value, int *numerator,
523                                      int *denominator) {
524     int negative = 0;
525 
526     if (value < 0) {
527         value = -value;
528         negative = 1;
529     }
530 
531     unsigned int n, d;
532     float2urat(value, 0x7FFFFFFFU, &n, &d);
533     *numerator = (int)n;
534     *denominator = (int)d;
535     if (negative) {
536         *numerator = -*numerator;
537     }
538 }
539 
540 //--------------------------------------------------------------------------
541 // Process one of the nested EXIF directories.
542 //--------------------------------------------------------------------------
ProcessExifDir(unsigned char * DirStart,unsigned char * OffsetBase,unsigned ExifLength,int NestingLevel)543 static void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase,
544         unsigned ExifLength, int NestingLevel)
545 {
546     int de;
547     int a;
548     int NumDirEntries;
549     unsigned ThumbnailOffset = 0;
550     unsigned ThumbnailSize = 0;
551     char IndentString[25];
552 
553     printf("ProcessExifDir");
554     if (NestingLevel > 4){
555         ErrNonfatal("Maximum directory nesting exceeded (corrupt exif header)", 0,0);
556         return;
557     }
558 
559     memset(IndentString, ' ', 25);
560     IndentString[NestingLevel * 4] = '\0';
561 
562 
563     NumDirEntries = Get16u(DirStart);
564     #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry))
565 
566     {
567         unsigned char * DirEnd;
568         DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries);
569         if (DirEnd+4 > (OffsetBase+ExifLength)){
570             if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){
571                 // Version 1.3 of jhead would truncate a bit too much.
572                 // This also caught later on as well.
573             }else{
574                 ErrNonfatal("Illegally sized exif subdirectory (%d entries)",NumDirEntries,0);
575                 return;
576             }
577         }
578         if (DumpExifMap){
579             printf("Map: %05d-%05d: Directory\n",(int)(DirStart-OffsetBase), (int)(DirEnd+4-OffsetBase));
580         }
581 
582 
583     }
584 
585     if (ShowTags){
586         printf("(dir has %d entries)\n",NumDirEntries);
587     }
588 
589     for (de=0;de<NumDirEntries;de++){
590         int Tag, Format, Components;
591         unsigned char * ValuePtr;
592         int ByteCount;
593         unsigned char * DirEntry;
594         DirEntry = DIR_ENTRY_ADDR(DirStart, de);
595 
596         Tag = Get16u(DirEntry);
597         Format = Get16u(DirEntry+2);
598         Components = Get32u(DirEntry+4);
599 
600         if ((Format-1) >= NUM_FORMATS) {
601             // (-1) catches illegal zero case as unsigned underflows to positive large.
602             ErrNonfatal("Illegal number format %d for tag %04x", Format, Tag);
603             continue;
604         }
605 
606         if ((unsigned)Components > 0x10000){
607             ErrNonfatal("Illegal number of components %d for tag %04x", Components, Tag);
608             continue;
609         }
610 
611         ByteCount = Components * BytesPerFormat[Format];
612 
613         if (ByteCount > 4){
614             unsigned OffsetVal;
615             OffsetVal = Get32u(DirEntry+8);
616             // If its bigger than 4 bytes, the dir entry contains an offset.
617             if (OffsetVal+ByteCount > ExifLength){
618                 // Bogus pointer offset and / or bytecount value
619                 ErrNonfatal("Illegal value pointer for tag %04x", Tag,0);
620                 continue;
621             }
622             ValuePtr = OffsetBase+OffsetVal;
623 
624             if (OffsetVal > ImageInfo.LargestExifOffset){
625                 ImageInfo.LargestExifOffset = OffsetVal;
626             }
627 
628             if (DumpExifMap){
629                 printf("Map: %05d-%05d:   Data for tag %04x\n",OffsetVal, OffsetVal+ByteCount, Tag);
630             }
631         }else{
632             // 4 bytes or less and value is in the dir entry itself
633             ValuePtr = DirEntry+8;
634         }
635 
636         if (Tag == TAG_MAKER_NOTE){
637             if (ShowTags){
638                 printf("%s    Maker note: ",IndentString);
639             }
640             ProcessMakerNote(ValuePtr, ByteCount, OffsetBase, ExifLength);
641             continue;
642         }
643 
644         if (ShowTags){
645             // Show tag name
646             for (a=0;;a++){
647                 if (a >= (int)TAG_TABLE_SIZE){
648                     printf("%s", IndentString);
649                     printf("    Unknown Tag %04x Value = ", Tag);
650                     break;
651                 }
652                 if (TagTable[a].Tag == Tag){
653                     printf("%s", IndentString);
654                     printf("    %s = ",TagTable[a].Desc);
655                     break;
656                 }
657             }
658 
659             // Show tag value.
660             switch(Format){
661                 case FMT_BYTE:
662                     if(ByteCount>1){
663                         printf("%.*ls\n", ByteCount/2, (wchar_t *)ValuePtr);
664                     }else{
665                         PrintFormatNumber(ValuePtr, Format, ByteCount);
666                         printf("\n");
667                     }
668                     break;
669 
670                 case FMT_UNDEFINED:
671                     // Undefined is typically an ascii string.
672 
673                 case FMT_STRING:
674                     // String arrays printed without function call (different from int arrays)
675                     {
676                           printf("\"%s\"", ValuePtr);
677 //                        int NoPrint = 0;
678 //                        printf("\"");
679 //                        for (a=0;a<ByteCount;a++){
680 //                            if (ValuePtr[a] >= 32){
681 //                                putchar(ValuePtr[a]);
682 //                                NoPrint = 0;
683 //                            }else{
684 //                                // Avoiding indicating too many unprintable characters of proprietary
685 //                                // bits of binary information this program may not know how to parse.
686 //                                if (!NoPrint && a != ByteCount-1){
687 //                                    putchar('?');
688 //                                    NoPrint = 1;
689 //                                }
690 //                            }
691 //                        }
692 //                        printf("\"\n");
693                     }
694                     break;
695 
696                 default:
697                     // Handle arrays of numbers later (will there ever be?)
698                     PrintFormatNumber(ValuePtr, Format, ByteCount);
699                     printf("\n");
700             }
701         }
702 
703         // Extract useful components of tag
704         switch(Tag){
705 
706             case TAG_MAKE:
707                 strncpy(ImageInfo.CameraMake, (char *)ValuePtr, ByteCount < 31 ? ByteCount : 31);
708                 break;
709 
710             case TAG_MODEL:
711                 strncpy(ImageInfo.CameraModel, (char *)ValuePtr, ByteCount < 39 ? ByteCount : 39);
712                 break;
713 
714             case TAG_SUBSEC_TIME:
715                 strlcpy(ImageInfo.SubSecTime, (char *)ValuePtr, sizeof(ImageInfo.SubSecTime));
716                 break;
717 
718             case TAG_SUBSEC_TIME_ORIG:
719                 strlcpy(ImageInfo.SubSecTimeOrig, (char *)ValuePtr,
720                         sizeof(ImageInfo.SubSecTimeOrig));
721                 break;
722 
723             case TAG_SUBSEC_TIME_DIG:
724                 strlcpy(ImageInfo.SubSecTimeDig, (char *)ValuePtr,
725                         sizeof(ImageInfo.SubSecTimeDig));
726                 break;
727 
728             case TAG_DATETIME_DIGITIZED:
729                 strlcpy(ImageInfo.DigitizedTime, (char *)ValuePtr,
730                         sizeof(ImageInfo.DigitizedTime));
731 
732                 if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
733                     ErrNonfatal("More than %d date fields!  This is nuts", MAX_DATE_COPIES, 0);
734                     break;
735                 }
736                 ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
737                     (char *)ValuePtr - (char *)OffsetBase;
738                 break;
739 
740             case TAG_DATETIME_ORIGINAL:
741                 // If we get a DATETIME_ORIGINAL, we use that one.
742                 strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
743                 // Fallthru...
744 
745             case TAG_DATETIME:
746                 if (!isdigit(ImageInfo.DateTime[0])){
747                     // If we don't already have a DATETIME_ORIGINAL, use whatever
748                     // time fields we may have.
749                     strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
750                 }
751 
752                 if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
753                     ErrNonfatal("More than %d date fields!  This is nuts", MAX_DATE_COPIES, 0);
754                     break;
755                 }
756                 ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
757                     (char *)ValuePtr - (char *)OffsetBase;
758                 break;
759 
760             case TAG_WINXP_COMMENT:
761                 if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
762                     // Already have a comment (probably windows comment), skip this one.
763                     if (ShowTags) printf("Windows XP commend and other comment in header\n");
764                     break; // Already have a windows comment, skip this one.
765                 }
766 
767                 if (ByteCount > 1){
768                     if (ByteCount > MAX_COMMENT_SIZE) ByteCount = MAX_COMMENT_SIZE;
769                     memcpy(ImageInfo.Comments, ValuePtr, ByteCount);
770                     ImageInfo.CommentWidchars = ByteCount/2;
771                 }
772                 break;
773 
774             case TAG_USERCOMMENT:
775                 if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
776                     // Already have a comment (probably windows comment), skip this one.
777                     if (ShowTags) printf("Multiple comments in exif header\n");
778                     break; // Already have a windows comment, skip this one.
779                 }
780 
781                 // Comment is often padded with trailing spaces.  Remove these first.
782                 for (a=ByteCount;;){
783                     a--;
784                     if ((ValuePtr)[a] == ' '){
785                         (ValuePtr)[a] = '\0';
786                     }else{
787                         break;
788                     }
789                     if (a == 0) break;
790                 }
791 
792                 // Copy the comment
793                 {
794                     // We want to set copied comment length (msize) to be the
795                     // minimum of:
796                     // (1) The space still available in Exif
797                     // (2) The given comment length (ByteCount)
798                     // (3) MAX_COMMENT_SIZE - 1
799                     int msiz = ExifLength - (ValuePtr-OffsetBase);
800                     if (msiz > ByteCount) msiz = ByteCount;
801                     if (msiz > MAX_COMMENT_SIZE - 1) msiz = MAX_COMMENT_SIZE - 1;
802                     if (msiz > 5 && memcmp(ValuePtr, "ASCII", 5) == 0) {
803                         for (a = 5; a < 10 && a < msiz; a++) {
804                             int c = (ValuePtr)[a];
805                             if (c != '\0' && c != ' ') {
806                                 strncpy(ImageInfo.Comments,
807                                         (char *)ValuePtr + a, msiz - a);
808                                 break;
809                             }
810                         }
811                     } else {
812                         strncpy(ImageInfo.Comments, (char *)ValuePtr, msiz);
813                     }
814                 }
815                 break;
816 
817             case TAG_FNUMBER:
818                 // Simplest way of expressing aperture, so I trust it the most.
819                 // (overwrite previously computd value if there is one)
820                 ImageInfo.ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format);
821                 break;
822 
823             case TAG_APERTURE:
824             case TAG_MAXAPERTURE:
825                 // More relevant info always comes earlier, so only use this field if we don't
826                 // have appropriate aperture information yet.
827                 if (ImageInfo.ApertureFNumber == 0){
828                     ImageInfo.ApertureFNumber
829                         = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5);
830                 }
831                 break;
832 
833             case TAG_FOCALLENGTH:
834                 // Nice digital cameras actually save the focal length as a function
835                 // of how farthey are zoomed in.
836                 ImageInfo.FocalLength.num = Get32u(ValuePtr);
837                 ImageInfo.FocalLength.denom = Get32u(4+(char *)ValuePtr);
838                 break;
839 
840             case TAG_SUBJECT_DISTANCE:
841                 // Inidcates the distacne the autofocus camera is focused to.
842                 // Tends to be less accurate as distance increases.
843                 ImageInfo.Distance = (float)ConvertAnyFormat(ValuePtr, Format);
844                 break;
845 
846             case TAG_EXPOSURETIME:
847                 // Simplest way of expressing exposure time, so I trust it most.
848                 // (overwrite previously computd value if there is one)
849                 ImageInfo.ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format);
850                 break;
851 
852             case TAG_SHUTTERSPEED:
853                 // More complicated way of expressing exposure time, so only use
854                 // this value if we don't already have it from somewhere else.
855                 if (ImageInfo.ExposureTime == 0){
856                     ImageInfo.ExposureTime
857                         = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2)));
858                 }
859                 break;
860 
861 
862             case TAG_FLASH:
863                 ImageInfo.FlashUsed=(int)ConvertAnyFormat(ValuePtr, Format);
864                 break;
865 
866             case TAG_ORIENTATION:
867                 if (NumOrientations >= 2){
868                     // Can have another orientation tag for the thumbnail, but if there's
869                     // a third one, things are stringae.
870                     ErrNonfatal("More than two orientation tags!",0,0);
871                     break;
872                 }
873                 OrientationPtr[NumOrientations] = ValuePtr;
874                 OrientationNumFormat[NumOrientations] = Format;
875                 if (NumOrientations == 0){
876                     ImageInfo.Orientation = (int)ConvertAnyFormat(ValuePtr, Format);
877                 }
878                 if (ImageInfo.Orientation < 0 || ImageInfo.Orientation > 8){
879                     ErrNonfatal("Undefined rotation value %d", ImageInfo.Orientation, 0);
880                     ImageInfo.Orientation = 0;
881                 }
882                 NumOrientations += 1;
883                 break;
884 
885             case TAG_EXIF_IMAGELENGTH:
886             case TAG_EXIF_IMAGEWIDTH:
887                 // Use largest of height and width to deal with images that have been
888                 // rotated to portrait format.
889                 a = (int)ConvertAnyFormat(ValuePtr, Format);
890                 if (ExifImageWidth < a) ExifImageWidth = a;
891                 break;
892 
893             case TAG_FOCAL_PLANE_XRES:
894                 FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format);
895                 break;
896 
897             case TAG_FOCAL_PLANE_UNITS:
898                 switch((int)ConvertAnyFormat(ValuePtr, Format)){
899                     case 1: FocalplaneUnits = 25.4; break; // inch
900                     case 2:
901                         // According to the information I was using, 2 means meters.
902                         // But looking at the Cannon powershot's files, inches is the only
903                         // sensible value.
904                         FocalplaneUnits = 25.4;
905                         break;
906 
907                     case 3: FocalplaneUnits = 10;   break;  // centimeter
908                     case 4: FocalplaneUnits = 1;    break;  // millimeter
909                     case 5: FocalplaneUnits = .001; break;  // micrometer
910                 }
911                 break;
912 
913             case TAG_EXPOSURE_BIAS:
914                 ImageInfo.ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format);
915                 break;
916 
917             case TAG_WHITEBALANCE:
918                 ImageInfo.Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format);
919                 break;
920 
921             case TAG_LIGHT_SOURCE:
922                 ImageInfo.LightSource = (int)ConvertAnyFormat(ValuePtr, Format);
923                 break;
924 
925             case TAG_METERING_MODE:
926                 ImageInfo.MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format);
927                 break;
928 
929             case TAG_EXPOSURE_PROGRAM:
930                 ImageInfo.ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format);
931                 break;
932 
933             case TAG_EXPOSURE_INDEX:
934                 if (ImageInfo.ISOequivalent == 0){
935                     // Exposure index and ISO equivalent are often used interchangeably,
936                     // so we will do the same in jhead.
937                     // http://photography.about.com/library/glossary/bldef_ei.htm
938                     ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
939                 }
940                 break;
941 
942             case TAG_EXPOSURE_MODE:
943                 ImageInfo.ExposureMode = (int)ConvertAnyFormat(ValuePtr, Format);
944                 break;
945 
946             case TAG_ISO_EQUIVALENT:
947                 ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
948                 if ( ImageInfo.ISOequivalent < 50 ){
949                     // Fixes strange encoding on some older digicams.
950                     ImageInfo.ISOequivalent *= 200;
951                 }
952                 break;
953 
954             case TAG_DIGITALZOOMRATIO:
955                 ImageInfo.DigitalZoomRatio = (float)ConvertAnyFormat(ValuePtr, Format);
956                 break;
957 
958             case TAG_THUMBNAIL_OFFSET:
959                 ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format);
960                 DirWithThumbnailPtrs = DirStart;
961                 break;
962 
963             case TAG_THUMBNAIL_LENGTH:
964                 ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format);
965                 ImageInfo.ThumbnailSizeOffset = ValuePtr-OffsetBase;
966                 break;
967 
968             case TAG_EXIF_OFFSET:
969                 if (ShowTags) printf("%s    Exif Dir:",IndentString);
970 
971             case TAG_INTEROP_OFFSET:
972                 if (Tag == TAG_INTEROP_OFFSET && ShowTags) printf("%s    Interop Dir:",IndentString);
973                 {
974                     unsigned char * SubdirStart;
975                     SubdirStart = OffsetBase + Get32u(ValuePtr);
976                     if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
977                         ErrNonfatal("Illegal exif or interop ofset directory link",0,0);
978                     }else{
979                         ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
980                     }
981                     continue;
982                 }
983                 break;
984 
985             case TAG_GPSINFO:
986                 if (ShowTags) printf("%s    GPS info dir:",IndentString);
987                 {
988                     unsigned char * SubdirStart;
989                     SubdirStart = OffsetBase + Get32u(ValuePtr);
990                     if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
991                         ErrNonfatal("Illegal GPS directory link",0,0);
992                     }else{
993                         ProcessGpsInfo(SubdirStart, ByteCount, OffsetBase, ExifLength);
994                     }
995                     continue;
996                 }
997                 break;
998 
999             case TAG_FOCALLENGTH_35MM:
1000                 // The focal length equivalent 35 mm is a 2.2 tag (defined as of April 2002)
1001                 // if its present, use it to compute equivalent focal length instead of
1002                 // computing it from sensor geometry and actual focal length.
1003                 ImageInfo.FocalLength35mmEquiv = (unsigned)ConvertAnyFormat(ValuePtr, Format);
1004                 break;
1005 
1006             case TAG_DISTANCE_RANGE:
1007                 // Three possible standard values:
1008                 //   1 = macro, 2 = close, 3 = distant
1009                 ImageInfo.DistanceRange = (int)ConvertAnyFormat(ValuePtr, Format);
1010                 break;
1011         }
1012     }
1013 
1014 
1015     {
1016         // In addition to linking to subdirectories via exif tags,
1017         // there's also a potential link to another directory at the end of each
1018         // directory.  this has got to be the result of a committee!
1019         unsigned char * SubdirStart;
1020         unsigned Offset;
1021 
1022         if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){
1023             printf("DirStart %p offset from dirstart %d", DirStart, 2+12*NumDirEntries);
1024             Offset = Get32u(DirStart+2+12*NumDirEntries);
1025             if (Offset){
1026                 SubdirStart = OffsetBase + Offset;
1027                 if (SubdirStart > OffsetBase+ExifLength || SubdirStart < OffsetBase){
1028                     printf("SubdirStart %p OffsetBase %p ExifLength %d Offset %d",
1029                         SubdirStart, OffsetBase, ExifLength, Offset);
1030                     if (SubdirStart > OffsetBase && SubdirStart < OffsetBase+ExifLength+20){
1031                         // Jhead 1.3 or earlier would crop the whole directory!
1032                         // As Jhead produces this form of format incorrectness,
1033                         // I'll just let it pass silently
1034                         if (ShowTags) printf("Thumbnail removed with Jhead 1.3 or earlier\n");
1035                     }else{
1036                         ErrNonfatal("Illegal subdirectory link",0,0);
1037                     }
1038                 }else{
1039                     if (SubdirStart <= OffsetBase+ExifLength){
1040                         if (ShowTags) printf("%s    Continued directory ",IndentString);
1041                         ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
1042                     }
1043                 }
1044                 if (Offset > ImageInfo.LargestExifOffset){
1045                     ImageInfo.LargestExifOffset = Offset;
1046                 }
1047             }
1048         }else{
1049             // The exif header ends before the last next directory pointer.
1050         }
1051     }
1052 
1053     if (ThumbnailOffset){
1054         ImageInfo.ThumbnailAtEnd = FALSE;
1055 
1056         if (DumpExifMap){
1057             printf("Map: %05d-%05d: Thumbnail\n",ThumbnailOffset, ThumbnailOffset+ThumbnailSize);
1058         }
1059 
1060         if (ThumbnailOffset <= ExifLength){
1061             if (ThumbnailSize > ExifLength-ThumbnailOffset){
1062                 // If thumbnail extends past exif header, only save the part that
1063                 // actually exists.  Canon's EOS viewer utility will do this - the
1064                 // thumbnail extracts ok with this hack.
1065                 ThumbnailSize = ExifLength-ThumbnailOffset;
1066                 if (ShowTags) printf("Thumbnail incorrectly placed in header\n");
1067 
1068             }
1069             // The thumbnail pointer appears to be valid.  Store it.
1070             ImageInfo.ThumbnailOffset = ThumbnailOffset;
1071             ImageInfo.ThumbnailSize = ThumbnailSize;
1072 
1073             if (ShowTags){
1074                 printf("Thumbnail size: %d bytes\n",ThumbnailSize);
1075             }
1076         }
1077     }
1078     printf("returning from ProcessExifDir");
1079 }
1080 
1081 
1082 //--------------------------------------------------------------------------
1083 // Process a EXIF marker
1084 // Describes all the drivel that most digital cameras include...
1085 //--------------------------------------------------------------------------
process_EXIF(unsigned char * ExifSection,unsigned int length)1086 void process_EXIF (unsigned char * ExifSection, unsigned int length)
1087 {
1088     int FirstOffset;
1089 
1090     FocalplaneXRes = 0;
1091     FocalplaneUnits = 0;
1092     ExifImageWidth = 0;
1093     NumOrientations = 0;
1094 
1095     if (ShowTags){
1096         printf("Exif header %d bytes long\n",length);
1097     }
1098 
1099     {   // Check the EXIF header component
1100         static uchar ExifHeader[] = "Exif\0\0";
1101         if (memcmp(ExifSection+2, ExifHeader,6)){
1102             ErrNonfatal("Incorrect Exif header",0,0);
1103             return;
1104         }
1105     }
1106 
1107     if (memcmp(ExifSection+8,"II",2) == 0){
1108         if (ShowTags) printf("Exif section in Intel order\n");
1109         MotorolaOrder = 0;
1110     }else{
1111         if (memcmp(ExifSection+8,"MM",2) == 0){
1112             if (ShowTags) printf("Exif section in Motorola order\n");
1113             MotorolaOrder = 1;
1114         }else{
1115             ErrNonfatal("Invalid Exif alignment marker.",0,0);
1116             return;
1117         }
1118     }
1119 
1120     // Check the next value for correctness.
1121     if (Get16u(ExifSection+10) != 0x2a){
1122         ErrNonfatal("Invalid Exif start (1)",0,0);
1123         return;
1124     }
1125 
1126     FirstOffset = Get32u(ExifSection+12);
1127     if (FirstOffset < 8 || FirstOffset > 16){
1128         // Usually set to 8, but other values valid too.
1129         ErrNonfatal("Suspicious offset of first IFD value",0,0);
1130         return;
1131     }
1132 
1133     DirWithThumbnailPtrs = NULL;
1134 
1135 
1136     // First directory starts 16 bytes in.  All offset are relative to 8 bytes in.
1137     ProcessExifDir(ExifSection+8+FirstOffset, ExifSection+8, length-8, 0);
1138 
1139     ImageInfo.ThumbnailAtEnd = ImageInfo.ThumbnailOffset >= ImageInfo.LargestExifOffset ? TRUE : FALSE;
1140 #ifdef SUPERDEBUG
1141     printf("Thumbnail %s end", (ImageInfo.ThumbnailAtEnd ? "at" : "NOT at"));
1142 #endif
1143     if (DumpExifMap){
1144         unsigned a,b;
1145         printf("Map: %05d- End of exif\n",length-8);
1146 //        for (a=0;a<length-8;a+= 10){
1147 //            printf("Map: %05d ",a);
1148 //            for (b=0;b<10;b++) printf(" %02x",*(ExifSection+8+a+b));
1149 //            printf("\n");
1150 //        }
1151         for (a = 0; a < length - 8; ++a) {
1152             unsigned char c = *(ExifSection+8+a);
1153             unsigned pc = isprint(c) ? c : ' ';
1154             printf("Map: %4d %02x %c", a, c, pc);
1155         }
1156     }
1157 
1158 
1159     // Compute the CCD width, in millimeters.
1160     if (FocalplaneXRes != 0){
1161         // Note: With some cameras, its not possible to compute this correctly because
1162         // they don't adjust the indicated focal plane resolution units when using less
1163         // than maximum resolution, so the CCDWidth value comes out too small.  Nothing
1164         // that Jhad can do about it - its a camera problem.
1165         ImageInfo.CCDWidth = (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes);
1166 
1167         if (ImageInfo.FocalLength.num != 0 && ImageInfo.FocalLength.denom != 0
1168             && ImageInfo.FocalLength35mmEquiv == 0){
1169             // Compute 35 mm equivalent focal length based on sensor geometry if we haven't
1170             // already got it explicitly from a tag.
1171             ImageInfo.FocalLength35mmEquiv = (int)(
1172                 (double)ImageInfo.FocalLength.num / ImageInfo.FocalLength.denom
1173                 / ImageInfo.CCDWidth * 36 + 0.5);
1174         }
1175     }
1176 }
1177 
TagToTagTableEntry(unsigned short tag)1178 static const TagTable_t* TagToTagTableEntry(unsigned short tag)
1179 {
1180     unsigned int i;
1181     for (i = 0; i < TAG_TABLE_SIZE; i++) {
1182         if (TagTable[i].Tag == tag) {
1183             printf("found tag %d", tag);
1184             int format = TagTable[i].Format;
1185             if (format == 0) {
1186                 printf("tag %s format not defined ***** YOU MUST ADD THE FORMAT TO THE TagTable in exif.c!!!!", TagTable[i].Desc);
1187                 return NULL;
1188             }
1189             return &TagTable[i];
1190         }
1191     }
1192     printf("tag %d NOT FOUND", tag);
1193     return NULL;
1194 }
1195 
writeExifTagAndData(int tag,int format,long components,long value,int valueInString,char * Buffer,int * DirIndex,int * DataWriteIndex)1196 static void writeExifTagAndData(int tag,
1197                                 int format,
1198                                 long components,
1199                                 long value,
1200                                 int valueInString,
1201                                 char* Buffer,
1202                                 int* DirIndex,
1203                                 int* DataWriteIndex) {
1204     void* componentsPosition = NULL; // for saving component position
1205 
1206     Put16u(Buffer+ (*DirIndex), tag);                    // Tag
1207     Put16u(Buffer+(*DirIndex) + 2, format);              // Format
1208     if (format == FMT_STRING && components == -1) {
1209         components = strlen((char*)value) + 1;                 // account for null terminator
1210         if (components & 1) ++components;               // no odd lengths
1211     } else if (format == FMT_SSHORT && components == -1) {
1212         // jhead only supports reading one SSHORT anyway
1213         components = 1;
1214     }
1215     if (format == FMT_UNDEFINED && components == -1) {
1216         // check if this UNDEFINED format is actually ASCII (as it usually is)
1217         // if so, we can calculate the size
1218         if(memcmp((char*)value, ExifAsciiPrefix, sizeof(ExifAsciiPrefix)) == 0) {
1219             components = sizeof(ExifAsciiPrefix) +
1220                          strlen((char*)value + sizeof(ExifAsciiPrefix)) + 1;
1221             if (components & 1) ++components;               // no odd lengths
1222         }
1223     }
1224     Put32u(Buffer+(*DirIndex) + 4, components);         // Components
1225     componentsPosition = Buffer+(*DirIndex) + 4; // components # can change for lists
1226     printf("# components: %ld", components);
1227     if (format == FMT_STRING) {
1228         // short strings can fit right in the long, otherwise have to
1229         // go in the data area
1230         if (components <= 4) {
1231             strcpy(Buffer+(*DirIndex) + 8, (char*)value);
1232         } else {
1233             Put32u(Buffer+(*DirIndex) + 8, (*DataWriteIndex)-8);   // Pointer
1234             printf("copying value %s to %d", (char*)value, (*DataWriteIndex));
1235             strncpy(Buffer+(*DataWriteIndex), (char*)value, components);
1236             (*DataWriteIndex) += components;
1237         }
1238     } else if ((format == FMT_UNDEFINED) &&
1239                (memcmp((char*)value, ExifAsciiPrefix, sizeof(ExifAsciiPrefix)) == 0)) {
1240         // short strings can fit right in the long, otherwise have to
1241         // go in the data area
1242         if (components <= 4) {
1243             memcpy(Buffer+(*DirIndex) + 8, (char*)value, components);
1244         } else {
1245             Put32u(Buffer+(*DirIndex) + 8, (*DataWriteIndex)-8);   // Pointer
1246             printf("copying %s to %d", (char*)value + sizeof(ExifAsciiPrefix), (*DataWriteIndex));
1247             memcpy(Buffer+(*DataWriteIndex), (char*)value, components);
1248             (*DataWriteIndex) += components;
1249         }
1250     } else if (!valueInString) {
1251         Put32u(Buffer+(*DirIndex) + 8, value);   // Value
1252     } else {
1253         Put32u(Buffer+(*DirIndex) + 8, (*DataWriteIndex)-8);   // Pointer
1254         // Usually the separator is ',', but sometimes ':' is used, like
1255         // TAG_GPS_TIMESTAMP.
1256         char* curElement = strtok((char*)value, ",:");
1257         int i;
1258 
1259         // (components == -1) Need to handle lists with unknown length too
1260         for (i = 0; ((i < components) || (components == -1)) && curElement != NULL; i++) {
1261 #ifdef SUPERDEBUG
1262             printf("processing component %s format %s", curElement, formatStr(format));
1263 #endif
1264             // elements are separated by commas
1265             if (format == FMT_URATIONAL) {
1266                 unsigned int numerator;
1267                 unsigned int denominator;
1268                 char* separator = strchr(curElement, '/');
1269                 if (separator) {
1270                     numerator = atoi(curElement);
1271                     denominator = atoi(separator + 1);
1272                 } else {
1273                     double value = atof(curElement);
1274                     ConvertDoubleToURational(value, &numerator, &denominator);
1275                 }
1276                 Put32u(Buffer+(*DataWriteIndex), numerator);
1277                 Put32u(Buffer+(*DataWriteIndex) + 4, denominator);
1278                 (*DataWriteIndex) += 8;
1279             } else if (format == FMT_SRATIONAL) {
1280                 int numerator;
1281                 int denominator;
1282                 char* separator = strchr(curElement, '/');
1283                 if (separator) {
1284                     numerator = atoi(curElement);
1285                     denominator = atoi(separator + 1);
1286                 } else {
1287                     double value = atof(curElement);
1288                     ConvertDoubleToSRational(value, &numerator, &denominator);
1289                 }
1290                 Put32u(Buffer+(*DataWriteIndex), numerator);
1291                 Put32u(Buffer+(*DataWriteIndex) + 4, denominator);
1292                 (*DataWriteIndex) += 8;
1293             } else if ((components == -1) && ((format == FMT_USHORT) || (format == FMT_SSHORT))) {
1294                 // variable components need to go into data write area
1295                 value = atoi(curElement);
1296                 Put16u(Buffer+(*DataWriteIndex), value);
1297                 (*DataWriteIndex) += 4;
1298             } else {
1299                 // TODO: doesn't handle multiple components yet -- if more than one, have to put in data write area.
1300                 value = atoi(curElement);
1301                 Put32u(Buffer+(*DirIndex) + 8, value);   // Value
1302             }
1303             curElement = strtok(NULL, ",:");
1304         }
1305         if (components == -1) Put32u(componentsPosition, i); // update component # for unknowns
1306     }
1307     (*DirIndex) += 12;
1308 }
1309 
1310 #ifdef SUPERDEBUG
formatStr(int format)1311 char* formatStr(int format) {
1312     switch (format) {
1313         case FMT_BYTE: return "FMT_BYTE"; break;
1314         case FMT_STRING: return "FMT_STRING"; break;
1315         case FMT_USHORT: return "FMT_USHORT"; break;
1316         case FMT_ULONG: return "FMT_ULONG"; break;
1317         case FMT_URATIONAL: return "FMT_URATIONAL"; break;
1318         case FMT_SBYTE: return "FMT_SBYTE"; break;
1319         case FMT_UNDEFINED: return "FMT_UNDEFINED"; break;
1320         case FMT_SSHORT: return "FMT_SSHORT"; break;
1321         case FMT_SLONG: return "FMT_SLONG"; break;
1322         case FMT_SRATIONAL: return "FMT_SRATIONAL"; break;
1323         case FMT_SINGLE: return "FMT_SINGLE"; break;
1324         case FMT_DOUBLE: return "FMT_SINGLE"; break;
1325         default: return "UNKNOWN";
1326     }
1327 }
1328 #endif
1329 
1330 //--------------------------------------------------------------------------
1331 // Create minimal exif header - just date and thumbnail pointers,
1332 // so that date and thumbnail may be filled later.
1333 //--------------------------------------------------------------------------
create_EXIF_internal(ExifElement_t * elements,int exifTagCount,int gpsTagCount,int hasDateTimeTag,char * Buffer)1334 static void create_EXIF_internal(ExifElement_t* elements, int exifTagCount, int gpsTagCount, int hasDateTimeTag, char* Buffer)
1335 {
1336     unsigned short NumEntries;
1337     int DataWriteIndex;
1338     int DirIndex;
1339     int DirExifLink = 0;
1340 
1341 #ifdef SUPERDEBUG
1342     ALOGE("create_EXIF %d exif elements, %d gps elements", exifTagCount, gpsTagCount);
1343 #endif
1344 
1345     MotorolaOrder = 0;
1346 
1347     memcpy(Buffer+2, "Exif\0\0II",8);
1348     Put16u(Buffer+10, 0x2a);
1349 
1350     DataWriteIndex = 16;
1351     Put32u(Buffer+12, DataWriteIndex-8); // first IFD offset.  Means start 16 bytes in.
1352 
1353     {
1354         DirIndex = DataWriteIndex;
1355         NumEntries = 1 + exifTagCount;  // the extra is the thumbnail
1356         if (gpsTagCount) {
1357             ++NumEntries;       // allow for the GPS info tag
1358         }
1359         if (!hasDateTimeTag) {
1360             // We have to write extra date time tag. The entry number should be
1361             // adjusted.
1362             ++NumEntries;
1363         }
1364         DataWriteIndex += 2 + NumEntries*12 + 4;
1365 
1366         Put16u(Buffer+DirIndex, NumEntries); // Number of entries
1367         DirIndex += 2;
1368 
1369         // Entries go here...
1370         if (!hasDateTimeTag) {
1371             // Date/time entry
1372             char* dateTime = NULL;
1373             char dateBuf[20];
1374             if (ImageInfo.numDateTimeTags) {
1375                 // If we had a pre-existing exif header, use time from that.
1376                 dateTime = ImageInfo.DateTime;
1377             } else {
1378                 // Oterwise, use the file's timestamp.
1379                 FileTimeAsString(dateBuf);
1380                 dateTime = dateBuf;
1381             }
1382             writeExifTagAndData(TAG_DATETIME,
1383                                 FMT_STRING,
1384                                 20,
1385                                 (long)(char*)dateBuf,
1386                                 FALSE,
1387                                 Buffer,
1388                                 &DirIndex,
1389                                 &DataWriteIndex);
1390 
1391         }
1392         if (exifTagCount > 0) {
1393             int i;
1394             for (i = 0; i < exifTagCount + gpsTagCount; i++) {
1395                 if (elements[i].GpsTag) {
1396                     continue;
1397                 }
1398                 const TagTable_t* entry = TagToTagTableEntry(elements[i].Tag);
1399                 if (entry == NULL) {
1400                     continue;
1401                 }
1402 #ifdef SUPERDEBUG
1403                 ALOGE("create_EXIF saving tag %x value \"%s\"",elements[i].Tag, elements[i].Value);
1404 #endif
1405                 writeExifTagAndData(elements[i].Tag,
1406                                     entry->Format,
1407                                     entry->DataLength,
1408                                     (long)elements[i].Value,
1409                                     TRUE,
1410                                     Buffer,
1411                                     &DirIndex,
1412                                     &DataWriteIndex);
1413             }
1414 
1415             if (gpsTagCount) {
1416                 // Link to gps dir entry
1417                 writeExifTagAndData(TAG_GPSINFO,
1418                                     FMT_ULONG,
1419                                     1,
1420                                     DataWriteIndex-8,
1421                                     FALSE,
1422                                     Buffer,
1423                                     &DirIndex,
1424                                     &DataWriteIndex);
1425             }
1426 
1427             // Link to exif dir entry
1428             int exifDirPtr = DataWriteIndex-8;
1429             if (gpsTagCount) {
1430                 exifDirPtr += 2 + gpsTagCount*12 + 4;
1431             }
1432             DirExifLink = DirIndex;
1433             writeExifTagAndData(TAG_EXIF_OFFSET,
1434                                 FMT_ULONG,
1435                                 1,
1436                                 exifDirPtr,
1437                                 FALSE,
1438                                 Buffer,
1439                                 &DirIndex,
1440                                 &DataWriteIndex);
1441         }
1442 
1443         // End of directory - contains optional link to continued directory.
1444         Put32u(Buffer+DirIndex, 0);
1445         printf("Ending Exif section DirIndex = %d DataWriteIndex %d", DirIndex, DataWriteIndex);
1446     }
1447 
1448 
1449     // GPS Section
1450     if (gpsTagCount) {
1451         DirIndex = DataWriteIndex;
1452         printf("Starting GPS section DirIndex = %d", DirIndex);
1453         NumEntries = gpsTagCount;
1454         DataWriteIndex += 2 + NumEntries*12 + 4;
1455 
1456         Put16u(Buffer+DirIndex, NumEntries); // Number of entries
1457         DirIndex += 2;
1458         {
1459             int i;
1460             for (i = 0; i < exifTagCount + gpsTagCount; i++) {
1461                 if (!elements[i].GpsTag) {
1462                     continue;
1463                 }
1464                 const TagTable_t* entry = GpsTagToTagTableEntry(elements[i].Tag);
1465                 if (entry == NULL) {
1466                     continue;
1467                 }
1468 #ifdef SUPERDEBUG
1469                 ALOGE("create_EXIF saving GPS tag %x value \"%s\"",elements[i].Tag, elements[i].Value);
1470 #endif
1471                 writeExifTagAndData(elements[i].Tag,
1472                                     entry->Format,
1473                                     entry->DataLength,
1474                                     (long)elements[i].Value,
1475                                     TRUE,
1476                                     Buffer,
1477                                     &DirIndex,
1478                                     &DataWriteIndex);
1479             }
1480         }
1481 
1482         // End of directory - contains optional link to continued directory.
1483         Put32u(Buffer+DirIndex, 0);
1484         printf("Ending GPS section DirIndex = %d DataWriteIndex %d", DirIndex, DataWriteIndex);
1485     }
1486 
1487     {
1488         // Overwriting TAG_EXIF_OFFSET which links to this directory
1489         Put32u(Buffer+DirExifLink+8, DataWriteIndex-8);
1490 
1491         printf("Starting Thumbnail section DirIndex = %d", DirIndex);
1492         DirIndex = DataWriteIndex;
1493         NumEntries = 2;
1494         DataWriteIndex += 2 + NumEntries*12 + 4;
1495 
1496         Put16u(Buffer+DirIndex, NumEntries); // Number of entries
1497         DirIndex += 2;
1498         {
1499             // Link to exif dir entry
1500             writeExifTagAndData(TAG_THUMBNAIL_OFFSET,
1501                                 FMT_ULONG,
1502                                 1,
1503                                 DataWriteIndex-8,
1504                                 FALSE,
1505                                 Buffer,
1506                                 &DirIndex,
1507                                 &DataWriteIndex);
1508         }
1509 
1510         {
1511             // Link to exif dir entry
1512             writeExifTagAndData(TAG_THUMBNAIL_LENGTH,
1513                                 FMT_ULONG,
1514                                 1,
1515                                 0,
1516                                 FALSE,
1517                                 Buffer,
1518                                 &DirIndex,
1519                                 &DataWriteIndex);
1520         }
1521 
1522         // End of directory - contains optional link to continued directory.
1523         Put32u(Buffer+DirIndex, 0);
1524         printf("Ending Thumbnail section DirIndex = %d DataWriteIndex %d", DirIndex, DataWriteIndex);
1525     }
1526 
1527 
1528     Buffer[0] = (unsigned char)(DataWriteIndex >> 8);
1529     Buffer[1] = (unsigned char)DataWriteIndex;
1530 
1531     // Remove old exif section, if there was one.
1532     RemoveSectionType(M_EXIF);
1533 
1534     {
1535         // Sections need malloced buffers, so do that now, especially because
1536         // we now know how big it needs to be allocated.
1537         unsigned char * NewBuf = malloc(DataWriteIndex);
1538         if (NewBuf == NULL){
1539             ErrFatal("Could not allocate memory");
1540         }
1541         memcpy(NewBuf, Buffer, DataWriteIndex);
1542 
1543         CreateSection(M_EXIF, NewBuf, DataWriteIndex);
1544 
1545         // Re-parse new exif section, now that its in place
1546         // otherwise, we risk touching data that has already been freed.
1547         process_EXIF(NewBuf, DataWriteIndex);
1548     }
1549 }
1550 
create_EXIF(ExifElement_t * elements,int exifTagCount,int gpsTagCount,int hasDateTimeTag)1551 void create_EXIF(ExifElement_t* elements, int exifTagCount, int gpsTagCount, int hasDateTimeTag)
1552 {
1553     // It is hard to calculate exact necessary size for editing the exif
1554     // header dynamically, so we are using the maximum size of EXIF, 64K
1555     const int EXIF_MAX_SIZE = 1024*64;
1556     char* Buffer = malloc(EXIF_MAX_SIZE);
1557 
1558     if (Buffer != NULL) {
1559         create_EXIF_internal(elements, exifTagCount, gpsTagCount, hasDateTimeTag, Buffer);
1560         free(Buffer);
1561     } else {
1562         ErrFatal("Could not allocate memory");
1563     }
1564 }
1565 
1566 //--------------------------------------------------------------------------
1567 // Cler the rotation tag in the exif header to 1.
1568 //--------------------------------------------------------------------------
ClearOrientation(void)1569 const char * ClearOrientation(void)
1570 {
1571     int a;
1572     if (NumOrientations == 0) return NULL;
1573 
1574     for (a=0;a<NumOrientations;a++){
1575         switch(OrientationNumFormat[a]){
1576             case FMT_SBYTE:
1577             case FMT_BYTE:
1578                 *(uchar *)(OrientationPtr[a]) = 1;
1579                 break;
1580 
1581             case FMT_USHORT:
1582                 Put16u(OrientationPtr[a], 1);
1583                 break;
1584 
1585             case FMT_ULONG:
1586             case FMT_SLONG:
1587                 memset(OrientationPtr, 0, 4);
1588                 // Can't be bothered to write  generic Put32 if I only use it once.
1589                 if (MotorolaOrder){
1590                     ((uchar *)OrientationPtr[a])[3] = 1;
1591                 }else{
1592                     ((uchar *)OrientationPtr[a])[0] = 1;
1593                 }
1594                 break;
1595 
1596             default:
1597                 return NULL;
1598         }
1599     }
1600 
1601     return OrientTab[ImageInfo.Orientation];
1602 }
1603 
1604 
1605 
1606 //--------------------------------------------------------------------------
1607 // Remove thumbnail out of the exif image.
1608 //--------------------------------------------------------------------------
RemoveThumbnail(unsigned char * ExifSection)1609 int RemoveThumbnail(unsigned char * ExifSection)
1610 {
1611     if (!DirWithThumbnailPtrs ||
1612         ImageInfo.ThumbnailOffset == 0 ||
1613         ImageInfo.ThumbnailSize == 0){
1614         // No thumbnail, or already deleted it.
1615         return 0;
1616     }
1617     if (ImageInfo.ThumbnailAtEnd == FALSE){
1618         ErrNonfatal("Thumbnail is not at end of header, can't chop it off", 0, 0);
1619         return 0;
1620     }
1621 
1622     {
1623         int de;
1624         int NumDirEntries;
1625         NumDirEntries = Get16u(DirWithThumbnailPtrs);
1626 
1627         for (de=0;de<NumDirEntries;de++){
1628             int Tag;
1629             unsigned char * DirEntry;
1630             DirEntry = DIR_ENTRY_ADDR(DirWithThumbnailPtrs, de);
1631             Tag = Get16u(DirEntry);
1632             if (Tag == TAG_THUMBNAIL_LENGTH){
1633                 // Set length to zero.
1634                 if (Get16u(DirEntry+2) != FMT_ULONG){
1635                     // non standard format encoding.  Can't do it.
1636                     ErrNonfatal("Can't remove thumbnail", 0, 0);
1637                     return 0;
1638                 }
1639                 Put32u(DirEntry+8, 0);
1640             }
1641         }
1642     }
1643 
1644     // This is how far the non thumbnail data went.
1645     return ImageInfo.ThumbnailOffset+8;
1646 
1647 }
1648 
1649 
1650 //--------------------------------------------------------------------------
1651 // Convert exif time to Unix time structure
1652 //--------------------------------------------------------------------------
Exif2tm(struct tm * timeptr,char * ExifTime)1653 int Exif2tm(struct tm * timeptr, char * ExifTime)
1654 {
1655     int a;
1656 
1657     timeptr->tm_wday = -1;
1658 
1659     // Check for format: YYYY:MM:DD HH:MM:SS format.
1660     // Date and time normally separated by a space, but also seen a ':' there, so
1661     // skip the middle space with '%*c' so it can be any character.
1662     a = sscanf(ExifTime, "%d%*c%d%*c%d%*c%d:%d:%d",
1663             &timeptr->tm_year, &timeptr->tm_mon, &timeptr->tm_mday,
1664             &timeptr->tm_hour, &timeptr->tm_min, &timeptr->tm_sec);
1665 
1666 
1667     if (a == 6){
1668         timeptr->tm_isdst = -1;
1669         timeptr->tm_mon -= 1;      // Adjust for unix zero-based months
1670         timeptr->tm_year -= 1900;  // Adjust for year starting at 1900
1671         return TRUE; // worked.
1672     }
1673 
1674     return FALSE; // Wasn't in Exif date format.
1675 }
1676 
1677 
1678 //--------------------------------------------------------------------------
1679 // Show the collected image info, displaying camera F-stop and shutter speed
1680 // in a consistent and legible fashion.
1681 //--------------------------------------------------------------------------
ShowImageInfo(int ShowFileInfo)1682 void ShowImageInfo(int ShowFileInfo)
1683 {
1684     if (ShowFileInfo){
1685         printf("File name    : %s\n",ImageInfo.FileName);
1686         printf("File size    : %d bytes\n",ImageInfo.FileSize);
1687 
1688         {
1689             char Temp[20];
1690             FileTimeAsString(Temp);
1691             printf("File date    : %s\n",Temp);
1692         }
1693     }
1694 
1695     if (ImageInfo.CameraMake[0]){
1696         printf("Camera make  : %s\n",ImageInfo.CameraMake);
1697         printf("Camera model : %s\n",ImageInfo.CameraModel);
1698     }
1699     if (ImageInfo.DateTime[0]){
1700         printf("Date/Time    : %s\n",ImageInfo.DateTime);
1701     }
1702     printf("Resolution   : %d x %d\n",ImageInfo.Width, ImageInfo.Height);
1703 
1704     if (ImageInfo.Orientation > 1){
1705         // Only print orientation if one was supplied, and if its not 1 (normal orientation)
1706         printf("Orientation  : %s\n", OrientTab[ImageInfo.Orientation]);
1707     }
1708 
1709     if (ImageInfo.IsColor == 0){
1710         printf("Color/bw     : Black and white\n");
1711     }
1712 
1713     if (ImageInfo.FlashUsed >= 0){
1714         if (ImageInfo.FlashUsed & 1){
1715             printf("Flash used   : Yes");
1716             switch (ImageInfo.FlashUsed){
1717 	            case 0x5: printf(" (Strobe light not detected)"); break;
1718 	            case 0x7: printf(" (Strobe light detected) "); break;
1719 	            case 0x9: printf(" (manual)"); break;
1720 	            case 0xd: printf(" (manual, return light not detected)"); break;
1721 	            case 0xf: printf(" (manual, return light  detected)"); break;
1722 	            case 0x19:printf(" (auto)"); break;
1723 	            case 0x1d:printf(" (auto, return light not detected)"); break;
1724 	            case 0x1f:printf(" (auto, return light detected)"); break;
1725 	            case 0x41:printf(" (red eye reduction mode)"); break;
1726 	            case 0x45:printf(" (red eye reduction mode return light not detected)"); break;
1727 	            case 0x47:printf(" (red eye reduction mode return light  detected)"); break;
1728 	            case 0x49:printf(" (manual, red eye reduction mode)"); break;
1729 	            case 0x4d:printf(" (manual, red eye reduction mode, return light not detected)"); break;
1730 	            case 0x4f:printf(" (red eye reduction mode, return light detected)"); break;
1731 	            case 0x59:printf(" (auto, red eye reduction mode)"); break;
1732 	            case 0x5d:printf(" (auto, red eye reduction mode, return light not detected)"); break;
1733 	            case 0x5f:printf(" (auto, red eye reduction mode, return light detected)"); break;
1734             }
1735         }else{
1736             printf("Flash used   : No");
1737             switch (ImageInfo.FlashUsed){
1738 	            case 0x18:printf(" (auto)"); break;
1739             }
1740         }
1741         printf("\n");
1742     }
1743 
1744 
1745     if (ImageInfo.FocalLength.num != 0 && ImageInfo.FocalLength.denom != 0) {
1746         printf("Focal length : %4.1fmm",(double)ImageInfo.FocalLength.num / ImageInfo.FocalLength.denom);
1747         if (ImageInfo.FocalLength35mmEquiv){
1748             printf("  (35mm equivalent: %dmm)", ImageInfo.FocalLength35mmEquiv);
1749         }
1750         printf("\n");
1751     }
1752 
1753     if (ImageInfo.DigitalZoomRatio > 1){
1754         // Digital zoom used.  Shame on you!
1755         printf("Digital Zoom : %1.3fx\n", (double)ImageInfo.DigitalZoomRatio);
1756     }
1757 
1758     if (ImageInfo.CCDWidth){
1759         printf("CCD width    : %4.2fmm\n",(double)ImageInfo.CCDWidth);
1760     }
1761 
1762     if (ImageInfo.ExposureTime){
1763         if (ImageInfo.ExposureTime < 0.010){
1764             printf("Exposure time: %6.4f s ",(double)ImageInfo.ExposureTime);
1765         }else{
1766             printf("Exposure time: %5.3f s ",(double)ImageInfo.ExposureTime);
1767         }
1768         if (ImageInfo.ExposureTime <= 0.5){
1769             printf(" (1/%d)",(int)(0.5 + 1/ImageInfo.ExposureTime));
1770         }
1771         printf("\n");
1772     }
1773     if (ImageInfo.ApertureFNumber){
1774         printf("Aperture     : f/%3.1f\n",(double)ImageInfo.ApertureFNumber);
1775     }
1776     if (ImageInfo.Distance){
1777         if (ImageInfo.Distance < 0){
1778             printf("Focus dist.  : Infinite\n");
1779         }else{
1780             printf("Focus dist.  : %4.2fm\n",(double)ImageInfo.Distance);
1781         }
1782     }
1783 
1784     if (ImageInfo.ISOequivalent){
1785         printf("ISO equiv.   : %2d\n",(int)ImageInfo.ISOequivalent);
1786     }
1787 
1788     if (ImageInfo.ExposureBias){
1789         // If exposure bias was specified, but set to zero, presumably its no bias at all,
1790         // so only show it if its nonzero.
1791         printf("Exposure bias: %4.2f\n",(double)ImageInfo.ExposureBias);
1792     }
1793 
1794     switch(ImageInfo.Whitebalance) {
1795         case 1:
1796             printf("Whitebalance : Manual\n");
1797             break;
1798         case 0:
1799             printf("Whitebalance : Auto\n");
1800             break;
1801     }
1802 
1803     //Quercus: 17-1-2004 Added LightSource, some cams return this, whitebalance or both
1804     switch(ImageInfo.LightSource) {
1805         case 1:
1806             printf("Light Source : Daylight\n");
1807             break;
1808         case 2:
1809             printf("Light Source : Fluorescent\n");
1810             break;
1811         case 3:
1812             printf("Light Source : Incandescent\n");
1813             break;
1814         case 4:
1815             printf("Light Source : Flash\n");
1816             break;
1817         case 9:
1818             printf("Light Source : Fine weather\n");
1819             break;
1820         case 11:
1821             printf("Light Source : Shade\n");
1822             break;
1823         default:; //Quercus: 17-1-2004 There are many more modes for this, check Exif2.2 specs
1824             // If it just says 'unknown' or we don't know it, then
1825             // don't bother showing it - it doesn't add any useful information.
1826     }
1827 
1828     if (ImageInfo.MeteringMode){ // 05-jan-2001 vcs
1829         switch(ImageInfo.MeteringMode) {
1830         case 2:
1831             printf("Metering Mode: center weight\n");
1832             break;
1833         case 3:
1834             printf("Metering Mode: spot\n");
1835             break;
1836         case 5:
1837             printf("Metering Mode: matrix\n");
1838             break;
1839         }
1840     }
1841 
1842     if (ImageInfo.ExposureProgram){ // 05-jan-2001 vcs
1843         switch(ImageInfo.ExposureProgram) {
1844         case 1:
1845             printf("Exposure     : Manual\n");
1846             break;
1847         case 2:
1848             printf("Exposure     : program (auto)\n");
1849             break;
1850         case 3:
1851             printf("Exposure     : aperture priority (semi-auto)\n");
1852             break;
1853         case 4:
1854             printf("Exposure     : shutter priority (semi-auto)\n");
1855             break;
1856         case 5:
1857             printf("Exposure     : Creative Program (based towards depth of field)\n");
1858             break;
1859         case 6:
1860             printf("Exposure     : Action program (based towards fast shutter speed)\n");
1861             break;
1862         case 7:
1863             printf("Exposure     : Portrait Mode\n");
1864             break;
1865         case 8:
1866             printf("Exposure     : LandscapeMode \n");
1867             break;
1868         default:
1869             break;
1870         }
1871     }
1872     switch(ImageInfo.ExposureMode){
1873         case 0: // Automatic (not worth cluttering up output for)
1874             break;
1875         case 1: printf("Exposure Mode: Manual\n");
1876             break;
1877         case 2: printf("Exposure Mode: Auto bracketing\n");
1878             break;
1879     }
1880 
1881     if (ImageInfo.DistanceRange) {
1882         printf("Focus range  : ");
1883         switch(ImageInfo.DistanceRange) {
1884             case 1:
1885                 printf("macro");
1886                 break;
1887             case 2:
1888                 printf("close");
1889                 break;
1890             case 3:
1891                 printf("distant");
1892                 break;
1893         }
1894         printf("\n");
1895     }
1896 
1897 
1898 
1899     if (ImageInfo.Process != M_SOF0){
1900         // don't show it if its the plain old boring 'baseline' process, but do
1901         // show it if its something else, like 'progressive' (used on web sometimes)
1902         int a;
1903         for (a=0;;a++){
1904             if (a >= (int)PROCESS_TABLE_SIZE){
1905                 // ran off the end of the table.
1906                 printf("Jpeg process : Unknown\n");
1907                 break;
1908             }
1909             if (ProcessTable[a].Tag == ImageInfo.Process){
1910                 printf("Jpeg process : %s\n",ProcessTable[a].Desc);
1911                 break;
1912             }
1913         }
1914     }
1915 
1916     if (ImageInfo.GpsInfoPresent){
1917         printf("GPS Latitude : %s\n",ImageInfo.GpsLat);
1918         printf("GPS Longitude: %s\n",ImageInfo.GpsLong);
1919         if (ImageInfo.GpsAlt[0]) printf("GPS Altitude : %s\n",ImageInfo.GpsAlt);
1920     }
1921 
1922     // Print the comment. Print 'Comment:' for each new line of comment.
1923     if (ImageInfo.Comments[0]){
1924         int a,c;
1925         printf("Comment      : ");
1926         if (!ImageInfo.CommentWidchars){
1927             for (a=0;a<MAX_COMMENT_SIZE;a++){
1928                 c = ImageInfo.Comments[a];
1929                 if (c == '\0') break;
1930                 if (c == '\n'){
1931                     // Do not start a new line if the string ends with a carriage return.
1932                     if (ImageInfo.Comments[a+1] != '\0'){
1933                         printf("\nComment      : ");
1934                     }else{
1935                         printf("\n");
1936                     }
1937                 }else{
1938                     putchar(c);
1939                 }
1940             }
1941             printf("\n");
1942         }else{
1943             printf("%.*ls\n", ImageInfo.CommentWidchars, (wchar_t *)ImageInfo.Comments);
1944         }
1945     }
1946     if (ImageInfo.ThumbnailOffset){
1947         printf("Map: %05d-%05d: Thumbnail\n",ImageInfo.ThumbnailOffset, ImageInfo.ThumbnailOffset+ImageInfo.ThumbnailSize);
1948     } else {
1949         printf("NO thumbnail");
1950     }
1951 }
1952 
1953 
1954 //--------------------------------------------------------------------------
1955 // Summarize highlights of image info on one line (suitable for grep-ing)
1956 //--------------------------------------------------------------------------
ShowConciseImageInfo(void)1957 void ShowConciseImageInfo(void)
1958 {
1959     printf("\"%s\"",ImageInfo.FileName);
1960 
1961     printf(" %dx%d",ImageInfo.Width, ImageInfo.Height);
1962 
1963     if (ImageInfo.ExposureTime){
1964         if (ImageInfo.ExposureTime <= 0.5){
1965             printf(" (1/%d)",(int)(0.5 + 1/ImageInfo.ExposureTime));
1966         }else{
1967             printf(" (%1.1f)",ImageInfo.ExposureTime);
1968         }
1969     }
1970 
1971     if (ImageInfo.ApertureFNumber){
1972         printf(" f/%3.1f",(double)ImageInfo.ApertureFNumber);
1973     }
1974 
1975     if (ImageInfo.FocalLength35mmEquiv){
1976         printf(" f(35)=%dmm",ImageInfo.FocalLength35mmEquiv);
1977     }
1978 
1979     if (ImageInfo.FlashUsed >= 0 && ImageInfo.FlashUsed & 1){
1980         printf(" (flash)");
1981     }
1982 
1983     if (ImageInfo.IsColor == 0){
1984         printf(" (bw)");
1985     }
1986 
1987     printf("\n");
1988 }
1989