Home | History | Annotate | Download | only in jhead
      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 
    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 
    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 //--------------------------------------------------------------------------
    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 //--------------------------------------------------------------------------
    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 //--------------------------------------------------------------------------
    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 //--------------------------------------------------------------------------
    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 //--------------------------------------------------------------------------
    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 //--------------------------------------------------------------------------
    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 //--------------------------------------------------------------------------
    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 //--------------------------------------------------------------------------
    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 
    517 static void ConvertDoubleToURational(double value, unsigned int *numerator,
    518                                      unsigned int *denominator) {
    519     float2urat(value, 0xFFFFFFFFU, numerator, denominator);
    520 }
    521 
    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 //--------------------------------------------------------------------------
    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_DATETIME_ORIGINAL:
    715                 // If we get a DATETIME_ORIGINAL, we use that one.
    716                 strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
    717                 // Fallthru...
    718 
    719             case TAG_DATETIME_DIGITIZED:
    720             case TAG_DATETIME:
    721                 if (!isdigit(ImageInfo.DateTime[0])){
    722                     // If we don't already have a DATETIME_ORIGINAL, use whatever
    723                     // time fields we may have.
    724                     strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
    725                 }
    726 
    727                 if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
    728                     ErrNonfatal("More than %d date fields!  This is nuts", MAX_DATE_COPIES, 0);
    729                     break;
    730                 }
    731                 ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
    732                     (char *)ValuePtr - (char *)OffsetBase;
    733                 break;
    734 
    735             case TAG_WINXP_COMMENT:
    736                 if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
    737                     // Already have a comment (probably windows comment), skip this one.
    738                     if (ShowTags) printf("Windows XP commend and other comment in header\n");
    739                     break; // Already have a windows comment, skip this one.
    740                 }
    741 
    742                 if (ByteCount > 1){
    743                     if (ByteCount > MAX_COMMENT_SIZE) ByteCount = MAX_COMMENT_SIZE;
    744                     memcpy(ImageInfo.Comments, ValuePtr, ByteCount);
    745                     ImageInfo.CommentWidchars = ByteCount/2;
    746                 }
    747                 break;
    748 
    749             case TAG_USERCOMMENT:
    750                 if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
    751                     // Already have a comment (probably windows comment), skip this one.
    752                     if (ShowTags) printf("Multiple comments in exif header\n");
    753                     break; // Already have a windows comment, skip this one.
    754                 }
    755 
    756                 // Comment is often padded with trailing spaces.  Remove these first.
    757                 for (a=ByteCount;;){
    758                     a--;
    759                     if ((ValuePtr)[a] == ' '){
    760                         (ValuePtr)[a] = '\0';
    761                     }else{
    762                         break;
    763                     }
    764                     if (a == 0) break;
    765                 }
    766 
    767                 // Copy the comment
    768                 {
    769                     // We want to set copied comment length (msize) to be the
    770                     // minimum of:
    771                     // (1) The space still available in Exif
    772                     // (2) The given comment length (ByteCount)
    773                     // (3) MAX_COMMENT_SIZE - 1
    774                     int msiz = ExifLength - (ValuePtr-OffsetBase);
    775                     if (msiz > ByteCount) msiz = ByteCount;
    776                     if (msiz > MAX_COMMENT_SIZE - 1) msiz = MAX_COMMENT_SIZE - 1;
    777                     if (msiz > 5 && memcmp(ValuePtr, "ASCII", 5) == 0) {
    778                         for (a = 5; a < 10 && a < msiz; a++) {
    779                             int c = (ValuePtr)[a];
    780                             if (c != '\0' && c != ' ') {
    781                                 strncpy(ImageInfo.Comments,
    782                                         (char *)ValuePtr + a, msiz - a);
    783                                 break;
    784                             }
    785                         }
    786                     } else {
    787                         strncpy(ImageInfo.Comments, (char *)ValuePtr, msiz);
    788                     }
    789                 }
    790                 break;
    791 
    792             case TAG_FNUMBER:
    793                 // Simplest way of expressing aperture, so I trust it the most.
    794                 // (overwrite previously computd value if there is one)
    795                 ImageInfo.ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format);
    796                 break;
    797 
    798             case TAG_APERTURE:
    799             case TAG_MAXAPERTURE:
    800                 // More relevant info always comes earlier, so only use this field if we don't
    801                 // have appropriate aperture information yet.
    802                 if (ImageInfo.ApertureFNumber == 0){
    803                     ImageInfo.ApertureFNumber
    804                         = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5);
    805                 }
    806                 break;
    807 
    808             case TAG_FOCALLENGTH:
    809                 // Nice digital cameras actually save the focal length as a function
    810                 // of how farthey are zoomed in.
    811                 ImageInfo.FocalLength.num = Get32u(ValuePtr);
    812                 ImageInfo.FocalLength.denom = Get32u(4+(char *)ValuePtr);
    813                 break;
    814 
    815             case TAG_SUBJECT_DISTANCE:
    816                 // Inidcates the distacne the autofocus camera is focused to.
    817                 // Tends to be less accurate as distance increases.
    818                 ImageInfo.Distance = (float)ConvertAnyFormat(ValuePtr, Format);
    819                 break;
    820 
    821             case TAG_EXPOSURETIME:
    822                 // Simplest way of expressing exposure time, so I trust it most.
    823                 // (overwrite previously computd value if there is one)
    824                 ImageInfo.ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format);
    825                 break;
    826 
    827             case TAG_SHUTTERSPEED:
    828                 // More complicated way of expressing exposure time, so only use
    829                 // this value if we don't already have it from somewhere else.
    830                 if (ImageInfo.ExposureTime == 0){
    831                     ImageInfo.ExposureTime
    832                         = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2)));
    833                 }
    834                 break;
    835 
    836 
    837             case TAG_FLASH:
    838                 ImageInfo.FlashUsed=(int)ConvertAnyFormat(ValuePtr, Format);
    839                 break;
    840 
    841             case TAG_ORIENTATION:
    842                 if (NumOrientations >= 2){
    843                     // Can have another orientation tag for the thumbnail, but if there's
    844                     // a third one, things are stringae.
    845                     ErrNonfatal("More than two orientation tags!",0,0);
    846                     break;
    847                 }
    848                 OrientationPtr[NumOrientations] = ValuePtr;
    849                 OrientationNumFormat[NumOrientations] = Format;
    850                 if (NumOrientations == 0){
    851                     ImageInfo.Orientation = (int)ConvertAnyFormat(ValuePtr, Format);
    852                 }
    853                 if (ImageInfo.Orientation < 0 || ImageInfo.Orientation > 8){
    854                     ErrNonfatal("Undefined rotation value %d", ImageInfo.Orientation, 0);
    855                     ImageInfo.Orientation = 0;
    856                 }
    857                 NumOrientations += 1;
    858                 break;
    859 
    860             case TAG_EXIF_IMAGELENGTH:
    861             case TAG_EXIF_IMAGEWIDTH:
    862                 // Use largest of height and width to deal with images that have been
    863                 // rotated to portrait format.
    864                 a = (int)ConvertAnyFormat(ValuePtr, Format);
    865                 if (ExifImageWidth < a) ExifImageWidth = a;
    866                 break;
    867 
    868             case TAG_FOCAL_PLANE_XRES:
    869                 FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format);
    870                 break;
    871 
    872             case TAG_FOCAL_PLANE_UNITS:
    873                 switch((int)ConvertAnyFormat(ValuePtr, Format)){
    874                     case 1: FocalplaneUnits = 25.4; break; // inch
    875                     case 2:
    876                         // According to the information I was using, 2 means meters.
    877                         // But looking at the Cannon powershot's files, inches is the only
    878                         // sensible value.
    879                         FocalplaneUnits = 25.4;
    880                         break;
    881 
    882                     case 3: FocalplaneUnits = 10;   break;  // centimeter
    883                     case 4: FocalplaneUnits = 1;    break;  // millimeter
    884                     case 5: FocalplaneUnits = .001; break;  // micrometer
    885                 }
    886                 break;
    887 
    888             case TAG_EXPOSURE_BIAS:
    889                 ImageInfo.ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format);
    890                 break;
    891 
    892             case TAG_WHITEBALANCE:
    893                 ImageInfo.Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format);
    894                 break;
    895 
    896             case TAG_LIGHT_SOURCE:
    897                 ImageInfo.LightSource = (int)ConvertAnyFormat(ValuePtr, Format);
    898                 break;
    899 
    900             case TAG_METERING_MODE:
    901                 ImageInfo.MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format);
    902                 break;
    903 
    904             case TAG_EXPOSURE_PROGRAM:
    905                 ImageInfo.ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format);
    906                 break;
    907 
    908             case TAG_EXPOSURE_INDEX:
    909                 if (ImageInfo.ISOequivalent == 0){
    910                     // Exposure index and ISO equivalent are often used interchangeably,
    911                     // so we will do the same in jhead.
    912                     // http://photography.about.com/library/glossary/bldef_ei.htm
    913                     ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
    914                 }
    915                 break;
    916 
    917             case TAG_EXPOSURE_MODE:
    918                 ImageInfo.ExposureMode = (int)ConvertAnyFormat(ValuePtr, Format);
    919                 break;
    920 
    921             case TAG_ISO_EQUIVALENT:
    922                 ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
    923                 if ( ImageInfo.ISOequivalent < 50 ){
    924                     // Fixes strange encoding on some older digicams.
    925                     ImageInfo.ISOequivalent *= 200;
    926                 }
    927                 break;
    928 
    929             case TAG_DIGITALZOOMRATIO:
    930                 ImageInfo.DigitalZoomRatio = (float)ConvertAnyFormat(ValuePtr, Format);
    931                 break;
    932 
    933             case TAG_THUMBNAIL_OFFSET:
    934                 ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format);
    935                 DirWithThumbnailPtrs = DirStart;
    936                 break;
    937 
    938             case TAG_THUMBNAIL_LENGTH:
    939                 ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format);
    940                 ImageInfo.ThumbnailSizeOffset = ValuePtr-OffsetBase;
    941                 break;
    942 
    943             case TAG_EXIF_OFFSET:
    944                 if (ShowTags) printf("%s    Exif Dir:",IndentString);
    945 
    946             case TAG_INTEROP_OFFSET:
    947                 if (Tag == TAG_INTEROP_OFFSET && ShowTags) printf("%s    Interop Dir:",IndentString);
    948                 {
    949                     unsigned char * SubdirStart;
    950                     SubdirStart = OffsetBase + Get32u(ValuePtr);
    951                     if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
    952                         ErrNonfatal("Illegal exif or interop ofset directory link",0,0);
    953                     }else{
    954                         ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
    955                     }
    956                     continue;
    957                 }
    958                 break;
    959 
    960             case TAG_GPSINFO:
    961                 if (ShowTags) printf("%s    GPS info dir:",IndentString);
    962                 {
    963                     unsigned char * SubdirStart;
    964                     SubdirStart = OffsetBase + Get32u(ValuePtr);
    965                     if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
    966                         ErrNonfatal("Illegal GPS directory link",0,0);
    967                     }else{
    968                         ProcessGpsInfo(SubdirStart, ByteCount, OffsetBase, ExifLength);
    969                     }
    970                     continue;
    971                 }
    972                 break;
    973 
    974             case TAG_FOCALLENGTH_35MM:
    975                 // The focal length equivalent 35 mm is a 2.2 tag (defined as of April 2002)
    976                 // if its present, use it to compute equivalent focal length instead of
    977                 // computing it from sensor geometry and actual focal length.
    978                 ImageInfo.FocalLength35mmEquiv = (unsigned)ConvertAnyFormat(ValuePtr, Format);
    979                 break;
    980 
    981             case TAG_DISTANCE_RANGE:
    982                 // Three possible standard values:
    983                 //   1 = macro, 2 = close, 3 = distant
    984                 ImageInfo.DistanceRange = (int)ConvertAnyFormat(ValuePtr, Format);
    985                 break;
    986         }
    987     }
    988 
    989 
    990     {
    991         // In addition to linking to subdirectories via exif tags,
    992         // there's also a potential link to another directory at the end of each
    993         // directory.  this has got to be the result of a committee!
    994         unsigned char * SubdirStart;
    995         unsigned Offset;
    996 
    997         if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){
    998             printf("DirStart %d offset from dirstart %d", (int)DirStart, 2+12*NumDirEntries);
    999             Offset = Get32u(DirStart+2+12*NumDirEntries);
   1000             if (Offset){
   1001                 SubdirStart = OffsetBase + Offset;
   1002                 if (SubdirStart > OffsetBase+ExifLength || SubdirStart < OffsetBase){
   1003                     printf("SubdirStart %d OffsetBase %d ExifLength %d Offset %d",
   1004                         (int)SubdirStart, (int)OffsetBase, ExifLength, Offset);
   1005                     if (SubdirStart > OffsetBase && SubdirStart < OffsetBase+ExifLength+20){
   1006                         // Jhead 1.3 or earlier would crop the whole directory!
   1007                         // As Jhead produces this form of format incorrectness,
   1008                         // I'll just let it pass silently
   1009                         if (ShowTags) printf("Thumbnail removed with Jhead 1.3 or earlier\n");
   1010                     }else{
   1011                         ErrNonfatal("Illegal subdirectory link",0,0);
   1012                     }
   1013                 }else{
   1014                     if (SubdirStart <= OffsetBase+ExifLength){
   1015                         if (ShowTags) printf("%s    Continued directory ",IndentString);
   1016                         ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
   1017                     }
   1018                 }
   1019                 if (Offset > ImageInfo.LargestExifOffset){
   1020                     ImageInfo.LargestExifOffset = Offset;
   1021                 }
   1022             }
   1023         }else{
   1024             // The exif header ends before the last next directory pointer.
   1025         }
   1026     }
   1027 
   1028     if (ThumbnailOffset){
   1029         ImageInfo.ThumbnailAtEnd = FALSE;
   1030 
   1031         if (DumpExifMap){
   1032             printf("Map: %05d-%05d: Thumbnail\n",ThumbnailOffset, ThumbnailOffset+ThumbnailSize);
   1033         }
   1034 
   1035         if (ThumbnailOffset <= ExifLength){
   1036             if (ThumbnailSize > ExifLength-ThumbnailOffset){
   1037                 // If thumbnail extends past exif header, only save the part that
   1038                 // actually exists.  Canon's EOS viewer utility will do this - the
   1039                 // thumbnail extracts ok with this hack.
   1040                 ThumbnailSize = ExifLength-ThumbnailOffset;
   1041                 if (ShowTags) printf("Thumbnail incorrectly placed in header\n");
   1042 
   1043             }
   1044             // The thumbnail pointer appears to be valid.  Store it.
   1045             ImageInfo.ThumbnailOffset = ThumbnailOffset;
   1046             ImageInfo.ThumbnailSize = ThumbnailSize;
   1047 
   1048             if (ShowTags){
   1049                 printf("Thumbnail size: %d bytes\n",ThumbnailSize);
   1050             }
   1051         }
   1052     }
   1053     printf("returning from ProcessExifDir");
   1054 }
   1055 
   1056 
   1057 //--------------------------------------------------------------------------
   1058 // Process a EXIF marker
   1059 // Describes all the drivel that most digital cameras include...
   1060 //--------------------------------------------------------------------------
   1061 void process_EXIF (unsigned char * ExifSection, unsigned int length)
   1062 {
   1063     int FirstOffset;
   1064 
   1065     FocalplaneXRes = 0;
   1066     FocalplaneUnits = 0;
   1067     ExifImageWidth = 0;
   1068     NumOrientations = 0;
   1069 
   1070     if (ShowTags){
   1071         printf("Exif header %d bytes long\n",length);
   1072     }
   1073 
   1074     {   // Check the EXIF header component
   1075         static uchar ExifHeader[] = "Exif\0\0";
   1076         if (memcmp(ExifSection+2, ExifHeader,6)){
   1077             ErrNonfatal("Incorrect Exif header",0,0);
   1078             return;
   1079         }
   1080     }
   1081 
   1082     if (memcmp(ExifSection+8,"II",2) == 0){
   1083         if (ShowTags) printf("Exif section in Intel order\n");
   1084         MotorolaOrder = 0;
   1085     }else{
   1086         if (memcmp(ExifSection+8,"MM",2) == 0){
   1087             if (ShowTags) printf("Exif section in Motorola order\n");
   1088             MotorolaOrder = 1;
   1089         }else{
   1090             ErrNonfatal("Invalid Exif alignment marker.",0,0);
   1091             return;
   1092         }
   1093     }
   1094 
   1095     // Check the next value for correctness.
   1096     if (Get16u(ExifSection+10) != 0x2a){
   1097         ErrNonfatal("Invalid Exif start (1)",0,0);
   1098         return;
   1099     }
   1100 
   1101     FirstOffset = Get32u(ExifSection+12);
   1102     if (FirstOffset < 8 || FirstOffset > 16){
   1103         // Usually set to 8, but other values valid too.
   1104         ErrNonfatal("Suspicious offset of first IFD value",0,0);
   1105         return;
   1106     }
   1107 
   1108     DirWithThumbnailPtrs = NULL;
   1109 
   1110 
   1111     // First directory starts 16 bytes in.  All offset are relative to 8 bytes in.
   1112     ProcessExifDir(ExifSection+8+FirstOffset, ExifSection+8, length-8, 0);
   1113 
   1114     ImageInfo.ThumbnailAtEnd = ImageInfo.ThumbnailOffset >= ImageInfo.LargestExifOffset ? TRUE : FALSE;
   1115 #ifdef SUPERDEBUG
   1116     printf("Thumbnail %s end", (ImageInfo.ThumbnailAtEnd ? "at" : "NOT at"));
   1117 #endif
   1118     if (DumpExifMap){
   1119         unsigned a,b;
   1120         printf("Map: %05d- End of exif\n",length-8);
   1121 //        for (a=0;a<length-8;a+= 10){
   1122 //            printf("Map: %05d ",a);
   1123 //            for (b=0;b<10;b++) printf(" %02x",*(ExifSection+8+a+b));
   1124 //            printf("\n");
   1125 //        }
   1126         for (a = 0; a < length - 8; ++a) {
   1127             unsigned char c = *(ExifSection+8+a);
   1128             unsigned pc = isprint(c) ? c : ' ';
   1129             printf("Map: %4d %02x %c", a, c, pc);
   1130         }
   1131     }
   1132 
   1133 
   1134     // Compute the CCD width, in millimeters.
   1135     if (FocalplaneXRes != 0){
   1136         // Note: With some cameras, its not possible to compute this correctly because
   1137         // they don't adjust the indicated focal plane resolution units when using less
   1138         // than maximum resolution, so the CCDWidth value comes out too small.  Nothing
   1139         // that Jhad can do about it - its a camera problem.
   1140         ImageInfo.CCDWidth = (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes);
   1141 
   1142         if (ImageInfo.FocalLength.num != 0 && ImageInfo.FocalLength.denom != 0
   1143             && ImageInfo.FocalLength35mmEquiv == 0){
   1144             // Compute 35 mm equivalent focal length based on sensor geometry if we haven't
   1145             // already got it explicitly from a tag.
   1146             ImageInfo.FocalLength35mmEquiv = (int)(
   1147                 (double)ImageInfo.FocalLength.num / ImageInfo.FocalLength.denom
   1148                 / ImageInfo.CCDWidth * 36 + 0.5);
   1149         }
   1150     }
   1151 }
   1152 
   1153 static const TagTable_t* TagToTagTableEntry(unsigned short tag)
   1154 {
   1155     unsigned int i;
   1156     for (i = 0; i < TAG_TABLE_SIZE; i++) {
   1157         if (TagTable[i].Tag == tag) {
   1158             printf("found tag %d", tag);
   1159             int format = TagTable[i].Format;
   1160             if (format == 0) {
   1161                 printf("tag %s format not defined ***** YOU MUST ADD THE FORMAT TO THE TagTable in exif.c!!!!", TagTable[i].Desc);
   1162                 return NULL;
   1163             }
   1164             return &TagTable[i];
   1165         }
   1166     }
   1167     printf("tag %d NOT FOUND", tag);
   1168     return NULL;
   1169 }
   1170 
   1171 static void writeExifTagAndData(int tag,
   1172                                 int format,
   1173                                 long components,
   1174                                 long value,
   1175                                 int valueInString,
   1176                                 char* Buffer,
   1177                                 int* DirIndex,
   1178                                 int* DataWriteIndex) {
   1179     void* componentsPosition = NULL; // for saving component position
   1180 
   1181     Put16u(Buffer+ (*DirIndex), tag);                    // Tag
   1182     Put16u(Buffer+(*DirIndex) + 2, format);              // Format
   1183     if (format == FMT_STRING && components == -1) {
   1184         components = strlen((char*)value) + 1;                 // account for null terminator
   1185         if (components & 1) ++components;               // no odd lengths
   1186     } else if (format == FMT_SSHORT && components == -1) {
   1187         // jhead only supports reading one SSHORT anyway
   1188         components = 1;
   1189     }
   1190     if (format == FMT_UNDEFINED && components == -1) {
   1191         // check if this UNDEFINED format is actually ASCII (as it usually is)
   1192         // if so, we can calculate the size
   1193         if(memcmp((char*)value, ExifAsciiPrefix, sizeof(ExifAsciiPrefix)) == 0) {
   1194             components = sizeof(ExifAsciiPrefix) +
   1195                          strlen((char*)value + sizeof(ExifAsciiPrefix)) + 1;
   1196             if (components & 1) ++components;               // no odd lengths
   1197         }
   1198     }
   1199     Put32u(Buffer+(*DirIndex) + 4, components);         // Components
   1200     componentsPosition = Buffer+(*DirIndex) + 4; // components # can change for lists
   1201     printf("# components: %ld", components);
   1202     if (format == FMT_STRING) {
   1203         // short strings can fit right in the long, otherwise have to
   1204         // go in the data area
   1205         if (components <= 4) {
   1206             strcpy(Buffer+(*DirIndex) + 8, (char*)value);
   1207         } else {
   1208             Put32u(Buffer+(*DirIndex) + 8, (*DataWriteIndex)-8);   // Pointer
   1209             printf("copying value %s to %d", (char*)value, (*DataWriteIndex));
   1210             strncpy(Buffer+(*DataWriteIndex), (char*)value, components);
   1211             (*DataWriteIndex) += components;
   1212         }
   1213     } else if ((format == FMT_UNDEFINED) &&
   1214                (memcmp((char*)value, ExifAsciiPrefix, sizeof(ExifAsciiPrefix)) == 0)) {
   1215         // short strings can fit right in the long, otherwise have to
   1216         // go in the data area
   1217         if (components <= 4) {
   1218             memcpy(Buffer+(*DirIndex) + 8, (char*)value, components);
   1219         } else {
   1220             Put32u(Buffer+(*DirIndex) + 8, (*DataWriteIndex)-8);   // Pointer
   1221             printf("copying %s to %d", (char*)value + sizeof(ExifAsciiPrefix), (*DataWriteIndex));
   1222             memcpy(Buffer+(*DataWriteIndex), (char*)value, components);
   1223             (*DataWriteIndex) += components;
   1224         }
   1225     } else if (!valueInString) {
   1226         Put32u(Buffer+(*DirIndex) + 8, value);   // Value
   1227     } else {
   1228         Put32u(Buffer+(*DirIndex) + 8, (*DataWriteIndex)-8);   // Pointer
   1229         // Usually the separator is ',', but sometimes ':' is used, like
   1230         // TAG_GPS_TIMESTAMP.
   1231         char* curElement = strtok((char*)value, ",:");
   1232         int i;
   1233 
   1234         // (components == -1) Need to handle lists with unknown length too
   1235         for (i = 0; ((i < components) || (components == -1)) && curElement != NULL; i++) {
   1236 #ifdef SUPERDEBUG
   1237             printf("processing component %s format %s", curElement, formatStr(format));
   1238 #endif
   1239             // elements are separated by commas
   1240             if (format == FMT_URATIONAL) {
   1241                 unsigned int numerator;
   1242                 unsigned int denominator;
   1243                 char* separator = strchr(curElement, '/');
   1244                 if (separator) {
   1245                     numerator = atoi(curElement);
   1246                     denominator = atoi(separator + 1);
   1247                 } else {
   1248                     double value = atof(curElement);
   1249                     ConvertDoubleToURational(value, &numerator, &denominator);
   1250                 }
   1251                 Put32u(Buffer+(*DataWriteIndex), numerator);
   1252                 Put32u(Buffer+(*DataWriteIndex) + 4, denominator);
   1253                 (*DataWriteIndex) += 8;
   1254             } else if (format == FMT_SRATIONAL) {
   1255                 int numerator;
   1256                 int denominator;
   1257                 char* separator = strchr(curElement, '/');
   1258                 if (separator) {
   1259                     numerator = atoi(curElement);
   1260                     denominator = atoi(separator + 1);
   1261                 } else {
   1262                     double value = atof(curElement);
   1263                     ConvertDoubleToSRational(value, &numerator, &denominator);
   1264                 }
   1265                 Put32u(Buffer+(*DataWriteIndex), numerator);
   1266                 Put32u(Buffer+(*DataWriteIndex) + 4, denominator);
   1267                 (*DataWriteIndex) += 8;
   1268             } else if ((components == -1) && ((format == FMT_USHORT) || (format == FMT_SSHORT))) {
   1269                 // variable components need to go into data write area
   1270                 value = atoi(curElement);
   1271                 Put16u(Buffer+(*DataWriteIndex), value);
   1272                 (*DataWriteIndex) += 4;
   1273             } else {
   1274                 // TODO: doesn't handle multiple components yet -- if more than one, have to put in data write area.
   1275                 value = atoi(curElement);
   1276                 Put32u(Buffer+(*DirIndex) + 8, value);   // Value
   1277             }
   1278             curElement = strtok(NULL, ",:");
   1279         }
   1280         if (components == -1) Put32u(componentsPosition, i); // update component # for unknowns
   1281     }
   1282     (*DirIndex) += 12;
   1283 }
   1284 
   1285 #ifdef SUPERDEBUG
   1286 char* formatStr(int format) {
   1287     switch (format) {
   1288         case FMT_BYTE: return "FMT_BYTE"; break;
   1289         case FMT_STRING: return "FMT_STRING"; break;
   1290         case FMT_USHORT: return "FMT_USHORT"; break;
   1291         case FMT_ULONG: return "FMT_ULONG"; break;
   1292         case FMT_URATIONAL: return "FMT_URATIONAL"; break;
   1293         case FMT_SBYTE: return "FMT_SBYTE"; break;
   1294         case FMT_UNDEFINED: return "FMT_UNDEFINED"; break;
   1295         case FMT_SSHORT: return "FMT_SSHORT"; break;
   1296         case FMT_SLONG: return "FMT_SLONG"; break;
   1297         case FMT_SRATIONAL: return "FMT_SRATIONAL"; break;
   1298         case FMT_SINGLE: return "FMT_SINGLE"; break;
   1299         case FMT_DOUBLE: return "FMT_SINGLE"; break;
   1300         default: return "UNKNOWN";
   1301     }
   1302 }
   1303 #endif
   1304 
   1305 //--------------------------------------------------------------------------
   1306 // Create minimal exif header - just date and thumbnail pointers,
   1307 // so that date and thumbnail may be filled later.
   1308 //--------------------------------------------------------------------------
   1309 static void create_EXIF_internal(ExifElement_t* elements, int exifTagCount, int gpsTagCount, int hasDateTimeTag, char* Buffer)
   1310 {
   1311     unsigned short NumEntries;
   1312     int DataWriteIndex;
   1313     int DirIndex;
   1314     int DirExifLink = 0;
   1315 
   1316 #ifdef SUPERDEBUG
   1317     ALOGE("create_EXIF %d exif elements, %d gps elements", exifTagCount, gpsTagCount);
   1318 #endif
   1319 
   1320     MotorolaOrder = 0;
   1321 
   1322     memcpy(Buffer+2, "Exif\0\0II",8);
   1323     Put16u(Buffer+10, 0x2a);
   1324 
   1325     DataWriteIndex = 16;
   1326     Put32u(Buffer+12, DataWriteIndex-8); // first IFD offset.  Means start 16 bytes in.
   1327 
   1328     {
   1329         DirIndex = DataWriteIndex;
   1330         NumEntries = 1 + exifTagCount;  // the extra is the thumbnail
   1331         if (gpsTagCount) {
   1332             ++NumEntries;       // allow for the GPS info tag
   1333         }
   1334         if (!hasDateTimeTag) {
   1335             // We have to write extra date time tag. The entry number should be
   1336             // adjusted.
   1337             ++NumEntries;
   1338         }
   1339         DataWriteIndex += 2 + NumEntries*12 + 4;
   1340 
   1341         Put16u(Buffer+DirIndex, NumEntries); // Number of entries
   1342         DirIndex += 2;
   1343 
   1344         // Entries go here...
   1345         if (!hasDateTimeTag) {
   1346             // Date/time entry
   1347             char* dateTime = NULL;
   1348             char dateBuf[20];
   1349             if (ImageInfo.numDateTimeTags) {
   1350                 // If we had a pre-existing exif header, use time from that.
   1351                 dateTime = ImageInfo.DateTime;
   1352             } else {
   1353                 // Oterwise, use the file's timestamp.
   1354                 FileTimeAsString(dateBuf);
   1355                 dateTime = dateBuf;
   1356             }
   1357             writeExifTagAndData(TAG_DATETIME,
   1358                                 FMT_STRING,
   1359                                 20,
   1360                                 (long)(char*)dateBuf,
   1361                                 FALSE,
   1362                                 Buffer,
   1363                                 &DirIndex,
   1364                                 &DataWriteIndex);
   1365 
   1366         }
   1367         if (exifTagCount > 0) {
   1368             int i;
   1369             for (i = 0; i < exifTagCount + gpsTagCount; i++) {
   1370                 if (elements[i].GpsTag) {
   1371                     continue;
   1372                 }
   1373                 const TagTable_t* entry = TagToTagTableEntry(elements[i].Tag);
   1374                 if (entry == NULL) {
   1375                     continue;
   1376                 }
   1377 #ifdef SUPERDEBUG
   1378                 ALOGE("create_EXIF saving tag %x value \"%s\"",elements[i].Tag, elements[i].Value);
   1379 #endif
   1380                 writeExifTagAndData(elements[i].Tag,
   1381                                     entry->Format,
   1382                                     entry->DataLength,
   1383                                     (long)elements[i].Value,
   1384                                     TRUE,
   1385                                     Buffer,
   1386                                     &DirIndex,
   1387                                     &DataWriteIndex);
   1388             }
   1389 
   1390             if (gpsTagCount) {
   1391                 // Link to gps dir entry
   1392                 writeExifTagAndData(TAG_GPSINFO,
   1393                                     FMT_ULONG,
   1394                                     1,
   1395                                     DataWriteIndex-8,
   1396                                     FALSE,
   1397                                     Buffer,
   1398                                     &DirIndex,
   1399                                     &DataWriteIndex);
   1400             }
   1401 
   1402             // Link to exif dir entry
   1403             int exifDirPtr = DataWriteIndex-8;
   1404             if (gpsTagCount) {
   1405                 exifDirPtr += 2 + gpsTagCount*12 + 4;
   1406             }
   1407             DirExifLink = DirIndex;
   1408             writeExifTagAndData(TAG_EXIF_OFFSET,
   1409                                 FMT_ULONG,
   1410                                 1,
   1411                                 exifDirPtr,
   1412                                 FALSE,
   1413                                 Buffer,
   1414                                 &DirIndex,
   1415                                 &DataWriteIndex);
   1416         }
   1417 
   1418         // End of directory - contains optional link to continued directory.
   1419         Put32u(Buffer+DirIndex, 0);
   1420         printf("Ending Exif section DirIndex = %d DataWriteIndex %d", DirIndex, DataWriteIndex);
   1421     }
   1422 
   1423 
   1424     // GPS Section
   1425     if (gpsTagCount) {
   1426         DirIndex = DataWriteIndex;
   1427         printf("Starting GPS section DirIndex = %d", DirIndex);
   1428         NumEntries = gpsTagCount;
   1429         DataWriteIndex += 2 + NumEntries*12 + 4;
   1430 
   1431         Put16u(Buffer+DirIndex, NumEntries); // Number of entries
   1432         DirIndex += 2;
   1433         {
   1434             int i;
   1435             for (i = 0; i < exifTagCount + gpsTagCount; i++) {
   1436                 if (!elements[i].GpsTag) {
   1437                     continue;
   1438                 }
   1439                 const TagTable_t* entry = GpsTagToTagTableEntry(elements[i].Tag);
   1440                 if (entry == NULL) {
   1441                     continue;
   1442                 }
   1443 #ifdef SUPERDEBUG
   1444                 ALOGE("create_EXIF saving GPS tag %x value \"%s\"",elements[i].Tag, elements[i].Value);
   1445 #endif
   1446                 writeExifTagAndData(elements[i].Tag,
   1447                                     entry->Format,
   1448                                     entry->DataLength,
   1449                                     (long)elements[i].Value,
   1450                                     TRUE,
   1451                                     Buffer,
   1452                                     &DirIndex,
   1453                                     &DataWriteIndex);
   1454             }
   1455         }
   1456 
   1457         // End of directory - contains optional link to continued directory.
   1458         Put32u(Buffer+DirIndex, 0);
   1459         printf("Ending GPS section DirIndex = %d DataWriteIndex %d", DirIndex, DataWriteIndex);
   1460     }
   1461 
   1462     {
   1463         // Overwriting TAG_EXIF_OFFSET which links to this directory
   1464         Put32u(Buffer+DirExifLink+8, DataWriteIndex-8);
   1465 
   1466         printf("Starting Thumbnail section DirIndex = %d", DirIndex);
   1467         DirIndex = DataWriteIndex;
   1468         NumEntries = 2;
   1469         DataWriteIndex += 2 + NumEntries*12 + 4;
   1470 
   1471         Put16u(Buffer+DirIndex, NumEntries); // Number of entries
   1472         DirIndex += 2;
   1473         {
   1474             // Link to exif dir entry
   1475             writeExifTagAndData(TAG_THUMBNAIL_OFFSET,
   1476                                 FMT_ULONG,
   1477                                 1,
   1478                                 DataWriteIndex-8,
   1479                                 FALSE,
   1480                                 Buffer,
   1481                                 &DirIndex,
   1482                                 &DataWriteIndex);
   1483         }
   1484 
   1485         {
   1486             // Link to exif dir entry
   1487             writeExifTagAndData(TAG_THUMBNAIL_LENGTH,
   1488                                 FMT_ULONG,
   1489                                 1,
   1490                                 0,
   1491                                 FALSE,
   1492                                 Buffer,
   1493                                 &DirIndex,
   1494                                 &DataWriteIndex);
   1495         }
   1496 
   1497         // End of directory - contains optional link to continued directory.
   1498         Put32u(Buffer+DirIndex, 0);
   1499         printf("Ending Thumbnail section DirIndex = %d DataWriteIndex %d", DirIndex, DataWriteIndex);
   1500     }
   1501 
   1502 
   1503     Buffer[0] = (unsigned char)(DataWriteIndex >> 8);
   1504     Buffer[1] = (unsigned char)DataWriteIndex;
   1505 
   1506     // Remove old exif section, if there was one.
   1507     RemoveSectionType(M_EXIF);
   1508 
   1509     {
   1510         // Sections need malloced buffers, so do that now, especially because
   1511         // we now know how big it needs to be allocated.
   1512         unsigned char * NewBuf = malloc(DataWriteIndex);
   1513         if (NewBuf == NULL){
   1514             ErrFatal("Could not allocate memory");
   1515         }
   1516         memcpy(NewBuf, Buffer, DataWriteIndex);
   1517 
   1518         CreateSection(M_EXIF, NewBuf, DataWriteIndex);
   1519 
   1520         // Re-parse new exif section, now that its in place
   1521         // otherwise, we risk touching data that has already been freed.
   1522         process_EXIF(NewBuf, DataWriteIndex);
   1523     }
   1524 }
   1525 
   1526 void create_EXIF(ExifElement_t* elements, int exifTagCount, int gpsTagCount, int hasDateTimeTag)
   1527 {
   1528     // It is hard to calculate exact necessary size for editing the exif
   1529     // header dynamically, so we are using the maximum size of EXIF, 64K
   1530     const int EXIF_MAX_SIZE = 1024*64;
   1531     char* Buffer = malloc(EXIF_MAX_SIZE);
   1532 
   1533     if (Buffer != NULL) {
   1534         create_EXIF_internal(elements, exifTagCount, gpsTagCount, hasDateTimeTag, Buffer);
   1535         free(Buffer);
   1536     } else {
   1537         ErrFatal("Could not allocate memory");
   1538     }
   1539 }
   1540 
   1541 //--------------------------------------------------------------------------
   1542 // Cler the rotation tag in the exif header to 1.
   1543 //--------------------------------------------------------------------------
   1544 const char * ClearOrientation(void)
   1545 {
   1546     int a;
   1547     if (NumOrientations == 0) return NULL;
   1548 
   1549     for (a=0;a<NumOrientations;a++){
   1550         switch(OrientationNumFormat[a]){
   1551             case FMT_SBYTE:
   1552             case FMT_BYTE:
   1553                 *(uchar *)(OrientationPtr[a]) = 1;
   1554                 break;
   1555 
   1556             case FMT_USHORT:
   1557                 Put16u(OrientationPtr[a], 1);
   1558                 break;
   1559 
   1560             case FMT_ULONG:
   1561             case FMT_SLONG:
   1562                 memset(OrientationPtr, 0, 4);
   1563                 // Can't be bothered to write  generic Put32 if I only use it once.
   1564                 if (MotorolaOrder){
   1565                     ((uchar *)OrientationPtr[a])[3] = 1;
   1566                 }else{
   1567                     ((uchar *)OrientationPtr[a])[0] = 1;
   1568                 }
   1569                 break;
   1570 
   1571             default:
   1572                 return NULL;
   1573         }
   1574     }
   1575 
   1576     return OrientTab[ImageInfo.Orientation];
   1577 }
   1578 
   1579 
   1580 
   1581 //--------------------------------------------------------------------------
   1582 // Remove thumbnail out of the exif image.
   1583 //--------------------------------------------------------------------------
   1584 int RemoveThumbnail(unsigned char * ExifSection)
   1585 {
   1586     if (!DirWithThumbnailPtrs ||
   1587         ImageInfo.ThumbnailOffset == 0 ||
   1588         ImageInfo.ThumbnailSize == 0){
   1589         // No thumbnail, or already deleted it.
   1590         return 0;
   1591     }
   1592     if (ImageInfo.ThumbnailAtEnd == FALSE){
   1593         ErrNonfatal("Thumbnail is not at end of header, can't chop it off", 0, 0);
   1594         return 0;
   1595     }
   1596 
   1597     {
   1598         int de;
   1599         int NumDirEntries;
   1600         NumDirEntries = Get16u(DirWithThumbnailPtrs);
   1601 
   1602         for (de=0;de<NumDirEntries;de++){
   1603             int Tag;
   1604             unsigned char * DirEntry;
   1605             DirEntry = DIR_ENTRY_ADDR(DirWithThumbnailPtrs, de);
   1606             Tag = Get16u(DirEntry);
   1607             if (Tag == TAG_THUMBNAIL_LENGTH){
   1608                 // Set length to zero.
   1609                 if (Get16u(DirEntry+2) != FMT_ULONG){
   1610                     // non standard format encoding.  Can't do it.
   1611                     ErrNonfatal("Can't remove thumbnail", 0, 0);
   1612                     return 0;
   1613                 }
   1614                 Put32u(DirEntry+8, 0);
   1615             }
   1616         }
   1617     }
   1618 
   1619     // This is how far the non thumbnail data went.
   1620     return ImageInfo.ThumbnailOffset+8;
   1621 
   1622 }
   1623 
   1624 
   1625 //--------------------------------------------------------------------------
   1626 // Convert exif time to Unix time structure
   1627 //--------------------------------------------------------------------------
   1628 int Exif2tm(struct tm * timeptr, char * ExifTime)
   1629 {
   1630     int a;
   1631 
   1632     timeptr->tm_wday = -1;
   1633 
   1634     // Check for format: YYYY:MM:DD HH:MM:SS format.
   1635     // Date and time normally separated by a space, but also seen a ':' there, so
   1636     // skip the middle space with '%*c' so it can be any character.
   1637     a = sscanf(ExifTime, "%d%*c%d%*c%d%*c%d:%d:%d",
   1638             &timeptr->tm_year, &timeptr->tm_mon, &timeptr->tm_mday,
   1639             &timeptr->tm_hour, &timeptr->tm_min, &timeptr->tm_sec);
   1640 
   1641 
   1642     if (a == 6){
   1643         timeptr->tm_isdst = -1;
   1644         timeptr->tm_mon -= 1;      // Adjust for unix zero-based months
   1645         timeptr->tm_year -= 1900;  // Adjust for year starting at 1900
   1646         return TRUE; // worked.
   1647     }
   1648 
   1649     return FALSE; // Wasn't in Exif date format.
   1650 }
   1651 
   1652 
   1653 //--------------------------------------------------------------------------
   1654 // Show the collected image info, displaying camera F-stop and shutter speed
   1655 // in a consistent and legible fashion.
   1656 //--------------------------------------------------------------------------
   1657 void ShowImageInfo(int ShowFileInfo)
   1658 {
   1659     if (ShowFileInfo){
   1660         printf("File name    : %s\n",ImageInfo.FileName);
   1661         printf("File size    : %d bytes\n",ImageInfo.FileSize);
   1662 
   1663         {
   1664             char Temp[20];
   1665             FileTimeAsString(Temp);
   1666             printf("File date    : %s\n",Temp);
   1667         }
   1668     }
   1669 
   1670     if (ImageInfo.CameraMake[0]){
   1671         printf("Camera make  : %s\n",ImageInfo.CameraMake);
   1672         printf("Camera model : %s\n",ImageInfo.CameraModel);
   1673     }
   1674     if (ImageInfo.DateTime[0]){
   1675         printf("Date/Time    : %s\n",ImageInfo.DateTime);
   1676     }
   1677     printf("Resolution   : %d x %d\n",ImageInfo.Width, ImageInfo.Height);
   1678 
   1679     if (ImageInfo.Orientation > 1){
   1680         // Only print orientation if one was supplied, and if its not 1 (normal orientation)
   1681         printf("Orientation  : %s\n", OrientTab[ImageInfo.Orientation]);
   1682     }
   1683 
   1684     if (ImageInfo.IsColor == 0){
   1685         printf("Color/bw     : Black and white\n");
   1686     }
   1687 
   1688     if (ImageInfo.FlashUsed >= 0){
   1689         if (ImageInfo.FlashUsed & 1){
   1690             printf("Flash used   : Yes");
   1691             switch (ImageInfo.FlashUsed){
   1692 	            case 0x5: printf(" (Strobe light not detected)"); break;
   1693 	            case 0x7: printf(" (Strobe light detected) "); break;
   1694 	            case 0x9: printf(" (manual)"); break;
   1695 	            case 0xd: printf(" (manual, return light not detected)"); break;
   1696 	            case 0xf: printf(" (manual, return light  detected)"); break;
   1697 	            case 0x19:printf(" (auto)"); break;
   1698 	            case 0x1d:printf(" (auto, return light not detected)"); break;
   1699 	            case 0x1f:printf(" (auto, return light detected)"); break;
   1700 	            case 0x41:printf(" (red eye reduction mode)"); break;
   1701 	            case 0x45:printf(" (red eye reduction mode return light not detected)"); break;
   1702 	            case 0x47:printf(" (red eye reduction mode return light  detected)"); break;
   1703 	            case 0x49:printf(" (manual, red eye reduction mode)"); break;
   1704 	            case 0x4d:printf(" (manual, red eye reduction mode, return light not detected)"); break;
   1705 	            case 0x4f:printf(" (red eye reduction mode, return light detected)"); break;
   1706 	            case 0x59:printf(" (auto, red eye reduction mode)"); break;
   1707 	            case 0x5d:printf(" (auto, red eye reduction mode, return light not detected)"); break;
   1708 	            case 0x5f:printf(" (auto, red eye reduction mode, return light detected)"); break;
   1709             }
   1710         }else{
   1711             printf("Flash used   : No");
   1712             switch (ImageInfo.FlashUsed){
   1713 	            case 0x18:printf(" (auto)"); break;
   1714             }
   1715         }
   1716         printf("\n");
   1717     }
   1718 
   1719 
   1720     if (ImageInfo.FocalLength.num != 0 && ImageInfo.FocalLength.denom != 0) {
   1721         printf("Focal length : %4.1fmm",(double)ImageInfo.FocalLength.num / ImageInfo.FocalLength.denom);
   1722         if (ImageInfo.FocalLength35mmEquiv){
   1723             printf("  (35mm equivalent: %dmm)", ImageInfo.FocalLength35mmEquiv);
   1724         }
   1725         printf("\n");
   1726     }
   1727 
   1728     if (ImageInfo.DigitalZoomRatio > 1){
   1729         // Digital zoom used.  Shame on you!
   1730         printf("Digital Zoom : %1.3fx\n", (double)ImageInfo.DigitalZoomRatio);
   1731     }
   1732 
   1733     if (ImageInfo.CCDWidth){
   1734         printf("CCD width    : %4.2fmm\n",(double)ImageInfo.CCDWidth);
   1735     }
   1736 
   1737     if (ImageInfo.ExposureTime){
   1738         if (ImageInfo.ExposureTime < 0.010){
   1739             printf("Exposure time: %6.4f s ",(double)ImageInfo.ExposureTime);
   1740         }else{
   1741             printf("Exposure time: %5.3f s ",(double)ImageInfo.ExposureTime);
   1742         }
   1743         if (ImageInfo.ExposureTime <= 0.5){
   1744             printf(" (1/%d)",(int)(0.5 + 1/ImageInfo.ExposureTime));
   1745         }
   1746         printf("\n");
   1747     }
   1748     if (ImageInfo.ApertureFNumber){
   1749         printf("Aperture     : f/%3.1f\n",(double)ImageInfo.ApertureFNumber);
   1750     }
   1751     if (ImageInfo.Distance){
   1752         if (ImageInfo.Distance < 0){
   1753             printf("Focus dist.  : Infinite\n");
   1754         }else{
   1755             printf("Focus dist.  : %4.2fm\n",(double)ImageInfo.Distance);
   1756         }
   1757     }
   1758 
   1759     if (ImageInfo.ISOequivalent){
   1760         printf("ISO equiv.   : %2d\n",(int)ImageInfo.ISOequivalent);
   1761     }
   1762 
   1763     if (ImageInfo.ExposureBias){
   1764         // If exposure bias was specified, but set to zero, presumably its no bias at all,
   1765         // so only show it if its nonzero.
   1766         printf("Exposure bias: %4.2f\n",(double)ImageInfo.ExposureBias);
   1767     }
   1768 
   1769     switch(ImageInfo.Whitebalance) {
   1770         case 1:
   1771             printf("Whitebalance : Manual\n");
   1772             break;
   1773         case 0:
   1774             printf("Whitebalance : Auto\n");
   1775             break;
   1776     }
   1777 
   1778     //Quercus: 17-1-2004 Added LightSource, some cams return this, whitebalance or both
   1779     switch(ImageInfo.LightSource) {
   1780         case 1:
   1781             printf("Light Source : Daylight\n");
   1782             break;
   1783         case 2:
   1784             printf("Light Source : Fluorescent\n");
   1785             break;
   1786         case 3:
   1787             printf("Light Source : Incandescent\n");
   1788             break;
   1789         case 4:
   1790             printf("Light Source : Flash\n");
   1791             break;
   1792         case 9:
   1793             printf("Light Source : Fine weather\n");
   1794             break;
   1795         case 11:
   1796             printf("Light Source : Shade\n");
   1797             break;
   1798         default:; //Quercus: 17-1-2004 There are many more modes for this, check Exif2.2 specs
   1799             // If it just says 'unknown' or we don't know it, then
   1800             // don't bother showing it - it doesn't add any useful information.
   1801     }
   1802 
   1803     if (ImageInfo.MeteringMode){ // 05-jan-2001 vcs
   1804         switch(ImageInfo.MeteringMode) {
   1805         case 2:
   1806             printf("Metering Mode: center weight\n");
   1807             break;
   1808         case 3:
   1809             printf("Metering Mode: spot\n");
   1810             break;
   1811         case 5:
   1812             printf("Metering Mode: matrix\n");
   1813             break;
   1814         }
   1815     }
   1816 
   1817     if (ImageInfo.ExposureProgram){ // 05-jan-2001 vcs
   1818         switch(ImageInfo.ExposureProgram) {
   1819         case 1:
   1820             printf("Exposure     : Manual\n");
   1821             break;
   1822         case 2:
   1823             printf("Exposure     : program (auto)\n");
   1824             break;
   1825         case 3:
   1826             printf("Exposure     : aperture priority (semi-auto)\n");
   1827             break;
   1828         case 4:
   1829             printf("Exposure     : shutter priority (semi-auto)\n");
   1830             break;
   1831         case 5:
   1832             printf("Exposure     : Creative Program (based towards depth of field)\n");
   1833             break;
   1834         case 6:
   1835             printf("Exposure     : Action program (based towards fast shutter speed)\n");
   1836             break;
   1837         case 7:
   1838             printf("Exposure     : Portrait Mode\n");
   1839             break;
   1840         case 8:
   1841             printf("Exposure     : LandscapeMode \n");
   1842             break;
   1843         default:
   1844             break;
   1845         }
   1846     }
   1847     switch(ImageInfo.ExposureMode){
   1848         case 0: // Automatic (not worth cluttering up output for)
   1849             break;
   1850         case 1: printf("Exposure Mode: Manual\n");
   1851             break;
   1852         case 2: printf("Exposure Mode: Auto bracketing\n");
   1853             break;
   1854     }
   1855 
   1856     if (ImageInfo.DistanceRange) {
   1857         printf("Focus range  : ");
   1858         switch(ImageInfo.DistanceRange) {
   1859             case 1:
   1860                 printf("macro");
   1861                 break;
   1862             case 2:
   1863                 printf("close");
   1864                 break;
   1865             case 3:
   1866                 printf("distant");
   1867                 break;
   1868         }
   1869         printf("\n");
   1870     }
   1871 
   1872 
   1873 
   1874     if (ImageInfo.Process != M_SOF0){
   1875         // don't show it if its the plain old boring 'baseline' process, but do
   1876         // show it if its something else, like 'progressive' (used on web sometimes)
   1877         int a;
   1878         for (a=0;;a++){
   1879             if (a >= (int)PROCESS_TABLE_SIZE){
   1880                 // ran off the end of the table.
   1881                 printf("Jpeg process : Unknown\n");
   1882                 break;
   1883             }
   1884             if (ProcessTable[a].Tag == ImageInfo.Process){
   1885                 printf("Jpeg process : %s\n",ProcessTable[a].Desc);
   1886                 break;
   1887             }
   1888         }
   1889     }
   1890 
   1891     if (ImageInfo.GpsInfoPresent){
   1892         printf("GPS Latitude : %s\n",ImageInfo.GpsLat);
   1893         printf("GPS Longitude: %s\n",ImageInfo.GpsLong);
   1894         if (ImageInfo.GpsAlt[0]) printf("GPS Altitude : %s\n",ImageInfo.GpsAlt);
   1895     }
   1896 
   1897     // Print the comment. Print 'Comment:' for each new line of comment.
   1898     if (ImageInfo.Comments[0]){
   1899         int a,c;
   1900         printf("Comment      : ");
   1901         if (!ImageInfo.CommentWidchars){
   1902             for (a=0;a<MAX_COMMENT_SIZE;a++){
   1903                 c = ImageInfo.Comments[a];
   1904                 if (c == '\0') break;
   1905                 if (c == '\n'){
   1906                     // Do not start a new line if the string ends with a carriage return.
   1907                     if (ImageInfo.Comments[a+1] != '\0'){
   1908                         printf("\nComment      : ");
   1909                     }else{
   1910                         printf("\n");
   1911                     }
   1912                 }else{
   1913                     putchar(c);
   1914                 }
   1915             }
   1916             printf("\n");
   1917         }else{
   1918             printf("%.*ls\n", ImageInfo.CommentWidchars, (wchar_t *)ImageInfo.Comments);
   1919         }
   1920     }
   1921     if (ImageInfo.ThumbnailOffset){
   1922         printf("Map: %05d-%05d: Thumbnail\n",ImageInfo.ThumbnailOffset, ImageInfo.ThumbnailOffset+ImageInfo.ThumbnailSize);
   1923     } else {
   1924         printf("NO thumbnail");
   1925     }
   1926 }
   1927 
   1928 
   1929 //--------------------------------------------------------------------------
   1930 // Summarize highlights of image info on one line (suitable for grep-ing)
   1931 //--------------------------------------------------------------------------
   1932 void ShowConciseImageInfo(void)
   1933 {
   1934     printf("\"%s\"",ImageInfo.FileName);
   1935 
   1936     printf(" %dx%d",ImageInfo.Width, ImageInfo.Height);
   1937 
   1938     if (ImageInfo.ExposureTime){
   1939         if (ImageInfo.ExposureTime <= 0.5){
   1940             printf(" (1/%d)",(int)(0.5 + 1/ImageInfo.ExposureTime));
   1941         }else{
   1942             printf(" (%1.1f)",ImageInfo.ExposureTime);
   1943         }
   1944     }
   1945 
   1946     if (ImageInfo.ApertureFNumber){
   1947         printf(" f/%3.1f",(double)ImageInfo.ApertureFNumber);
   1948     }
   1949 
   1950     if (ImageInfo.FocalLength35mmEquiv){
   1951         printf(" f(35)=%dmm",ImageInfo.FocalLength35mmEquiv);
   1952     }
   1953 
   1954     if (ImageInfo.FlashUsed >= 0 && ImageInfo.FlashUsed & 1){
   1955         printf(" (flash)");
   1956     }
   1957 
   1958     if (ImageInfo.IsColor == 0){
   1959         printf(" (bw)");
   1960     }
   1961 
   1962     printf("\n");
   1963 }
   1964