Debian Codegraph @

xbmc/pictures/ExifParse.cpp

raw
1 /*
2 * Copyright (C) 2005-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
8
9 //--------------------------------------------------------------------------
10 // Program to pull the EXIF information out of various types of digital
11 // images and present it in a reasonably consistent way
12 //
13 // Original code pulled from 'jhead' by Matthias Wandel (http://www.sentex.net/~mwandel/) - jhead
14 // Adapted for XBMC by DD.
15 //--------------------------------------------------------------------------
16
17 // Note: Jhead supports TAG_MAKER_NOTE exif field,
18 // but that is omitted for now - to make porting easier and addition smaller
19
20 #include "ExifParse.h"
21
22 #ifdef TARGET_WINDOWS
23 #include <windows.h>
24 #else
25 #include <memory.h>
26 #include <cstring>
27 #endif
28
29 #include <math.h>
30 #include <stdint.h>
31 #include <stdio.h>
32
33 #ifndef min
34 #define min(a,b) (a)>(b)?(b):(a)
35 #endif
36 #ifndef max
37 #define max(a,b) (a)<(b)?(b):(a)
38 #endif
39
40
41 // Prototypes for exif utility functions.
42 static void ErrNonfatal(const char* const msg, int a1, int a2);
43
44 #define DIR_ENTRY_ADDR(Start, Entry) ((Start)+2+12*(Entry))
45
46
47 //--------------------------------------------------------------------------
48 // Describes tag values
49 #define TAG_DESCRIPTION 0x010E
50 #define TAG_MAKE 0x010F
51 #define TAG_MODEL 0x0110
52 #define TAG_ORIENTATION 0x0112
53 #define TAG_X_RESOLUTION 0x011A // Not processed. Format rational64u (see http://search.cpan.org/src/EXIFTOOL/Image-ExifTool-6.76/html/TagNames/EXIF.html)
54 #define TAG_Y_RESOLUTION 0x011B // Not processed. Format rational64u
55 #define TAG_RESOLUTION_UNIT 0x0128 // Not processed. Format int16u. Values: 1-none; 2-inches; 3-cm
56 #define TAG_SOFTWARE 0x0131
57 #define TAG_DATETIME 0x0132
58 #define TAG_THUMBNAIL_OFFSET 0x0201
59 #define TAG_THUMBNAIL_LENGTH 0x0202
60 #define TAG_Y_CB_CR_POS 0x0213 // Not processed. Format int16u. Values: 1-Centered; 2-Co-sited
61 #define TAG_EXPOSURETIME 0x829A
62 #define TAG_FNUMBER 0x829D
63 #define TAG_EXIF_OFFSET 0x8769
64 #define TAG_EXPOSURE_PROGRAM 0x8822
65 #define TAG_GPSINFO 0x8825
66 #define TAG_ISO_EQUIVALENT 0x8827
67 #define TAG_EXIF_VERSION 0x9000 // Not processed.
68 #define TAG_COMPONENT_CFG 0x9101 // Not processed.
69 #define TAG_DATETIME_ORIGINAL 0x9003
70 #define TAG_DATETIME_DIGITIZED 0x9004
71 #define TAG_SHUTTERSPEED 0x9201
72 #define TAG_APERTURE 0x9202
73 #define TAG_EXPOSURE_BIAS 0x9204
74 #define TAG_MAXAPERTURE 0x9205
75 #define TAG_SUBJECT_DISTANCE 0x9206
76 #define TAG_METERING_MODE 0x9207
77 #define TAG_LIGHT_SOURCE 0x9208
78 #define TAG_FLASH 0x9209
79 #define TAG_FOCALLENGTH 0x920A
80 #define TAG_MAKER_NOTE 0x927C // Not processed yet. Maybe in the future.
81 #define TAG_USERCOMMENT 0x9286
82 #define TAG_XP_COMMENT 0x9c9c
83 #define TAG_FLASHPIX_VERSION 0xA000 // Not processed.
84 #define TAG_COLOUR_SPACE 0xA001 // Not processed. Format int16u. Values: 1-RGB; 2-Adobe RGB 65535-Uncalibrated
85 #define TAG_EXIF_IMAGEWIDTH 0xa002
86 #define TAG_EXIF_IMAGELENGTH 0xa003
87 #define TAG_INTEROP_OFFSET 0xa005
88 #define TAG_FOCALPLANEXRES 0xa20E
89 #define TAG_FOCALPLANEUNITS 0xa210
90 #define TAG_EXPOSURE_INDEX 0xa215
91 #define TAG_EXPOSURE_MODE 0xa402
92 #define TAG_WHITEBALANCE 0xa403
93 #define TAG_DIGITALZOOMRATIO 0xA404
94 #define TAG_FOCALLENGTH_35MM 0xa405
95
96 #define TAG_GPS_LAT_REF 1
97 #define TAG_GPS_LAT 2
98 #define TAG_GPS_LONG_REF 3
99 #define TAG_GPS_LONG 4
100 #define TAG_GPS_ALT_REF 5
101 #define TAG_GPS_ALT 6
102
103 //--------------------------------------------------------------------------
104 // Exif format descriptor stuff
105 namespace
106 {
107 constexpr auto FMT_BYTE = 1;
108 [[maybe_unused]] constexpr auto FMT_STRING = 2;
109 constexpr auto FMT_USHORT = 3;
110 constexpr auto FMT_ULONG = 4;
111 constexpr auto FMT_URATIONAL = 5;
112 constexpr auto FMT_SBYTE = 6;
113 [[maybe_unused]] constexpr auto FMT_UNDEFINED = 7;
114 constexpr auto FMT_SSHORT = 8;
115 constexpr auto FMT_SLONG = 9;
116 constexpr auto FMT_SRATIONAL = 10;
117 constexpr auto FMT_SINGLE = 11;
118 constexpr auto FMT_DOUBLE = 12;
119 // NOTE: Remember to change NUM_FORMATS if you define a new format
120 constexpr auto NUM_FORMATS = 12;
121
122 const unsigned int BytesPerFormat[NUM_FORMATS] = {1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
123 } // namespace
124
125 //--------------------------------------------------------------------------
126 // Internationalisation string IDs. The enum order must match that in the
127 // language file (e.g. 'language/resource.language.en_gb/strings.po', and EXIF_PARSE_STRING_ID_BASE
128 // must match the ID of the first Exif string in that file.
129 #define EXIF_PARSE_STRING_ID_BASE 21800
130 enum {
131 // Distance
132 ExifStrDistanceInfinite = EXIF_PARSE_STRING_ID_BASE,
133 // Whitebalance et.al.
134 ExifStrManual,
135 ExifStrAuto,
136 // Flash modes
137 ExifStrYes,
138 ExifStrNo,
139 ExifStrFlashNoStrobe,
140 ExifStrFlashStrobe,
141 ExifStrFlashManual,
142 ExifStrFlashManualNoReturn,
143 ExifStrFlashManualReturn,
144 ExifStrFlashAuto,
145 ExifStrFlashAutoNoReturn,
146 ExifStrFlashAutoReturn,
147 ExifStrFlashRedEye,
148 ExifStrFlashRedEyeNoReturn,
149 ExifStrFlashRedEyeReturn,
150 ExifStrFlashManualRedEye,
151 ExifStrFlashManualRedEyeNoReturn,
152 ExifStrFlashManualRedEyeReturn,
153 ExifStrFlashAutoRedEye,
154 ExifStrFlashAutoRedEyeNoReturn,
155 ExifStrFlashAutoRedEyeReturn,
156 // Light sources
157 ExifStrDaylight,
158 ExifStrFluorescent,
159 ExifStrIncandescent,
160 ExifStrFlash,
161 ExifStrFineWeather,
162 ExifStrShade,
163 // Metering Mode
164 ExifStrMeteringCenter,
165 ExifStrMeteringSpot,
166 ExifStrMeteringMatrix,
167 // Exposure Program
168 ExifStrExposureProgram,
169 ExifStrExposureAperture,
170 ExifStrExposureShutter,
171 ExifStrExposureCreative,
172 ExifStrExposureAction,
173 ExifStrExposurePortrait,
174 ExifStrExposureLandscape,
175 // Exposure mode
176 ExifStrExposureModeAuto,
177 // ISO equivalent
178 ExifStrIsoEquivalent,
179 // GPS latitude, longitude, altitude
180 ExifStrGpsLatitude,
181 ExifStrGpsLongitude,
182 ExifStrGpsAltitude,
183 };
184
185
186
187
188 //--------------------------------------------------------------------------
189 // Report non fatal errors. Now that microsoft.net modifies exif headers,
190 // there's corrupted ones, and there could be more in the future.
191 //--------------------------------------------------------------------------
192 static void ErrNonfatal(const char* const msg, int a1, int a2)
193 {
194 printf("ExifParse - Nonfatal Error : %s %d %d", msg, a1, a2);
195 }
196
197 //--------------------------------------------------------------------------
198 // Convert a 16 bit unsigned value from file's native byte order
199 //--------------------------------------------------------------------------
200 int CExifParse::Get16(const void* const Short, const bool motorolaOrder)
201 {
202 if (motorolaOrder) {
203 return (((const unsigned char *)Short)[0] << 8) | ((const unsigned char *)Short)[1];
204 } else {
205 return (((const unsigned char *)Short)[1] << 8) | ((const unsigned char *)Short)[0];
206 }
207 }
208
209 //--------------------------------------------------------------------------
210 // Convert a 32 bit signed value from file's native byte order
211 //--------------------------------------------------------------------------
212 int CExifParse::Get32(const void* const Long, const bool motorolaOrder)
213 {
214 if (motorolaOrder) {
215 return (((const char *)Long)[0] << 24) | (((const unsigned char *)Long)[1] << 16)
216 | (((const unsigned char *)Long)[2] << 8 ) | (((const unsigned char *)Long)[3] << 0 );
217 } else {
218 return (((const char *)Long)[3] << 24) | (((const unsigned char *)Long)[2] << 16)
219 | (((const unsigned char *)Long)[1] << 8 ) | (((const unsigned char *)Long)[0] << 0 );
220 }
221 }
222
223 //--------------------------------------------------------------------------
224 // It appears that CStdString constructor replaces "\n" with "\r\n" which results
225 // in "\r\r\n" if there already is "\r\n", which in turn results in corrupted
226 // display. So this is an attempt to undo effects of a smart constructor. Also,
227 // replaces all nonprintable characters with "."
228 //--------------------------------------------------------------------------
229 /*void CExifParse::FixComment(CStdString& comment)
230 {
231 comment.Replace("\r\r\n", "\r\n");
232 for (unsigned int i=0; i<comment.length(); i++)
233 {
234 if ((comment[i] < 32) && (comment[i] != '\n') && (comment[i] != '\t') && (comment[i] != '\r'))
235 {
236 comment[i] = '.';
237 }
238 }
239 }*/
240
241 //--------------------------------------------------------------------------
242 // Evaluate number, be it int, rational, or float from directory.
243 //--------------------------------------------------------------------------
244 double CExifParse::ConvertAnyFormat(const void* const ValuePtr, int Format)
245 {
246 double Value;
247 Value = 0;
248
249 switch(Format)
250 {
251 case FMT_SBYTE: Value = *(const signed char*)ValuePtr; break;
252 case FMT_BYTE: Value = *(const unsigned char*)ValuePtr; break;
253
254 case FMT_USHORT: Value = Get16(ValuePtr, m_MotorolaOrder); break;
255 case FMT_ULONG: Value = (unsigned)Get32(ValuePtr, m_MotorolaOrder); break;
256
257 case FMT_URATIONAL:
258 case FMT_SRATIONAL:
259 {
260 int Num,Den;
261 Num = Get32(ValuePtr, m_MotorolaOrder);
262 Den = Get32(4+(const char *)ValuePtr, m_MotorolaOrder);
263
264 if (Den == 0) Value = 0;
265 else Value = (double)Num/Den;
266 }
267 break;
268
269 case FMT_SSHORT: Value = (signed short)Get16(ValuePtr, m_MotorolaOrder); break;
270 case FMT_SLONG: Value = Get32(ValuePtr, m_MotorolaOrder); break;
271
272 // Not sure if this is correct (never seen float used in Exif format)
273 case FMT_SINGLE: Value = (double)*(const float*)ValuePtr; break;
274 case FMT_DOUBLE: Value = *(const double*)ValuePtr; break;
275
276 default:
277 ErrNonfatal("Illegal format code %d",Format,0);
278 }
279 return Value;
280 }
281
282 //--------------------------------------------------------------------------
283 // Exif date tag is stored as a fixed format string "YYYY:MM:DD HH:MM:SS".
284 // If date is not set, then the string is filled with blanks and colons:
285 // " : : : : ". We want this string localised.
286 //--------------------------------------------------------------------------
287 /*void CExifParse::LocaliseDate (void)
288 {
289 if (m_ExifInfo[SLIDESHOW_EXIF_DATE_TIME][0] != ' ')
290 {
291 int year = atoi(m_ExifInfo[SLIDESHOW_EXIF_DATE_TIME].substr(0, 4).c_str());
292 int month = atoi(m_ExifInfo[SLIDESHOW_EXIF_DATE_TIME].substr(5, 2).c_str());
293 int day = atoi(m_ExifInfo[SLIDESHOW_EXIF_DATE_TIME].substr(8, 2).c_str());
294 int hour = atoi(m_ExifInfo[SLIDESHOW_EXIF_DATE_TIME].substr(11,2).c_str());
295 int min = atoi(m_ExifInfo[SLIDESHOW_EXIF_DATE_TIME].substr(14,2).c_str());
296 int sec = atoi(m_ExifInfo[SLIDESHOW_EXIF_DATE_TIME].substr(17,2).c_str());
297 CDateTime date(year, month, day, hour, min, sec);
298 m_ExifInfo[SLIDESHOW_EXIF_DATE_TIME] = date.GetAsLocalizedDateTime();
299 }
300 }*/
301
302
303 //--------------------------------------------------------------------------
304 // Convert exposure time into a human readable format
305 //--------------------------------------------------------------------------
306 /*void CExifParse::GetExposureTime(const float exposureTime, CStdString& outStr)
307 {
308 if (exposureTime)
309 {
310 if (exposureTime < 0.010) outStr.Format("%6.4fs ", exposureTime);
311 else outStr.Format("%5.3fs ", exposureTime);
312 if (exposureTime <= 0.5) outStr.Format("%s (1/%d)", outStr, (int)(0.5 + 1/exposureTime));
313 }
314 }*/
315
316 //--------------------------------------------------------------------------
317 // Process one of the nested EXIF directories.
318 //--------------------------------------------------------------------------
319 void CExifParse::ProcessDir(const unsigned char* const DirStart,
320 const unsigned char* const OffsetBase,
321 const unsigned ExifLength,
322 int NestingLevel)
323 {
324 if (NestingLevel > 4)
325 {
326 ErrNonfatal("Maximum directory nesting exceeded (corrupt exif header)", 0,0);
327 return;
328 }
329
330 char IndentString[25];
331 memset(IndentString, ' ', 25);
332 IndentString[NestingLevel * 4] = '\0';
333
334
335 int NumDirEntries = Get16((const void*)DirStart, m_MotorolaOrder);
336
337 const unsigned char* const DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries);
338 if (DirEnd+4 > (OffsetBase+ExifLength))
339 {
340 if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength)
341 {
342 // Version 1.3 of jhead would truncate a bit too much.
343 // This also caught later on as well.
344 }
345 else
346 {
347 ErrNonfatal("Illegally sized directory", 0,0);
348 return;
349 }
350 }
351
352 for (int de=0;de<NumDirEntries;de++)
353 {
354 int Tag, Format, Components;
355 unsigned char* ValuePtr;
356 int ByteCount;
357 const unsigned char* const DirEntry = DIR_ENTRY_ADDR(DirStart, de);
358
359 Tag = Get16(DirEntry, m_MotorolaOrder);
360 Format = Get16(DirEntry+2, m_MotorolaOrder);
361 Components = Get32(DirEntry+4, m_MotorolaOrder);
362
363 if (Format <= 0 || Format > NUM_FORMATS)
364 {
365 ErrNonfatal("Illegal number format %d for tag %04x", Format, Tag);
366 continue;
367 }
368
369 if ((unsigned)Components > 0x10000)
370 {
371 ErrNonfatal("Illegal number of components %d for tag %04x", Components, Tag);
372 continue;
373 }
374
375 ByteCount = Components * BytesPerFormat[Format - 1];
376
377 if (ByteCount > 4)
378 {
379 unsigned OffsetVal;
380 OffsetVal = (unsigned)Get32(DirEntry+8, m_MotorolaOrder);
381 // If its bigger than 4 bytes, the dir entry contains an offset.
382 if (OffsetVal > UINT32_MAX - ByteCount || OffsetVal + ByteCount > ExifLength)
383 {
384 // Bogus pointer offset and / or bytecount value
385 ErrNonfatal("Illegal value pointer for tag %04x", Tag,0);
386 continue;
387 }
388 ValuePtr = (unsigned char*)(const_cast<unsigned char*>(OffsetBase)+OffsetVal);
389
390 if (OffsetVal > m_LargestExifOffset)
391 {
392 m_LargestExifOffset = OffsetVal;
393 }
394
395 }
396 else {
397 // 4 bytes or less and value is in the dir entry itself
398 ValuePtr = (unsigned char*)(const_cast<unsigned char*>(DirEntry)+8);
399 }
400
401
402 // Extract useful components of tag
403 switch(Tag)
404 {
405 case TAG_DESCRIPTION:
406 {
407 int length = max(ByteCount, 0);
408 length = min(length, MAX_COMMENT);
409 strncpy(m_ExifInfo->Description, (char *)ValuePtr, length);
410 m_ExifInfo->Description[length] = '\0';
411 break;
412 }
413 case TAG_MAKE:
414 {
415 int space = sizeof(m_ExifInfo->CameraMake);
416 if (space > 0)
417 {
418 strncpy(m_ExifInfo->CameraMake, (char *)ValuePtr, space - 1);
419 m_ExifInfo->CameraMake[space - 1] = '\0';
420 }
421 break;
422 }
423 case TAG_MODEL:
424 {
425 int space = sizeof(m_ExifInfo->CameraModel);
426 if (space > 0)
427 {
428 strncpy(m_ExifInfo->CameraModel, (char *)ValuePtr, space - 1);
429 m_ExifInfo->CameraModel[space - 1] = '\0';
430 }
431 break;
432 }
433 // case TAG_SOFTWARE: strncpy(m_ExifInfo->Software, ValuePtr, 5); break;
434 case TAG_FOCALPLANEXRES: m_FocalPlaneXRes = ConvertAnyFormat(ValuePtr, Format); break;
435 case TAG_THUMBNAIL_OFFSET: m_ExifInfo->ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format); break;
436 case TAG_THUMBNAIL_LENGTH: m_ExifInfo->ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format); break;
437
438 case TAG_MAKER_NOTE:
439 continue;
440 break;
441
442 case TAG_DATETIME_ORIGINAL:
443 {
444
445 int space = sizeof(m_ExifInfo->DateTime);
446 if (space > 0)
447 {
448 strncpy(m_ExifInfo->DateTime, (char *)ValuePtr, space - 1);
449 m_ExifInfo->DateTime[space - 1] = '\0';
450 // If we get a DATETIME_ORIGINAL, we use that one.
451 m_DateFound = true;
452 }
453 break;
454 }
455 case TAG_DATETIME_DIGITIZED:
456 case TAG_DATETIME:
457 {
458 if (!m_DateFound)
459 {
460 // If we don't already have a DATETIME_ORIGINAL, use whatever
461 // time fields we may have.
462 int space = sizeof(m_ExifInfo->DateTime);
463 if (space > 0)
464 {
465 strncpy(m_ExifInfo->DateTime, (char *)ValuePtr, space - 1);
466 m_ExifInfo->DateTime[space - 1] = '\0';
467 }
468 }
469 break;
470 }
471 case TAG_USERCOMMENT:
472 {
473 // The UserComment allows comments without the charset limitations of ImageDescription.
474 // Therefore the UserComment field is prefixed by a CharacterCode field (8 Byte):
475 // - ASCII: 'ASCII\0\0\0'
476 // - Unicode: 'UNICODE\0'
477 // - JIS X208-1990: 'JIS\0\0\0\0\0'
478 // - Unknown: '\0\0\0\0\0\0\0\0' (application specific)
479
480 m_ExifInfo->CommentsCharset = EXIF_COMMENT_CHARSET_UNKNOWN;
481
482 const int EXIF_COMMENT_CHARSET_LENGTH = 8;
483 if (ByteCount >= EXIF_COMMENT_CHARSET_LENGTH)
484 {
485 // As some implementations use spaces instead of \0 for the padding,
486 // we're not so strict and check only the prefix.
487 if (memcmp(ValuePtr, "ASCII", 5) == 0)
488 m_ExifInfo->CommentsCharset = EXIF_COMMENT_CHARSET_ASCII;
489 else if (memcmp(ValuePtr, "UNICODE", 7) == 0)
490 m_ExifInfo->CommentsCharset = EXIF_COMMENT_CHARSET_UNICODE;
491 else if (memcmp(ValuePtr, "JIS", 3) == 0)
492 m_ExifInfo->CommentsCharset = EXIF_COMMENT_CHARSET_JIS;
493
494 int length = ByteCount - EXIF_COMMENT_CHARSET_LENGTH;
495 length = min(length, MAX_COMMENT);
496 memcpy(m_ExifInfo->Comments, ValuePtr + EXIF_COMMENT_CHARSET_LENGTH, length);
497 m_ExifInfo->Comments[length] = '\0';
498 // FixComment(comment); // Ensure comment is printable
499 }
500 }
501 break;
502
503 case TAG_XP_COMMENT:
504 {
505 // The XP user comment field is always unicode (UCS-2) encoded
506 m_ExifInfo->XPCommentsCharset = EXIF_COMMENT_CHARSET_UNICODE;
507 size_t length = min(ByteCount, MAX_COMMENT);
508 memcpy(m_ExifInfo->XPComment, ValuePtr, length);
509 m_ExifInfo->XPComment[length] = '\0';
510 }
511 break;
512
513 case TAG_FNUMBER:
514 // Simplest way of expressing aperture, so I trust it the most.
515 // (overwrite previously computd value if there is one)
516 m_ExifInfo->ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format);
517 break;
518
519 case TAG_APERTURE:
520 case TAG_MAXAPERTURE:
521 // More relevant info always comes earlier, so only use this field if we don't
522 // have appropriate aperture information yet.
523 if (m_ExifInfo->ApertureFNumber == 0)
524 {
525 m_ExifInfo->ApertureFNumber = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2.0)*0.5);
526 }
527 break;
528
529 case TAG_FOCALLENGTH:
530 // Nice digital cameras actually save the focal length as a function
531 // of how far they are zoomed in.
532 m_ExifInfo->FocalLength = (float)ConvertAnyFormat(ValuePtr, Format);
533 break;
534
535 case TAG_SUBJECT_DISTANCE:
536 // Inidcates the distacne the autofocus camera is focused to.
537 // Tends to be less accurate as distance increases.
538 {
539 float distance = (float)ConvertAnyFormat(ValuePtr, Format);
540 m_ExifInfo->Distance = distance;
541 }
542 break;
543
544 case TAG_EXPOSURETIME:
545 {
546 // Simplest way of expressing exposure time, so I trust it most.
547 // (overwrite previously computd value if there is one)
548 float expTime = (float)ConvertAnyFormat(ValuePtr, Format);
549 if (expTime)
550 m_ExifInfo->ExposureTime = expTime;
551 }
552 break;
553
554 case TAG_SHUTTERSPEED:
555 // More complicated way of expressing exposure time, so only use
556 // this value if we don't already have it from somewhere else.
557 if (m_ExifInfo->ExposureTime == 0)
558 {
559 m_ExifInfo->ExposureTime = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2.0)));
560 }
561 break;
562
563 case TAG_FLASH:
564 m_ExifInfo->FlashUsed = (int)ConvertAnyFormat(ValuePtr, Format);
565 break;
566
567 case TAG_ORIENTATION:
568 m_ExifInfo->Orientation = (int)ConvertAnyFormat(ValuePtr, Format);
569 if (m_ExifInfo->Orientation < 0 || m_ExifInfo->Orientation > 8)
570 {
571 ErrNonfatal("Undefined rotation value %d", m_ExifInfo->Orientation, 0);
572 m_ExifInfo->Orientation = 0;
573 }
574 break;
575
576 case TAG_EXIF_IMAGELENGTH:
577 case TAG_EXIF_IMAGEWIDTH:
578 // Use largest of height and width to deal with images that have been
579 // rotated to portrait format.
580 {
581 int a = (int)ConvertAnyFormat(ValuePtr, Format);
582 if (m_ExifImageWidth < a) m_ExifImageWidth = a;
583 }
584 break;
585
586 case TAG_FOCALPLANEUNITS:
587 switch((int)ConvertAnyFormat(ValuePtr, Format))
588 {
589 // According to the information I was using, 2 means meters.
590 // But looking at the Cannon powershot's files, inches is the only
591 // sensible value.
592 case 1: m_FocalPlaneUnits = 25.4; break; // inch
593 case 2: m_FocalPlaneUnits = 25.4; break;
594 case 3: m_FocalPlaneUnits = 10; break; // centimeter
595 case 4: m_FocalPlaneUnits = 1; break; // millimeter
596 case 5: m_FocalPlaneUnits = .001; break; // micrometer
597 }
598 break;
599
600 case TAG_EXPOSURE_BIAS:
601 m_ExifInfo->ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format);
602 break;
603
604 case TAG_WHITEBALANCE:
605 m_ExifInfo->Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format);
606 break;
607
608 case TAG_LIGHT_SOURCE:
609 //Quercus: 17-1-2004 Added LightSource, some cams return this, whitebalance or both
610 m_ExifInfo->LightSource = (int)ConvertAnyFormat(ValuePtr, Format);
611 break;
612
613 case TAG_METERING_MODE:
614 m_ExifInfo->MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format);
615 break;
616
617 case TAG_EXPOSURE_PROGRAM:
618 m_ExifInfo->ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format);
619 break;
620
621 case TAG_EXPOSURE_INDEX:
622 if (m_ExifInfo->ISOequivalent == 0)
623 {
624 // Exposure index and ISO equivalent are often used interchangeably,
625 // so we will do the same.
626 // http://photography.about.com/library/glossary/bldef_ei.htm
627 m_ExifInfo->ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
628 }
629 break;
630
631 case TAG_ISO_EQUIVALENT:
632 m_ExifInfo->ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
633 if (m_ExifInfo->ISOequivalent < 50)
634 m_ExifInfo->ISOequivalent *= 200; // Fixes strange encoding on some older digicams.
635 break;
636
637 case TAG_EXPOSURE_MODE:
638 m_ExifInfo->ExposureMode = (int)ConvertAnyFormat(ValuePtr, Format);
639 break;
640
641 case TAG_DIGITALZOOMRATIO:
642 m_ExifInfo->DigitalZoomRatio = (float)ConvertAnyFormat(ValuePtr, Format);
643 break;
644
645 case TAG_EXIF_OFFSET:
646 case TAG_INTEROP_OFFSET:
647 {
648 const unsigned char* const SubdirStart = OffsetBase + (unsigned)Get32(ValuePtr, m_MotorolaOrder);
649 if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength)
650 {
651 ErrNonfatal("Illegal exif or interop ofset directory link",0,0);
652 }
653 else
654 {
655 ProcessDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
656 }
657 continue;
658 }
659 break;
660
661 case TAG_GPSINFO:
662 {
663 const unsigned char* const SubdirStart = OffsetBase + (unsigned)Get32(ValuePtr, m_MotorolaOrder);
664 if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength)
665 {
666 ErrNonfatal("Illegal GPS directory link",0,0);
667 }
668 else
669 {
670 ProcessGpsInfo(SubdirStart, ByteCount, OffsetBase, ExifLength);
671 }
672 continue;
673 }
674 break;
675
676 case TAG_FOCALLENGTH_35MM:
677 // The focal length equivalent 35 mm is a 2.2 tag (defined as of April 2002)
678 // if its present, use it to compute equivalent focal length instead of
679 // computing it from sensor geometry and actual focal length.
680 m_ExifInfo->FocalLength35mmEquiv = (unsigned)ConvertAnyFormat(ValuePtr, Format);
681 break;
682 }
683 }
684
685
686 // In addition to linking to subdirectories via exif tags,
687 // there's also a potential link to another directory at the end of each
688 // directory. this has got to be the result of a committee!
689 unsigned Offset;
690
691 if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength)
692 {
693 Offset = (unsigned)Get32(DirStart+2+12*NumDirEntries, m_MotorolaOrder);
694 if (Offset)
695 {
696 const unsigned char* const SubdirStart = OffsetBase + Offset;
697 if (SubdirStart > OffsetBase+ExifLength || SubdirStart < OffsetBase)
698 {
699 if (SubdirStart > OffsetBase && SubdirStart < OffsetBase+ExifLength+20)
700 {
701 // Jhead 1.3 or earlier would crop the whole directory!
702 // As Jhead produces this form of format incorrectness,
703 // I'll just let it pass silently
704 }
705 else
706 {
707 ErrNonfatal("Illegal subdirectory link",0,0);
708 }
709 }
710 else
711 {
712 if (SubdirStart <= OffsetBase+ExifLength)
713 {
714 ProcessDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
715 }
716 }
717 if (Offset > m_LargestExifOffset)
718 {
719 m_LargestExifOffset = Offset;
720 }
721 }
722 }
723 else
724 {
725 // The exif header ends before the last next directory pointer.
726 }
727
728 if (m_ExifInfo->ThumbnailOffset)
729 {
730 m_ExifInfo->ThumbnailAtEnd = false;
731
732 if (m_ExifInfo->ThumbnailOffset <= ExifLength)
733 {
734 if (m_ExifInfo->ThumbnailSize > ExifLength - m_ExifInfo->ThumbnailOffset)
735 {
736 // If thumbnail extends past exif header, only save the part that
737 // actually exists. Canon's EOS viewer utility will do this - the
738 // thumbnail extracts ok with this hack.
739 m_ExifInfo->ThumbnailSize = ExifLength - m_ExifInfo->ThumbnailOffset;
740 }
741 }
742 }
743 }
744
745
746 //--------------------------------------------------------------------------
747 // Process a EXIF marker
748 // Describes all the drivel that most digital cameras include...
749 //--------------------------------------------------------------------------
750 bool CExifParse::Process (const unsigned char* const ExifSection, const unsigned short length, ExifInfo_t *info)
751 {
752 m_ExifInfo = info;
753 // EXIF signature: "Exif\0\0"
754 // Check EXIF signatures
755 const char ExifHeader[] = "Exif\0\0";
756 const char ExifAlignment0[] = "II";
757 const char ExifAlignment1[] = "MM";
758 const char ExifExtra = 0x2a;
759
760 const char* pos = (const char*)(ExifSection + sizeof(short)); // position data pointer after length field
761
762 if (memcmp(pos, ExifHeader,6))
763 {
764 printf("ExifParse: incorrect Exif header");
765 return false;
766 }
767 pos += 6;
768
769 if (memcmp(pos, ExifAlignment0, strlen(ExifAlignment0)) == 0)
770 {
771 m_MotorolaOrder = false;
772 }
773 else if (memcmp(pos, ExifAlignment1, strlen(ExifAlignment1)) == 0)
774 {
775 m_MotorolaOrder = true;
776 }
777 else
778 {
779 printf("ExifParse: invalid Exif alignment marker");
780 return false;
781 }
782 pos += strlen(ExifAlignment0);
783
784 // Check the next value for correctness.
785 if (Get16((const void*)(pos), m_MotorolaOrder) != ExifExtra)
786 {
787 printf("ExifParse: invalid Exif start (1)");
788 return false;
789 }
790 pos += sizeof(short);
791
792 unsigned long FirstOffset = (unsigned)Get32((const void*)pos, m_MotorolaOrder);
793 if (FirstOffset < 8 || FirstOffset + 8 >= length)
794 {
795 ErrNonfatal("Invalid offset of first IFD value: %u", FirstOffset, 0);
796 return false;
797 }
798
799
800
801 // First directory starts 16 bytes in. All offset are relative to 8 bytes in.
802 ProcessDir(ExifSection+8+FirstOffset, ExifSection+8, length-8, 0);
803
804 m_ExifInfo->ThumbnailAtEnd = m_ExifInfo->ThumbnailOffset >= m_LargestExifOffset;
805
806 // Compute the CCD width, in millimeters.
807 if (m_FocalPlaneXRes != 0)
808 {
809 // Note: With some cameras, its not possible to compute this correctly because
810 // they don't adjust the indicated focal plane resolution units when using less
811 // than maximum resolution, so the CCDWidth value comes out too small. Nothing
812 // that Jhead can do about it - its a camera problem.
813 m_ExifInfo->CCDWidth = (float)(m_ExifImageWidth * m_FocalPlaneUnits / m_FocalPlaneXRes);
814 }
815
816 if (m_ExifInfo->FocalLength)
817 {
818 if (m_ExifInfo->FocalLength35mmEquiv == 0)
819 {
820 // Compute 35 mm equivalent focal length based on sensor geometry if we haven't
821 // already got it explicitly from a tag.
822 if (m_ExifInfo->CCDWidth != 0.0f)
823 {
824 m_ExifInfo->FocalLength35mmEquiv =
825 (int)(m_ExifInfo->FocalLength / m_ExifInfo->CCDWidth * 36 + 0.5f);
826 }
827 }
828 }
829 return true;
830 }
831
832
833
834 //--------------------------------------------------------------------------
835 // GPS Lat/Long extraction helper function
836 //--------------------------------------------------------------------------
837 void CExifParse::GetLatLong(
838 const unsigned int Format,
839 const unsigned char* ValuePtr,
840 const int ComponentSize,
841 char *latLongString)
842 {
843 if (Format != FMT_URATIONAL)
844 {
845 ErrNonfatal("Illegal number format %d for GPS Lat/Long", Format, 0);
846 }
847 else
848 {
849 double Values[3];
850 for (unsigned a=0; a<3 ;a++)
851 {
852 Values[a] = ConvertAnyFormat(ValuePtr+a*ComponentSize, Format);
853 }
854 if (Values[0] < 0 || Values[0] > 180 || Values[1] < 0 || Values[1] >= 60 || Values[2] < 0 || Values[2] >= 60)
855 {
856 // Ignore invalid values (DMS format expected)
857 ErrNonfatal("Invalid Lat/Long value", 0, 0);
858 latLongString[0] = 0;
859 }
860 else
861 {
862 char latLong[30];
863 snprintf(latLong, sizeof(latLong), "%3.0fd %2.0f' %5.2f\"", Values[0], Values[1], Values[2]);
864 strcat(latLongString, latLong);
865 }
866 }
867 }
868
869 //--------------------------------------------------------------------------
870 // Process GPS info directory
871 //--------------------------------------------------------------------------
872 void CExifParse::ProcessGpsInfo(
873 const unsigned char* const DirStart,
874 int ByteCountUnused,
875 const unsigned char* const OffsetBase,
876 unsigned ExifLength)
877 {
878 int NumDirEntries = Get16(DirStart, m_MotorolaOrder);
879
880 for (int de=0;de<NumDirEntries;de++)
881 {
882 const unsigned char* DirEntry = DIR_ENTRY_ADDR(DirStart, de);
883
884 // Fix from aosp 34a2564d3268a5ca1472c5076675782fbaf724d6
885 if (DirEntry + 12 > OffsetBase + ExifLength)
886 {
887 ErrNonfatal("GPS info directory goes past end of exif", 0, 0);
888 return;
889 }
890
891 unsigned Tag = Get16(DirEntry, m_MotorolaOrder);
892 unsigned Format = Get16(DirEntry+2, m_MotorolaOrder);
893 unsigned Components = (unsigned)Get32(DirEntry+4, m_MotorolaOrder);
894 if (Format == 0 || Format > NUM_FORMATS)
895 {
896 ErrNonfatal("Illegal number format %d for tag %04x", Format, Tag);
897 continue;
898 }
899
900 unsigned ComponentSize = BytesPerFormat[Format - 1];
901 unsigned ByteCount = Components * ComponentSize;
902
903 const unsigned char* ValuePtr;
904
905 if (ByteCount > 4)
906 {
907 unsigned OffsetVal = (unsigned)Get32(DirEntry+8, m_MotorolaOrder);
908 // If its bigger than 4 bytes, the dir entry contains an offset.
909 if (OffsetVal > UINT32_MAX - ByteCount || OffsetVal + ByteCount > ExifLength)
910 {
911 // Bogus pointer offset and / or bytecount value
912 ErrNonfatal("Illegal value pointer for tag %04x", Tag,0);
913 continue;
914 }
915 ValuePtr = OffsetBase+OffsetVal;
916 }
917 else
918 {
919 // 4 bytes or less and value is in the dir entry itself
920 ValuePtr = DirEntry+8;
921 }
922
923 switch(Tag)
924 {
925 case TAG_GPS_LAT_REF:
926 m_ExifInfo->GpsLat[0] = ValuePtr[0];
927 m_ExifInfo->GpsLat[1] = 0;
928 break;
929
930 case TAG_GPS_LONG_REF:
931 m_ExifInfo->GpsLong[0] = ValuePtr[0];
932 m_ExifInfo->GpsLong[1] = 0;
933 break;
934
935 case TAG_GPS_LAT:
936 GetLatLong(Format, ValuePtr, ComponentSize, m_ExifInfo->GpsLat);
937 break;
938 case TAG_GPS_LONG:
939 GetLatLong(Format, ValuePtr, ComponentSize, m_ExifInfo->GpsLong);
940 break;
941
942 case TAG_GPS_ALT_REF:
943 if (ValuePtr[0] != 0)
944 m_ExifInfo->GpsAlt[0] = '-';
945 m_ExifInfo->GpsAlt[1] = 0;
946 break;
947
948 case TAG_GPS_ALT:
949 {
950 char temp[18];
951 snprintf(temp, sizeof(temp), "%.2fm",
952 static_cast<double>(ConvertAnyFormat(ValuePtr, Format)));
953 strcat(m_ExifInfo->GpsAlt, temp);
954 }
955 break;
956 }
957 }
958 }
959