ExifInterface.java revision 65207118371a4a70e4c3d06a211b69edf2e2dfb3
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.media;
18
19import android.annotation.NonNull;
20import android.content.res.AssetManager;
21import android.graphics.Bitmap;
22import android.graphics.BitmapFactory;
23import android.system.ErrnoException;
24import android.system.Os;
25import android.system.OsConstants;
26import android.util.Log;
27import android.util.Pair;
28import android.annotation.IntDef;
29
30import java.io.BufferedInputStream;
31import java.io.ByteArrayInputStream;
32import java.io.DataInputStream;
33import java.io.DataInput;
34import java.io.EOFException;
35import java.io.File;
36import java.io.FileDescriptor;
37import java.io.FileInputStream;
38import java.io.FileNotFoundException;
39import java.io.FileOutputStream;
40import java.io.FilterOutputStream;
41import java.io.IOException;
42import java.io.InputStream;
43import java.io.OutputStream;
44import java.nio.ByteBuffer;
45import java.nio.ByteOrder;
46import java.nio.charset.Charset;
47import java.nio.charset.StandardCharsets;
48import java.text.ParsePosition;
49import java.text.SimpleDateFormat;
50import java.util.Arrays;
51import java.util.LinkedList;
52import java.util.Date;
53import java.util.HashMap;
54import java.util.HashSet;
55import java.util.Map;
56import java.util.Set;
57import java.util.TimeZone;
58import java.util.regex.Matcher;
59import java.util.regex.Pattern;
60import java.lang.annotation.Retention;
61import java.lang.annotation.RetentionPolicy;
62
63import libcore.io.IoUtils;
64import libcore.io.Streams;
65
66/**
67 * This is a class for reading and writing Exif tags in a JPEG file or a RAW image file.
68 * <p>
69 * Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW and RAF.
70 * <p>
71 * Attribute mutation is supported for JPEG image files.
72 */
73public class ExifInterface {
74    private static final String TAG = "ExifInterface";
75    private static final boolean DEBUG = false;
76
77    // The Exif tag names. See Tiff 6.0 Section 3 and Section 8.
78    /** Type is String. */
79    public static final String TAG_ARTIST = "Artist";
80    /** Type is int. */
81    public static final String TAG_BITS_PER_SAMPLE = "BitsPerSample";
82    /** Type is int. */
83    public static final String TAG_COMPRESSION = "Compression";
84    /** Type is String. */
85    public static final String TAG_COPYRIGHT = "Copyright";
86    /** Type is String. */
87    public static final String TAG_DATETIME = "DateTime";
88    /** Type is String. */
89    public static final String TAG_IMAGE_DESCRIPTION = "ImageDescription";
90    /** Type is int. */
91    public static final String TAG_IMAGE_LENGTH = "ImageLength";
92    /** Type is int. */
93    public static final String TAG_IMAGE_WIDTH = "ImageWidth";
94    /** Type is int. */
95    public static final String TAG_JPEG_INTERCHANGE_FORMAT = "JPEGInterchangeFormat";
96    /** Type is int. */
97    public static final String TAG_JPEG_INTERCHANGE_FORMAT_LENGTH = "JPEGInterchangeFormatLength";
98    /** Type is String. */
99    public static final String TAG_MAKE = "Make";
100    /** Type is String. */
101    public static final String TAG_MODEL = "Model";
102    /** Type is int. */
103    public static final String TAG_ORIENTATION = "Orientation";
104    /** Type is int. */
105    public static final String TAG_PHOTOMETRIC_INTERPRETATION = "PhotometricInterpretation";
106    /** Type is int. */
107    public static final String TAG_PLANAR_CONFIGURATION = "PlanarConfiguration";
108    /** Type is rational. */
109    public static final String TAG_PRIMARY_CHROMATICITIES = "PrimaryChromaticities";
110    /** Type is rational. */
111    public static final String TAG_REFERENCE_BLACK_WHITE = "ReferenceBlackWhite";
112    /** Type is int. */
113    public static final String TAG_RESOLUTION_UNIT = "ResolutionUnit";
114    /** Type is int. */
115    public static final String TAG_ROWS_PER_STRIP = "RowsPerStrip";
116    /** Type is int. */
117    public static final String TAG_SAMPLES_PER_PIXEL = "SamplesPerPixel";
118    /** Type is String. */
119    public static final String TAG_SOFTWARE = "Software";
120    /** Type is int. */
121    public static final String TAG_STRIP_BYTE_COUNTS = "StripByteCounts";
122    /** Type is int. */
123    public static final String TAG_STRIP_OFFSETS = "StripOffsets";
124    /** Type is int. */
125    public static final String TAG_TRANSFER_FUNCTION = "TransferFunction";
126    /** Type is rational. */
127    public static final String TAG_WHITE_POINT = "WhitePoint";
128    /** Type is rational. */
129    public static final String TAG_X_RESOLUTION = "XResolution";
130    /** Type is rational. */
131    public static final String TAG_Y_CB_CR_COEFFICIENTS = "YCbCrCoefficients";
132    /** Type is int. */
133    public static final String TAG_Y_CB_CR_POSITIONING = "YCbCrPositioning";
134    /** Type is int. */
135    public static final String TAG_Y_CB_CR_SUB_SAMPLING = "YCbCrSubSampling";
136    /** Type is rational. */
137    public static final String TAG_Y_RESOLUTION = "YResolution";
138    /** Type is rational. */
139    public static final String TAG_APERTURE_VALUE = "ApertureValue";
140    /** Type is rational. */
141    public static final String TAG_BRIGHTNESS_VALUE = "BrightnessValue";
142    /** Type is String. */
143    public static final String TAG_CFA_PATTERN = "CFAPattern";
144    /** Type is int. */
145    public static final String TAG_COLOR_SPACE = "ColorSpace";
146    /** Type is String. */
147    public static final String TAG_COMPONENTS_CONFIGURATION = "ComponentsConfiguration";
148    /** Type is rational. */
149    public static final String TAG_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel";
150    /** Type is int. */
151    public static final String TAG_CONTRAST = "Contrast";
152    /** Type is int. */
153    public static final String TAG_CUSTOM_RENDERED = "CustomRendered";
154    /** Type is String. */
155    public static final String TAG_DATETIME_DIGITIZED = "DateTimeDigitized";
156    /** Type is String. */
157    public static final String TAG_DATETIME_ORIGINAL = "DateTimeOriginal";
158    /** Type is String. */
159    public static final String TAG_DEVICE_SETTING_DESCRIPTION = "DeviceSettingDescription";
160    /** Type is double. */
161    public static final String TAG_DIGITAL_ZOOM_RATIO = "DigitalZoomRatio";
162    /** Type is String. */
163    public static final String TAG_EXIF_VERSION = "ExifVersion";
164    /** Type is double. */
165    public static final String TAG_EXPOSURE_BIAS_VALUE = "ExposureBiasValue";
166    /** Type is rational. */
167    public static final String TAG_EXPOSURE_INDEX = "ExposureIndex";
168    /** Type is int. */
169    public static final String TAG_EXPOSURE_MODE = "ExposureMode";
170    /** Type is int. */
171    public static final String TAG_EXPOSURE_PROGRAM = "ExposureProgram";
172    /** Type is double. */
173    public static final String TAG_EXPOSURE_TIME = "ExposureTime";
174    /** Type is double. */
175    public static final String TAG_F_NUMBER = "FNumber";
176    /**
177     * Type is double.
178     *
179     * @deprecated use {@link #TAG_F_NUMBER} instead
180     */
181    @Deprecated
182    public static final String TAG_APERTURE = "FNumber";
183    /** Type is String. */
184    public static final String TAG_FILE_SOURCE = "FileSource";
185    /** Type is int. */
186    public static final String TAG_FLASH = "Flash";
187    /** Type is rational. */
188    public static final String TAG_FLASH_ENERGY = "FlashEnergy";
189    /** Type is String. */
190    public static final String TAG_FLASHPIX_VERSION = "FlashpixVersion";
191    /** Type is rational. */
192    public static final String TAG_FOCAL_LENGTH = "FocalLength";
193    /** Type is int. */
194    public static final String TAG_FOCAL_LENGTH_IN_35MM_FILM = "FocalLengthIn35mmFilm";
195    /** Type is int. */
196    public static final String TAG_FOCAL_PLANE_RESOLUTION_UNIT = "FocalPlaneResolutionUnit";
197    /** Type is rational. */
198    public static final String TAG_FOCAL_PLANE_X_RESOLUTION = "FocalPlaneXResolution";
199    /** Type is rational. */
200    public static final String TAG_FOCAL_PLANE_Y_RESOLUTION = "FocalPlaneYResolution";
201    /** Type is int. */
202    public static final String TAG_GAIN_CONTROL = "GainControl";
203    /** Type is int. */
204    public static final String TAG_ISO_SPEED_RATINGS = "ISOSpeedRatings";
205    /**
206     * Type is int.
207     *
208     * @deprecated use {@link #TAG_ISO_SPEED_RATINGS} instead
209     */
210    @Deprecated
211    public static final String TAG_ISO = "ISOSpeedRatings";
212    /** Type is String. */
213    public static final String TAG_IMAGE_UNIQUE_ID = "ImageUniqueID";
214    /** Type is int. */
215    public static final String TAG_LIGHT_SOURCE = "LightSource";
216    /** Type is String. */
217    public static final String TAG_MAKER_NOTE = "MakerNote";
218    /** Type is rational. */
219    public static final String TAG_MAX_APERTURE_VALUE = "MaxApertureValue";
220    /** Type is int. */
221    public static final String TAG_METERING_MODE = "MeteringMode";
222    /** Type is int. */
223    public static final String TAG_NEW_SUBFILE_TYPE = "NewSubfileType";
224    /** Type is String. */
225    public static final String TAG_OECF = "OECF";
226    /** Type is int. */
227    public static final String TAG_PIXEL_X_DIMENSION = "PixelXDimension";
228    /** Type is int. */
229    public static final String TAG_PIXEL_Y_DIMENSION = "PixelYDimension";
230    /** Type is String. */
231    public static final String TAG_RELATED_SOUND_FILE = "RelatedSoundFile";
232    /** Type is int. */
233    public static final String TAG_SATURATION = "Saturation";
234    /** Type is int. */
235    public static final String TAG_SCENE_CAPTURE_TYPE = "SceneCaptureType";
236    /** Type is String. */
237    public static final String TAG_SCENE_TYPE = "SceneType";
238    /** Type is int. */
239    public static final String TAG_SENSING_METHOD = "SensingMethod";
240    /** Type is int. */
241    public static final String TAG_SHARPNESS = "Sharpness";
242    /** Type is rational. */
243    public static final String TAG_SHUTTER_SPEED_VALUE = "ShutterSpeedValue";
244    /** Type is String. */
245    public static final String TAG_SPATIAL_FREQUENCY_RESPONSE = "SpatialFrequencyResponse";
246    /** Type is String. */
247    public static final String TAG_SPECTRAL_SENSITIVITY = "SpectralSensitivity";
248    /** Type is int. */
249    public static final String TAG_SUBFILE_TYPE = "SubfileType";
250    /** Type is String. */
251    public static final String TAG_SUBSEC_TIME = "SubSecTime";
252    /**
253     * Type is String.
254     *
255     * @deprecated use {@link #TAG_SUBSEC_TIME_DIGITIZED} instead
256     */
257    public static final String TAG_SUBSEC_TIME_DIG = "SubSecTimeDigitized";
258    /** Type is String. */
259    public static final String TAG_SUBSEC_TIME_DIGITIZED = "SubSecTimeDigitized";
260    /**
261     * Type is String.
262     *
263     * @deprecated use {@link #TAG_SUBSEC_TIME_ORIGINAL} instead
264     */
265    public static final String TAG_SUBSEC_TIME_ORIG = "SubSecTimeOriginal";
266    /** Type is String. */
267    public static final String TAG_SUBSEC_TIME_ORIGINAL = "SubSecTimeOriginal";
268    /** Type is int. */
269    public static final String TAG_SUBJECT_AREA = "SubjectArea";
270    /** Type is double. */
271    public static final String TAG_SUBJECT_DISTANCE = "SubjectDistance";
272    /** Type is int. */
273    public static final String TAG_SUBJECT_DISTANCE_RANGE = "SubjectDistanceRange";
274    /** Type is int. */
275    public static final String TAG_SUBJECT_LOCATION = "SubjectLocation";
276    /** Type is String. */
277    public static final String TAG_USER_COMMENT = "UserComment";
278    /** Type is int. */
279    public static final String TAG_WHITE_BALANCE = "WhiteBalance";
280    /**
281     * The altitude (in meters) based on the reference in TAG_GPS_ALTITUDE_REF.
282     * Type is rational.
283     */
284    public static final String TAG_GPS_ALTITUDE = "GPSAltitude";
285    /**
286     * 0 if the altitude is above sea level. 1 if the altitude is below sea
287     * level. Type is int.
288     */
289    public static final String TAG_GPS_ALTITUDE_REF = "GPSAltitudeRef";
290    /** Type is String. */
291    public static final String TAG_GPS_AREA_INFORMATION = "GPSAreaInformation";
292    /** Type is rational. */
293    public static final String TAG_GPS_DOP = "GPSDOP";
294    /** Type is String. */
295    public static final String TAG_GPS_DATESTAMP = "GPSDateStamp";
296    /** Type is rational. */
297    public static final String TAG_GPS_DEST_BEARING = "GPSDestBearing";
298    /** Type is String. */
299    public static final String TAG_GPS_DEST_BEARING_REF = "GPSDestBearingRef";
300    /** Type is rational. */
301    public static final String TAG_GPS_DEST_DISTANCE = "GPSDestDistance";
302    /** Type is String. */
303    public static final String TAG_GPS_DEST_DISTANCE_REF = "GPSDestDistanceRef";
304    /** Type is rational. */
305    public static final String TAG_GPS_DEST_LATITUDE = "GPSDestLatitude";
306    /** Type is String. */
307    public static final String TAG_GPS_DEST_LATITUDE_REF = "GPSDestLatitudeRef";
308    /** Type is rational. */
309    public static final String TAG_GPS_DEST_LONGITUDE = "GPSDestLongitude";
310    /** Type is String. */
311    public static final String TAG_GPS_DEST_LONGITUDE_REF = "GPSDestLongitudeRef";
312    /** Type is int. */
313    public static final String TAG_GPS_DIFFERENTIAL = "GPSDifferential";
314    /** Type is rational. */
315    public static final String TAG_GPS_IMG_DIRECTION = "GPSImgDirection";
316    /** Type is String. */
317    public static final String TAG_GPS_IMG_DIRECTION_REF = "GPSImgDirectionRef";
318    /** Type is rational. Format is "num1/denom1,num2/denom2,num3/denom3". */
319    public static final String TAG_GPS_LATITUDE = "GPSLatitude";
320    /** Type is String. */
321    public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef";
322    /** Type is rational. Format is "num1/denom1,num2/denom2,num3/denom3". */
323    public static final String TAG_GPS_LONGITUDE = "GPSLongitude";
324    /** Type is String. */
325    public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef";
326    /** Type is String. */
327    public static final String TAG_GPS_MAP_DATUM = "GPSMapDatum";
328    /** Type is String. */
329    public static final String TAG_GPS_MEASURE_MODE = "GPSMeasureMode";
330    /** Type is String. Name of GPS processing method used for location finding. */
331    public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod";
332    /** Type is String. */
333    public static final String TAG_GPS_SATELLITES = "GPSSatellites";
334    /** Type is rational. */
335    public static final String TAG_GPS_SPEED = "GPSSpeed";
336    /** Type is String. */
337    public static final String TAG_GPS_SPEED_REF = "GPSSpeedRef";
338    /** Type is String. */
339    public static final String TAG_GPS_STATUS = "GPSStatus";
340    /** Type is String. Format is "hh:mm:ss". */
341    public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp";
342    /** Type is rational. */
343    public static final String TAG_GPS_TRACK = "GPSTrack";
344    /** Type is String. */
345    public static final String TAG_GPS_TRACK_REF = "GPSTrackRef";
346    /** Type is String. */
347    public static final String TAG_GPS_VERSION_ID = "GPSVersionID";
348    /** Type is String. */
349    public static final String TAG_INTEROPERABILITY_INDEX = "InteroperabilityIndex";
350    /** Type is int. */
351    public static final String TAG_THUMBNAIL_IMAGE_LENGTH = "ThumbnailImageLength";
352    /** Type is int. */
353    public static final String TAG_THUMBNAIL_IMAGE_WIDTH = "ThumbnailImageWidth";
354    /** Type is int. DNG Specification 1.4.0.0. Section 4 */
355    public static final String TAG_DNG_VERSION = "DNGVersion";
356    /** Type is int. DNG Specification 1.4.0.0. Section 4 */
357    public static final String TAG_DEFAULT_CROP_SIZE = "DefaultCropSize";
358    /** Type is undefined. See Olympus MakerNote tags in http://www.exiv2.org/tags-olympus.html. */
359    public static final String TAG_ORF_THUMBNAIL_IMAGE = "ThumbnailImage";
360    /** Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html. */
361    public static final String TAG_ORF_PREVIEW_IMAGE_START = "PreviewImageStart";
362    /** Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html. */
363    public static final String TAG_ORF_PREVIEW_IMAGE_LENGTH = "PreviewImageLength";
364    /** Type is int. See Olympus Image Processing tags in http://www.exiv2.org/tags-olympus.html. */
365    public static final String TAG_ORF_ASPECT_FRAME = "AspectFrame";
366    /**
367     * Type is int. See PanasonicRaw tags in
368     * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
369     */
370    public static final String TAG_RW2_SENSOR_BOTTOM_BORDER = "SensorBottomBorder";
371    /**
372     * Type is int. See PanasonicRaw tags in
373     * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
374     */
375    public static final String TAG_RW2_SENSOR_LEFT_BORDER = "SensorLeftBorder";
376    /**
377     * Type is int. See PanasonicRaw tags in
378     * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
379     */
380    public static final String TAG_RW2_SENSOR_RIGHT_BORDER = "SensorRightBorder";
381    /**
382     * Type is int. See PanasonicRaw tags in
383     * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
384     */
385    public static final String TAG_RW2_SENSOR_TOP_BORDER = "SensorTopBorder";
386    /**
387     * Type is int. See PanasonicRaw tags in
388     * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
389     */
390    public static final String TAG_RW2_ISO = "ISO";
391    /**
392     * Type is undefined. See PanasonicRaw tags in
393     * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
394     */
395    public static final String TAG_RW2_JPG_FROM_RAW = "JpgFromRaw";
396
397    /**
398     * Private tags used for pointing the other IFD offsets.
399     * The types of the following tags are int.
400     * See JEITA CP-3451C Section 4.6.3: Exif-specific IFD.
401     * For SubIFD, see Note 1 of Adobe PageMaker® 6.0 TIFF Technical Notes.
402     */
403    private static final String TAG_EXIF_IFD_POINTER = "ExifIFDPointer";
404    private static final String TAG_GPS_INFO_IFD_POINTER = "GPSInfoIFDPointer";
405    private static final String TAG_INTEROPERABILITY_IFD_POINTER = "InteroperabilityIFDPointer";
406    private static final String TAG_SUB_IFD_POINTER = "SubIFDPointer";
407    // Proprietary pointer tags used for ORF files.
408    // See http://www.exiv2.org/tags-olympus.html
409    private static final String TAG_ORF_CAMERA_SETTINGS_IFD_POINTER = "CameraSettingsIFDPointer";
410    private static final String TAG_ORF_IMAGE_PROCESSING_IFD_POINTER = "ImageProcessingIFDPointer";
411
412    // Private tags used for thumbnail information.
413    private static final String TAG_HAS_THUMBNAIL = "HasThumbnail";
414    private static final String TAG_THUMBNAIL_OFFSET = "ThumbnailOffset";
415    private static final String TAG_THUMBNAIL_LENGTH = "ThumbnailLength";
416    private static final String TAG_THUMBNAIL_DATA = "ThumbnailData";
417    private static final int MAX_THUMBNAIL_SIZE = 512;
418
419    // Constants used for the Orientation Exif tag.
420    public static final int ORIENTATION_UNDEFINED = 0;
421    public static final int ORIENTATION_NORMAL = 1;
422    public static final int ORIENTATION_FLIP_HORIZONTAL = 2;  // left right reversed mirror
423    public static final int ORIENTATION_ROTATE_180 = 3;
424    public static final int ORIENTATION_FLIP_VERTICAL = 4;  // upside down mirror
425    // flipped about top-left <--> bottom-right axis
426    public static final int ORIENTATION_TRANSPOSE = 5;
427    public static final int ORIENTATION_ROTATE_90 = 6;  // rotate 90 cw to right it
428    // flipped about top-right <--> bottom-left axis
429    public static final int ORIENTATION_TRANSVERSE = 7;
430    public static final int ORIENTATION_ROTATE_270 = 8;  // rotate 270 to right it
431
432    // Constants used for white balance
433    public static final int WHITEBALANCE_AUTO = 0;
434    public static final int WHITEBALANCE_MANUAL = 1;
435
436    // Maximum size for checking file type signature (see image_type_recognition_lite.cc)
437    private static final int SIGNATURE_CHECK_SIZE = 5000;
438
439    private static final byte[] JPEG_SIGNATURE = new byte[] {(byte) 0xff, (byte) 0xd8, (byte) 0xff};
440    private static final String RAF_SIGNATURE = "FUJIFILMCCD-RAW";
441    private static final int RAF_OFFSET_TO_JPEG_IMAGE_OFFSET = 84;
442    private static final int RAF_INFO_SIZE = 160;
443    private static final int RAF_JPEG_LENGTH_VALUE_SIZE = 4;
444
445    // See http://fileformats.archiveteam.org/wiki/Olympus_ORF
446    private static final short ORF_SIGNATURE_1 = 0x4f52;
447    private static final short ORF_SIGNATURE_2 = 0x5352;
448    // There are two formats for Olympus Makernote Headers. Each has different identifiers and
449    // offsets to the actual data.
450    // See http://www.exiv2.org/makernote.html#R1
451    private static final byte[] ORF_MAKER_NOTE_HEADER_1 = new byte[] {(byte) 0x4f, (byte) 0x4c,
452            (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x00}; // "OLYMP\0"
453    private static final byte[] ORF_MAKER_NOTE_HEADER_2 = new byte[] {(byte) 0x4f, (byte) 0x4c,
454            (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x55, (byte) 0x53, (byte) 0x00,
455            (byte) 0x49, (byte) 0x49}; // "OLYMPUS\0II"
456    private static final int ORF_MAKER_NOTE_HEADER_1_SIZE = 8;
457    private static final int ORF_MAKER_NOTE_HEADER_2_SIZE = 12;
458
459    // See http://fileformats.archiveteam.org/wiki/RW2
460    private static final short RW2_SIGNATURE = 0x0055;
461
462    // See http://fileformats.archiveteam.org/wiki/Pentax_PEF
463    private static final String PEF_SIGNATURE = "PENTAX";
464    // See http://www.exiv2.org/makernote.html#R11
465    private static final int PEF_MAKER_NOTE_SKIP_SIZE = 6;
466
467    private static SimpleDateFormat sFormatter;
468
469    // See Exchangeable image file format for digital still cameras: Exif version 2.2.
470    // The following values are for parsing EXIF data area. There are tag groups in EXIF data area.
471    // They are called "Image File Directory". They have multiple data formats to cover various
472    // image metadata from GPS longitude to camera model name.
473
474    // Types of Exif byte alignments (see JEITA CP-3451C Section 4.5.2)
475    private static final short BYTE_ALIGN_II = 0x4949;  // II: Intel order
476    private static final short BYTE_ALIGN_MM = 0x4d4d;  // MM: Motorola order
477
478    // TIFF Header Fixed Constant (see JEITA CP-3451C Section 4.5.2)
479    private static final byte START_CODE = 0x2a; // 42
480    private static final int IFD_OFFSET = 8;
481
482    // Formats for the value in IFD entry (See TIFF 6.0 Section 2, "Image File Directory".)
483    private static final int IFD_FORMAT_BYTE = 1;
484    private static final int IFD_FORMAT_STRING = 2;
485    private static final int IFD_FORMAT_USHORT = 3;
486    private static final int IFD_FORMAT_ULONG = 4;
487    private static final int IFD_FORMAT_URATIONAL = 5;
488    private static final int IFD_FORMAT_SBYTE = 6;
489    private static final int IFD_FORMAT_UNDEFINED = 7;
490    private static final int IFD_FORMAT_SSHORT = 8;
491    private static final int IFD_FORMAT_SLONG = 9;
492    private static final int IFD_FORMAT_SRATIONAL = 10;
493    private static final int IFD_FORMAT_SINGLE = 11;
494    private static final int IFD_FORMAT_DOUBLE = 12;
495    // Format indicating a new IFD entry (See Adobe PageMaker® 6.0 TIFF Technical Notes, "New Tag")
496    private static final int IFD_FORMAT_IFD = 13;
497    // Names for the data formats for debugging purpose.
498    private static final String[] IFD_FORMAT_NAMES = new String[] {
499            "", "BYTE", "STRING", "USHORT", "ULONG", "URATIONAL", "SBYTE", "UNDEFINED", "SSHORT",
500            "SLONG", "SRATIONAL", "SINGLE", "DOUBLE"
501    };
502    // Sizes of the components of each IFD value format
503    private static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[] {
504            0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1
505    };
506    private static final byte[] EXIF_ASCII_PREFIX = new byte[] {
507            0x41, 0x53, 0x43, 0x49, 0x49, 0x0, 0x0, 0x0
508    };
509
510    /**
511     * Constants used for Compression tag.
512     * For Value 1, 2, 32773, see TIFF 6.0 Spec Section 3: Bilevel Images, Compression
513     * For Value 6, see TIFF 6.0 Spec Section 22: JPEG Compression, Extensions to Existing Fields
514     * For Value 7, 8, 34892, see DNG Specification 1.4.0.0. Section 3, Compression
515     */
516    private static final int DATA_UNCOMPRESSED = 1;
517    private static final int DATA_HUFFMAN_COMPRESSED = 2;
518    private static final int DATA_JPEG = 6;
519    private static final int DATA_JPEG_COMPRESSED = 7;
520    private static final int DATA_DEFLATE_ZIP = 8;
521    private static final int DATA_PACK_BITS_COMPRESSED = 32773;
522    private static final int DATA_LOSSY_JPEG = 34892;
523
524    /**
525     * Constants used for BitsPerSample tag.
526     * For RGB, see TIFF 6.0 Spec Section 6, Differences from Palette Color Images
527     * For Greyscale, see TIFF 6.0 Spec Section 4, Differences from Bilevel Images
528     */
529    private static final int[] BITS_PER_SAMPLE_RGB = new int[] { 8, 8, 8 };
530    private static final int[] BITS_PER_SAMPLE_GREYSCALE_1 = new int[] { 4 };
531    private static final int[] BITS_PER_SAMPLE_GREYSCALE_2 = new int[] { 8 };
532
533    /**
534     * Constants used for PhotometricInterpretation tag.
535     * For White/Black, see Section 3, Color.
536     * See TIFF 6.0 Spec Section 22, Minimum Requirements for TIFF with JPEG Compression.
537     */
538    private static final int PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO = 0;
539    private static final int PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO = 1;
540    private static final int PHOTOMETRIC_INTERPRETATION_RGB = 2;
541    private static final int PHOTOMETRIC_INTERPRETATION_YCBCR = 6;
542
543    /**
544     * Constants used for NewSubfileType tag.
545     * See TIFF 6.0 Spec Section 8
546     * */
547    private static final int ORIGINAL_RESOLUTION_IMAGE = 0;
548    private static final int REDUCED_RESOLUTION_IMAGE = 1;
549
550    // A class for indicating EXIF rational type.
551    private static class Rational {
552        public final long numerator;
553        public final long denominator;
554
555        private Rational(long numerator, long denominator) {
556            // Handle erroneous case
557            if (denominator == 0) {
558                this.numerator = 0;
559                this.denominator = 1;
560                return;
561            }
562            this.numerator = numerator;
563            this.denominator = denominator;
564        }
565
566        @Override
567        public String toString() {
568            return numerator + "/" + denominator;
569        }
570
571        public double calculate() {
572            return (double) numerator / denominator;
573        }
574    }
575
576    // A class for indicating EXIF attribute.
577    private static class ExifAttribute {
578        public final int format;
579        public final int numberOfComponents;
580        public final byte[] bytes;
581
582        private ExifAttribute(int format, int numberOfComponents, byte[] bytes) {
583            this.format = format;
584            this.numberOfComponents = numberOfComponents;
585            this.bytes = bytes;
586        }
587
588        public static ExifAttribute createUShort(int[] values, ByteOrder byteOrder) {
589            final ByteBuffer buffer = ByteBuffer.wrap(
590                    new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_USHORT] * values.length]);
591            buffer.order(byteOrder);
592            for (int value : values) {
593                buffer.putShort((short) value);
594            }
595            return new ExifAttribute(IFD_FORMAT_USHORT, values.length, buffer.array());
596        }
597
598        public static ExifAttribute createUShort(int value, ByteOrder byteOrder) {
599            return createUShort(new int[] {value}, byteOrder);
600        }
601
602        public static ExifAttribute createULong(long[] values, ByteOrder byteOrder) {
603            final ByteBuffer buffer = ByteBuffer.wrap(
604                    new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_ULONG] * values.length]);
605            buffer.order(byteOrder);
606            for (long value : values) {
607                buffer.putInt((int) value);
608            }
609            return new ExifAttribute(IFD_FORMAT_ULONG, values.length, buffer.array());
610        }
611
612        public static ExifAttribute createULong(long value, ByteOrder byteOrder) {
613            return createULong(new long[] {value}, byteOrder);
614        }
615
616        public static ExifAttribute createSLong(int[] values, ByteOrder byteOrder) {
617            final ByteBuffer buffer = ByteBuffer.wrap(
618                    new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SLONG] * values.length]);
619            buffer.order(byteOrder);
620            for (int value : values) {
621                buffer.putInt(value);
622            }
623            return new ExifAttribute(IFD_FORMAT_SLONG, values.length, buffer.array());
624        }
625
626        public static ExifAttribute createSLong(int value, ByteOrder byteOrder) {
627            return createSLong(new int[] {value}, byteOrder);
628        }
629
630        public static ExifAttribute createByte(String value) {
631            // Exception for GPSAltitudeRef tag
632            if (value.length() == 1 && value.charAt(0) >= '0' && value.charAt(0) <= '1') {
633                final byte[] bytes = new byte[] { (byte) (value.charAt(0) - '0') };
634                return new ExifAttribute(IFD_FORMAT_BYTE, bytes.length, bytes);
635            }
636            final byte[] ascii = value.getBytes(ASCII);
637            return new ExifAttribute(IFD_FORMAT_BYTE, ascii.length, ascii);
638        }
639
640        public static ExifAttribute createString(String value) {
641            final byte[] ascii = (value + '\0').getBytes(ASCII);
642            return new ExifAttribute(IFD_FORMAT_STRING, ascii.length, ascii);
643        }
644
645        public static ExifAttribute createURational(Rational[] values, ByteOrder byteOrder) {
646            final ByteBuffer buffer = ByteBuffer.wrap(
647                    new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_URATIONAL] * values.length]);
648            buffer.order(byteOrder);
649            for (Rational value : values) {
650                buffer.putInt((int) value.numerator);
651                buffer.putInt((int) value.denominator);
652            }
653            return new ExifAttribute(IFD_FORMAT_URATIONAL, values.length, buffer.array());
654        }
655
656        public static ExifAttribute createURational(Rational value, ByteOrder byteOrder) {
657            return createURational(new Rational[] {value}, byteOrder);
658        }
659
660        public static ExifAttribute createSRational(Rational[] values, ByteOrder byteOrder) {
661            final ByteBuffer buffer = ByteBuffer.wrap(
662                    new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SRATIONAL] * values.length]);
663            buffer.order(byteOrder);
664            for (Rational value : values) {
665                buffer.putInt((int) value.numerator);
666                buffer.putInt((int) value.denominator);
667            }
668            return new ExifAttribute(IFD_FORMAT_SRATIONAL, values.length, buffer.array());
669        }
670
671        public static ExifAttribute createSRational(Rational value, ByteOrder byteOrder) {
672            return createSRational(new Rational[] {value}, byteOrder);
673        }
674
675        public static ExifAttribute createDouble(double[] values, ByteOrder byteOrder) {
676            final ByteBuffer buffer = ByteBuffer.wrap(
677                    new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_DOUBLE] * values.length]);
678            buffer.order(byteOrder);
679            for (double value : values) {
680                buffer.putDouble(value);
681            }
682            return new ExifAttribute(IFD_FORMAT_DOUBLE, values.length, buffer.array());
683        }
684
685        public static ExifAttribute createDouble(double value, ByteOrder byteOrder) {
686            return createDouble(new double[] {value}, byteOrder);
687        }
688
689        @Override
690        public String toString() {
691            return "(" + IFD_FORMAT_NAMES[format] + ", data length:" + bytes.length + ")";
692        }
693
694        private Object getValue(ByteOrder byteOrder) {
695            try {
696                ByteOrderedDataInputStream inputStream =
697                        new ByteOrderedDataInputStream(bytes);
698                inputStream.setByteOrder(byteOrder);
699                switch (format) {
700                    case IFD_FORMAT_BYTE:
701                    case IFD_FORMAT_SBYTE: {
702                        // Exception for GPSAltitudeRef tag
703                        if (bytes.length == 1 && bytes[0] >= 0 && bytes[0] <= 1) {
704                            return new String(new char[] { (char) (bytes[0] + '0') });
705                        }
706                        return new String(bytes, ASCII);
707                    }
708                    case IFD_FORMAT_UNDEFINED:
709                    case IFD_FORMAT_STRING: {
710                        int index = 0;
711                        if (numberOfComponents >= EXIF_ASCII_PREFIX.length) {
712                            boolean same = true;
713                            for (int i = 0; i < EXIF_ASCII_PREFIX.length; ++i) {
714                                if (bytes[i] != EXIF_ASCII_PREFIX[i]) {
715                                    same = false;
716                                    break;
717                                }
718                            }
719                            if (same) {
720                                index = EXIF_ASCII_PREFIX.length;
721                            }
722                        }
723
724                        StringBuilder stringBuilder = new StringBuilder();
725                        while (index < numberOfComponents) {
726                            int ch = bytes[index];
727                            if (ch == 0) {
728                                break;
729                            }
730                            if (ch >= 32) {
731                                stringBuilder.append((char) ch);
732                            } else {
733                                stringBuilder.append('?');
734                            }
735                            ++index;
736                        }
737                        return stringBuilder.toString();
738                    }
739                    case IFD_FORMAT_USHORT: {
740                        final int[] values = new int[numberOfComponents];
741                        for (int i = 0; i < numberOfComponents; ++i) {
742                            values[i] = inputStream.readUnsignedShort();
743                        }
744                        return values;
745                    }
746                    case IFD_FORMAT_ULONG: {
747                        final long[] values = new long[numberOfComponents];
748                        for (int i = 0; i < numberOfComponents; ++i) {
749                            values[i] = inputStream.readUnsignedInt();
750                        }
751                        return values;
752                    }
753                    case IFD_FORMAT_URATIONAL: {
754                        final Rational[] values = new Rational[numberOfComponents];
755                        for (int i = 0; i < numberOfComponents; ++i) {
756                            final long numerator = inputStream.readUnsignedInt();
757                            final long denominator = inputStream.readUnsignedInt();
758                            values[i] = new Rational(numerator, denominator);
759                        }
760                        return values;
761                    }
762                    case IFD_FORMAT_SSHORT: {
763                        final int[] values = new int[numberOfComponents];
764                        for (int i = 0; i < numberOfComponents; ++i) {
765                            values[i] = inputStream.readShort();
766                        }
767                        return values;
768                    }
769                    case IFD_FORMAT_SLONG: {
770                        final int[] values = new int[numberOfComponents];
771                        for (int i = 0; i < numberOfComponents; ++i) {
772                            values[i] = inputStream.readInt();
773                        }
774                        return values;
775                    }
776                    case IFD_FORMAT_SRATIONAL: {
777                        final Rational[] values = new Rational[numberOfComponents];
778                        for (int i = 0; i < numberOfComponents; ++i) {
779                            final long numerator = inputStream.readInt();
780                            final long denominator = inputStream.readInt();
781                            values[i] = new Rational(numerator, denominator);
782                        }
783                        return values;
784                    }
785                    case IFD_FORMAT_SINGLE: {
786                        final double[] values = new double[numberOfComponents];
787                        for (int i = 0; i < numberOfComponents; ++i) {
788                            values[i] = inputStream.readFloat();
789                        }
790                        return values;
791                    }
792                    case IFD_FORMAT_DOUBLE: {
793                        final double[] values = new double[numberOfComponents];
794                        for (int i = 0; i < numberOfComponents; ++i) {
795                            values[i] = inputStream.readDouble();
796                        }
797                        return values;
798                    }
799                    default:
800                        return null;
801                }
802            } catch (IOException e) {
803                Log.w(TAG, "IOException occurred during reading a value", e);
804                return null;
805            }
806        }
807
808        public double getDoubleValue(ByteOrder byteOrder) {
809            Object value = getValue(byteOrder);
810            if (value == null) {
811                throw new NumberFormatException("NULL can't be converted to a double value");
812            }
813            if (value instanceof String) {
814                return Double.parseDouble((String) value);
815            }
816            if (value instanceof long[]) {
817                long[] array = (long[]) value;
818                if (array.length == 1) {
819                    return array[0];
820                }
821                throw new NumberFormatException("There are more than one component");
822            }
823            if (value instanceof int[]) {
824                int[] array = (int[]) value;
825                if (array.length == 1) {
826                    return array[0];
827                }
828                throw new NumberFormatException("There are more than one component");
829            }
830            if (value instanceof double[]) {
831                double[] array = (double[]) value;
832                if (array.length == 1) {
833                    return array[0];
834                }
835                throw new NumberFormatException("There are more than one component");
836            }
837            if (value instanceof Rational[]) {
838                Rational[] array = (Rational[]) value;
839                if (array.length == 1) {
840                    return array[0].calculate();
841                }
842                throw new NumberFormatException("There are more than one component");
843            }
844            throw new NumberFormatException("Couldn't find a double value");
845        }
846
847        public int getIntValue(ByteOrder byteOrder) {
848            Object value = getValue(byteOrder);
849            if (value == null) {
850                throw new NumberFormatException("NULL can't be converted to a integer value");
851            }
852            if (value instanceof String) {
853                return Integer.parseInt((String) value);
854            }
855            if (value instanceof long[]) {
856                long[] array = (long[]) value;
857                if (array.length == 1) {
858                    return (int) array[0];
859                }
860                throw new NumberFormatException("There are more than one component");
861            }
862            if (value instanceof int[]) {
863                int[] array = (int[]) value;
864                if (array.length == 1) {
865                    return array[0];
866                }
867                throw new NumberFormatException("There are more than one component");
868            }
869            throw new NumberFormatException("Couldn't find a integer value");
870        }
871
872        public String getStringValue(ByteOrder byteOrder) {
873            Object value = getValue(byteOrder);
874            if (value == null) {
875                return null;
876            }
877            if (value instanceof String) {
878                return (String) value;
879            }
880
881            final StringBuilder stringBuilder = new StringBuilder();
882            if (value instanceof long[]) {
883                long[] array = (long[]) value;
884                for (int i = 0; i < array.length; ++i) {
885                    stringBuilder.append(array[i]);
886                    if (i + 1 != array.length) {
887                        stringBuilder.append(",");
888                    }
889                }
890                return stringBuilder.toString();
891            }
892            if (value instanceof int[]) {
893                int[] array = (int[]) value;
894                for (int i = 0; i < array.length; ++i) {
895                    stringBuilder.append(array[i]);
896                    if (i + 1 != array.length) {
897                        stringBuilder.append(",");
898                    }
899                }
900                return stringBuilder.toString();
901            }
902            if (value instanceof double[]) {
903                double[] array = (double[]) value;
904                for (int i = 0; i < array.length; ++i) {
905                    stringBuilder.append(array[i]);
906                    if (i + 1 != array.length) {
907                        stringBuilder.append(",");
908                    }
909                }
910                return stringBuilder.toString();
911            }
912            if (value instanceof Rational[]) {
913                Rational[] array = (Rational[]) value;
914                for (int i = 0; i < array.length; ++i) {
915                    stringBuilder.append(array[i].numerator);
916                    stringBuilder.append('/');
917                    stringBuilder.append(array[i].denominator);
918                    if (i + 1 != array.length) {
919                        stringBuilder.append(",");
920                    }
921                }
922                return stringBuilder.toString();
923            }
924            return null;
925        }
926
927        public int size() {
928            return IFD_FORMAT_BYTES_PER_FORMAT[format] * numberOfComponents;
929        }
930    }
931
932    // A class for indicating EXIF tag.
933    private static class ExifTag {
934        public final int number;
935        public final String name;
936        public final int primaryFormat;
937        public final int secondaryFormat;
938
939        private ExifTag(String name, int number, int format) {
940            this.name = name;
941            this.number = number;
942            this.primaryFormat = format;
943            this.secondaryFormat = -1;
944        }
945
946        private ExifTag(String name, int number, int primaryFormat, int secondaryFormat) {
947            this.name = name;
948            this.number = number;
949            this.primaryFormat = primaryFormat;
950            this.secondaryFormat = secondaryFormat;
951        }
952    }
953
954    // Primary image IFD TIFF tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
955    private static final ExifTag[] IFD_TIFF_TAGS = new ExifTag[] {
956            // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images.
957            new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG),
958            new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG),
959            new ExifTag(TAG_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
960            new ExifTag(TAG_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
961            new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT),
962            new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT),
963            new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT),
964            new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING),
965            new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING),
966            new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING),
967            new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
968            new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT),
969            new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT),
970            new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
971            new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
972            new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL),
973            new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL),
974            new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT),
975            new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT),
976            new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT),
977            new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING),
978            new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING),
979            new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING),
980            new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL),
981            new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL),
982            // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1.
983            new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG),
984            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG),
985            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG),
986            new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL),
987            new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT),
988            new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT),
989            new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL),
990            new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING),
991            new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG),
992            new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG),
993            // RW2 file tags
994            // See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html)
995            new ExifTag(TAG_RW2_SENSOR_TOP_BORDER, 4, IFD_FORMAT_ULONG),
996            new ExifTag(TAG_RW2_SENSOR_LEFT_BORDER, 5, IFD_FORMAT_ULONG),
997            new ExifTag(TAG_RW2_SENSOR_BOTTOM_BORDER, 6, IFD_FORMAT_ULONG),
998            new ExifTag(TAG_RW2_SENSOR_RIGHT_BORDER, 7, IFD_FORMAT_ULONG),
999            new ExifTag(TAG_RW2_ISO, 23, IFD_FORMAT_USHORT),
1000            new ExifTag(TAG_RW2_JPG_FROM_RAW, 46, IFD_FORMAT_UNDEFINED)
1001    };
1002
1003    // Primary image IFD Exif Private tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
1004    private static final ExifTag[] IFD_EXIF_TAGS = new ExifTag[] {
1005            new ExifTag(TAG_EXPOSURE_TIME, 33434, IFD_FORMAT_URATIONAL),
1006            new ExifTag(TAG_F_NUMBER, 33437, IFD_FORMAT_URATIONAL),
1007            new ExifTag(TAG_EXPOSURE_PROGRAM, 34850, IFD_FORMAT_USHORT),
1008            new ExifTag(TAG_SPECTRAL_SENSITIVITY, 34852, IFD_FORMAT_STRING),
1009            new ExifTag(TAG_ISO_SPEED_RATINGS, 34855, IFD_FORMAT_USHORT),
1010            new ExifTag(TAG_OECF, 34856, IFD_FORMAT_UNDEFINED),
1011            new ExifTag(TAG_EXIF_VERSION, 36864, IFD_FORMAT_STRING),
1012            new ExifTag(TAG_DATETIME_ORIGINAL, 36867, IFD_FORMAT_STRING),
1013            new ExifTag(TAG_DATETIME_DIGITIZED, 36868, IFD_FORMAT_STRING),
1014            new ExifTag(TAG_COMPONENTS_CONFIGURATION, 37121, IFD_FORMAT_UNDEFINED),
1015            new ExifTag(TAG_COMPRESSED_BITS_PER_PIXEL, 37122, IFD_FORMAT_URATIONAL),
1016            new ExifTag(TAG_SHUTTER_SPEED_VALUE, 37377, IFD_FORMAT_SRATIONAL),
1017            new ExifTag(TAG_APERTURE_VALUE, 37378, IFD_FORMAT_URATIONAL),
1018            new ExifTag(TAG_BRIGHTNESS_VALUE, 37379, IFD_FORMAT_SRATIONAL),
1019            new ExifTag(TAG_EXPOSURE_BIAS_VALUE, 37380, IFD_FORMAT_SRATIONAL),
1020            new ExifTag(TAG_MAX_APERTURE_VALUE, 37381, IFD_FORMAT_URATIONAL),
1021            new ExifTag(TAG_SUBJECT_DISTANCE, 37382, IFD_FORMAT_URATIONAL),
1022            new ExifTag(TAG_METERING_MODE, 37383, IFD_FORMAT_USHORT),
1023            new ExifTag(TAG_LIGHT_SOURCE, 37384, IFD_FORMAT_USHORT),
1024            new ExifTag(TAG_FLASH, 37385, IFD_FORMAT_USHORT),
1025            new ExifTag(TAG_FOCAL_LENGTH, 37386, IFD_FORMAT_URATIONAL),
1026            new ExifTag(TAG_SUBJECT_AREA, 37396, IFD_FORMAT_USHORT),
1027            new ExifTag(TAG_MAKER_NOTE, 37500, IFD_FORMAT_UNDEFINED),
1028            new ExifTag(TAG_USER_COMMENT, 37510, IFD_FORMAT_UNDEFINED),
1029            new ExifTag(TAG_SUBSEC_TIME, 37520, IFD_FORMAT_STRING),
1030            new ExifTag(TAG_SUBSEC_TIME_ORIG, 37521, IFD_FORMAT_STRING),
1031            new ExifTag(TAG_SUBSEC_TIME_DIG, 37522, IFD_FORMAT_STRING),
1032            new ExifTag(TAG_FLASHPIX_VERSION, 40960, IFD_FORMAT_UNDEFINED),
1033            new ExifTag(TAG_COLOR_SPACE, 40961, IFD_FORMAT_USHORT),
1034            new ExifTag(TAG_PIXEL_X_DIMENSION, 40962, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
1035            new ExifTag(TAG_PIXEL_Y_DIMENSION, 40963, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
1036            new ExifTag(TAG_RELATED_SOUND_FILE, 40964, IFD_FORMAT_STRING),
1037            new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG),
1038            new ExifTag(TAG_FLASH_ENERGY, 41483, IFD_FORMAT_URATIONAL),
1039            new ExifTag(TAG_SPATIAL_FREQUENCY_RESPONSE, 41484, IFD_FORMAT_UNDEFINED),
1040            new ExifTag(TAG_FOCAL_PLANE_X_RESOLUTION, 41486, IFD_FORMAT_URATIONAL),
1041            new ExifTag(TAG_FOCAL_PLANE_Y_RESOLUTION, 41487, IFD_FORMAT_URATIONAL),
1042            new ExifTag(TAG_FOCAL_PLANE_RESOLUTION_UNIT, 41488, IFD_FORMAT_USHORT),
1043            new ExifTag(TAG_SUBJECT_LOCATION, 41492, IFD_FORMAT_USHORT),
1044            new ExifTag(TAG_EXPOSURE_INDEX, 41493, IFD_FORMAT_URATIONAL),
1045            new ExifTag(TAG_SENSING_METHOD, 41495, IFD_FORMAT_USHORT),
1046            new ExifTag(TAG_FILE_SOURCE, 41728, IFD_FORMAT_UNDEFINED),
1047            new ExifTag(TAG_SCENE_TYPE, 41729, IFD_FORMAT_UNDEFINED),
1048            new ExifTag(TAG_CFA_PATTERN, 41730, IFD_FORMAT_UNDEFINED),
1049            new ExifTag(TAG_CUSTOM_RENDERED, 41985, IFD_FORMAT_USHORT),
1050            new ExifTag(TAG_EXPOSURE_MODE, 41986, IFD_FORMAT_USHORT),
1051            new ExifTag(TAG_WHITE_BALANCE, 41987, IFD_FORMAT_USHORT),
1052            new ExifTag(TAG_DIGITAL_ZOOM_RATIO, 41988, IFD_FORMAT_URATIONAL),
1053            new ExifTag(TAG_FOCAL_LENGTH_IN_35MM_FILM, 41989, IFD_FORMAT_USHORT),
1054            new ExifTag(TAG_SCENE_CAPTURE_TYPE, 41990, IFD_FORMAT_USHORT),
1055            new ExifTag(TAG_GAIN_CONTROL, 41991, IFD_FORMAT_USHORT),
1056            new ExifTag(TAG_CONTRAST, 41992, IFD_FORMAT_USHORT),
1057            new ExifTag(TAG_SATURATION, 41993, IFD_FORMAT_USHORT),
1058            new ExifTag(TAG_SHARPNESS, 41994, IFD_FORMAT_USHORT),
1059            new ExifTag(TAG_DEVICE_SETTING_DESCRIPTION, 41995, IFD_FORMAT_UNDEFINED),
1060            new ExifTag(TAG_SUBJECT_DISTANCE_RANGE, 41996, IFD_FORMAT_USHORT),
1061            new ExifTag(TAG_IMAGE_UNIQUE_ID, 42016, IFD_FORMAT_STRING),
1062            new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE),
1063            new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG)
1064    };
1065
1066    // Primary image IFD GPS Info tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
1067    private static final ExifTag[] IFD_GPS_TAGS = new ExifTag[] {
1068            new ExifTag(TAG_GPS_VERSION_ID, 0, IFD_FORMAT_BYTE),
1069            new ExifTag(TAG_GPS_LATITUDE_REF, 1, IFD_FORMAT_STRING),
1070            new ExifTag(TAG_GPS_LATITUDE, 2, IFD_FORMAT_URATIONAL),
1071            new ExifTag(TAG_GPS_LONGITUDE_REF, 3, IFD_FORMAT_STRING),
1072            new ExifTag(TAG_GPS_LONGITUDE, 4, IFD_FORMAT_URATIONAL),
1073            new ExifTag(TAG_GPS_ALTITUDE_REF, 5, IFD_FORMAT_BYTE),
1074            new ExifTag(TAG_GPS_ALTITUDE, 6, IFD_FORMAT_URATIONAL),
1075            new ExifTag(TAG_GPS_TIMESTAMP, 7, IFD_FORMAT_URATIONAL),
1076            new ExifTag(TAG_GPS_SATELLITES, 8, IFD_FORMAT_STRING),
1077            new ExifTag(TAG_GPS_STATUS, 9, IFD_FORMAT_STRING),
1078            new ExifTag(TAG_GPS_MEASURE_MODE, 10, IFD_FORMAT_STRING),
1079            new ExifTag(TAG_GPS_DOP, 11, IFD_FORMAT_URATIONAL),
1080            new ExifTag(TAG_GPS_SPEED_REF, 12, IFD_FORMAT_STRING),
1081            new ExifTag(TAG_GPS_SPEED, 13, IFD_FORMAT_URATIONAL),
1082            new ExifTag(TAG_GPS_TRACK_REF, 14, IFD_FORMAT_STRING),
1083            new ExifTag(TAG_GPS_TRACK, 15, IFD_FORMAT_URATIONAL),
1084            new ExifTag(TAG_GPS_IMG_DIRECTION_REF, 16, IFD_FORMAT_STRING),
1085            new ExifTag(TAG_GPS_IMG_DIRECTION, 17, IFD_FORMAT_URATIONAL),
1086            new ExifTag(TAG_GPS_MAP_DATUM, 18, IFD_FORMAT_STRING),
1087            new ExifTag(TAG_GPS_DEST_LATITUDE_REF, 19, IFD_FORMAT_STRING),
1088            new ExifTag(TAG_GPS_DEST_LATITUDE, 20, IFD_FORMAT_URATIONAL),
1089            new ExifTag(TAG_GPS_DEST_LONGITUDE_REF, 21, IFD_FORMAT_STRING),
1090            new ExifTag(TAG_GPS_DEST_LONGITUDE, 22, IFD_FORMAT_URATIONAL),
1091            new ExifTag(TAG_GPS_DEST_BEARING_REF, 23, IFD_FORMAT_STRING),
1092            new ExifTag(TAG_GPS_DEST_BEARING, 24, IFD_FORMAT_URATIONAL),
1093            new ExifTag(TAG_GPS_DEST_DISTANCE_REF, 25, IFD_FORMAT_STRING),
1094            new ExifTag(TAG_GPS_DEST_DISTANCE, 26, IFD_FORMAT_URATIONAL),
1095            new ExifTag(TAG_GPS_PROCESSING_METHOD, 27, IFD_FORMAT_UNDEFINED),
1096            new ExifTag(TAG_GPS_AREA_INFORMATION, 28, IFD_FORMAT_UNDEFINED),
1097            new ExifTag(TAG_GPS_DATESTAMP, 29, IFD_FORMAT_STRING),
1098            new ExifTag(TAG_GPS_DIFFERENTIAL, 30, IFD_FORMAT_USHORT)
1099    };
1100    // Primary image IFD Interoperability tag (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
1101    private static final ExifTag[] IFD_INTEROPERABILITY_TAGS = new ExifTag[] {
1102            new ExifTag(TAG_INTEROPERABILITY_INDEX, 1, IFD_FORMAT_STRING)
1103    };
1104    // IFD Thumbnail tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
1105    private static final ExifTag[] IFD_THUMBNAIL_TAGS = new ExifTag[] {
1106            // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images.
1107            new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG),
1108            new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG),
1109            new ExifTag(TAG_THUMBNAIL_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
1110            new ExifTag(TAG_THUMBNAIL_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
1111            new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT),
1112            new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT),
1113            new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT),
1114            new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING),
1115            new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING),
1116            new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING),
1117            new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
1118            new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT),
1119            new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT),
1120            new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
1121            new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
1122            new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL),
1123            new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL),
1124            new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT),
1125            new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT),
1126            new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT),
1127            new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING),
1128            new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING),
1129            new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING),
1130            new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL),
1131            new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL),
1132            // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1.
1133            new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG),
1134            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG),
1135            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG),
1136            new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL),
1137            new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT),
1138            new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT),
1139            new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL),
1140            new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING),
1141            new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG),
1142            new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG),
1143            new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE),
1144            new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG)
1145    };
1146
1147    // RAF file tag (See piex.cc line 372)
1148    private static final ExifTag TAG_RAF_IMAGE_SIZE =
1149            new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT);
1150
1151    // ORF file tags (See http://www.exiv2.org/tags-olympus.html)
1152    private static final ExifTag[] ORF_MAKER_NOTE_TAGS = new ExifTag[] {
1153            new ExifTag(TAG_ORF_THUMBNAIL_IMAGE, 256, IFD_FORMAT_UNDEFINED),
1154            new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_ULONG),
1155            new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_ULONG)
1156    };
1157    private static final ExifTag[] ORF_CAMERA_SETTINGS_TAGS = new ExifTag[] {
1158            new ExifTag(TAG_ORF_PREVIEW_IMAGE_START, 257, IFD_FORMAT_ULONG),
1159            new ExifTag(TAG_ORF_PREVIEW_IMAGE_LENGTH, 258, IFD_FORMAT_ULONG)
1160    };
1161    private static final ExifTag[] ORF_IMAGE_PROCESSING_TAGS = new ExifTag[] {
1162            new ExifTag(TAG_ORF_ASPECT_FRAME, 4371, IFD_FORMAT_USHORT)
1163    };
1164    // PEF file tag (See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Pentax.html)
1165    private static final ExifTag[] PEF_TAGS = new ExifTag[] {
1166            new ExifTag(TAG_COLOR_SPACE, 55, IFD_FORMAT_USHORT)
1167    };
1168
1169    // See JEITA CP-3451C Section 4.6.3: Exif-specific IFD.
1170    // The following values are used for indicating pointers to the other Image File Directories.
1171
1172    // Indices of Exif Ifd tag groups
1173    /** @hide */
1174    @Retention(RetentionPolicy.SOURCE)
1175    @IntDef({IFD_TYPE_PRIMARY, IFD_TYPE_EXIF, IFD_TYPE_GPS, IFD_TYPE_INTEROPERABILITY,
1176            IFD_TYPE_THUMBNAIL, IFD_TYPE_PREVIEW, IFD_TYPE_ORF_MAKER_NOTE,
1177            IFD_TYPE_ORF_CAMERA_SETTINGS, IFD_TYPE_ORF_IMAGE_PROCESSING, IFD_TYPE_PEF})
1178    public @interface IfdType {}
1179
1180    private static final int IFD_TYPE_PRIMARY = 0;
1181    private static final int IFD_TYPE_EXIF = 1;
1182    private static final int IFD_TYPE_GPS = 2;
1183    private static final int IFD_TYPE_INTEROPERABILITY = 3;
1184    private static final int IFD_TYPE_THUMBNAIL = 4;
1185    private static final int IFD_TYPE_PREVIEW = 5;
1186    private static final int IFD_TYPE_ORF_MAKER_NOTE = 6;
1187    private static final int IFD_TYPE_ORF_CAMERA_SETTINGS = 7;
1188    private static final int IFD_TYPE_ORF_IMAGE_PROCESSING = 8;
1189    private static final int IFD_TYPE_PEF = 9;
1190
1191    // List of Exif tag groups
1192    private static final ExifTag[][] EXIF_TAGS = new ExifTag[][] {
1193            IFD_TIFF_TAGS, IFD_EXIF_TAGS, IFD_GPS_TAGS, IFD_INTEROPERABILITY_TAGS,
1194            IFD_THUMBNAIL_TAGS, IFD_TIFF_TAGS, ORF_MAKER_NOTE_TAGS, ORF_CAMERA_SETTINGS_TAGS,
1195            ORF_IMAGE_PROCESSING_TAGS, PEF_TAGS
1196    };
1197    // List of tags for pointing to the other image file directory offset.
1198    private static final ExifTag[] EXIF_POINTER_TAGS = new ExifTag[] {
1199            new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG),
1200            new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG),
1201            new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG),
1202            new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG),
1203            new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_BYTE),
1204            new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_BYTE)
1205    };
1206
1207    // Tags for indicating the thumbnail offset and length
1208    private static final ExifTag JPEG_INTERCHANGE_FORMAT_TAG =
1209            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG);
1210    private static final ExifTag JPEG_INTERCHANGE_FORMAT_LENGTH_TAG =
1211            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG);
1212
1213    // Mappings from tag number to tag name and each item represents one IFD tag group.
1214    private static final HashMap[] sExifTagMapsForReading = new HashMap[EXIF_TAGS.length];
1215    // Mappings from tag name to tag number and each item represents one IFD tag group.
1216    private static final HashMap[] sExifTagMapsForWriting = new HashMap[EXIF_TAGS.length];
1217    private static final HashSet<String> sTagSetForCompatibility = new HashSet<>(Arrays.asList(
1218            TAG_F_NUMBER, TAG_DIGITAL_ZOOM_RATIO, TAG_EXPOSURE_TIME, TAG_SUBJECT_DISTANCE,
1219            TAG_GPS_TIMESTAMP));
1220    // Mappings from tag number to IFD type for pointer tags.
1221    private static final HashMap sExifPointerTagMap = new HashMap();
1222
1223    // See JPEG File Interchange Format Version 1.02.
1224    // The following values are defined for handling JPEG streams. In this implementation, we are
1225    // not only getting information from EXIF but also from some JPEG special segments such as
1226    // MARKER_COM for user comment and MARKER_SOFx for image width and height.
1227
1228    private static final Charset ASCII = Charset.forName("US-ASCII");
1229    // Identifier for EXIF APP1 segment in JPEG
1230    private static final byte[] IDENTIFIER_EXIF_APP1 = "Exif\0\0".getBytes(ASCII);
1231    // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with
1232    // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start
1233    // of frame(baseline DCT) and the image size info exists in its beginning part.
1234    private static final byte MARKER = (byte) 0xff;
1235    private static final byte MARKER_SOI = (byte) 0xd8;
1236    private static final byte MARKER_SOF0 = (byte) 0xc0;
1237    private static final byte MARKER_SOF1 = (byte) 0xc1;
1238    private static final byte MARKER_SOF2 = (byte) 0xc2;
1239    private static final byte MARKER_SOF3 = (byte) 0xc3;
1240    private static final byte MARKER_SOF5 = (byte) 0xc5;
1241    private static final byte MARKER_SOF6 = (byte) 0xc6;
1242    private static final byte MARKER_SOF7 = (byte) 0xc7;
1243    private static final byte MARKER_SOF9 = (byte) 0xc9;
1244    private static final byte MARKER_SOF10 = (byte) 0xca;
1245    private static final byte MARKER_SOF11 = (byte) 0xcb;
1246    private static final byte MARKER_SOF13 = (byte) 0xcd;
1247    private static final byte MARKER_SOF14 = (byte) 0xce;
1248    private static final byte MARKER_SOF15 = (byte) 0xcf;
1249    private static final byte MARKER_SOS = (byte) 0xda;
1250    private static final byte MARKER_APP1 = (byte) 0xe1;
1251    private static final byte MARKER_COM = (byte) 0xfe;
1252    private static final byte MARKER_EOI = (byte) 0xd9;
1253
1254    // Supported Image File Types
1255    private static final int IMAGE_TYPE_UNKNOWN = 0;
1256    private static final int IMAGE_TYPE_ARW = 1;
1257    private static final int IMAGE_TYPE_CR2 = 2;
1258    private static final int IMAGE_TYPE_DNG = 3;
1259    private static final int IMAGE_TYPE_JPEG = 4;
1260    private static final int IMAGE_TYPE_NEF = 5;
1261    private static final int IMAGE_TYPE_NRW = 6;
1262    private static final int IMAGE_TYPE_ORF = 7;
1263    private static final int IMAGE_TYPE_PEF = 8;
1264    private static final int IMAGE_TYPE_RAF = 9;
1265    private static final int IMAGE_TYPE_RW2 = 10;
1266    private static final int IMAGE_TYPE_SRW = 11;
1267
1268    static {
1269        sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
1270        sFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
1271
1272        // Build up the hash tables to look up Exif tags for reading Exif tags.
1273        for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) {
1274            sExifTagMapsForReading[ifdType] = new HashMap();
1275            sExifTagMapsForWriting[ifdType] = new HashMap();
1276            for (ExifTag tag : EXIF_TAGS[ifdType]) {
1277                sExifTagMapsForReading[ifdType].put(tag.number, tag);
1278                sExifTagMapsForWriting[ifdType].put(tag.name, tag);
1279            }
1280        }
1281
1282        // Build up the hash table to look up Exif pointer tags.
1283        sExifPointerTagMap.put(EXIF_POINTER_TAGS[0].number, IFD_TYPE_PREVIEW); // 330
1284        sExifPointerTagMap.put(EXIF_POINTER_TAGS[1].number, IFD_TYPE_EXIF); // 34665
1285        sExifPointerTagMap.put(EXIF_POINTER_TAGS[2].number, IFD_TYPE_GPS); // 34853
1286        sExifPointerTagMap.put(EXIF_POINTER_TAGS[3].number, IFD_TYPE_INTEROPERABILITY); // 40965
1287        sExifPointerTagMap.put(EXIF_POINTER_TAGS[4].number, IFD_TYPE_ORF_CAMERA_SETTINGS); // 8224
1288        sExifPointerTagMap.put(EXIF_POINTER_TAGS[5].number, IFD_TYPE_ORF_IMAGE_PROCESSING); // 8256
1289    }
1290
1291    private final String mFilename;
1292    private final FileDescriptor mSeekableFileDescriptor;
1293    private final AssetManager.AssetInputStream mAssetInputStream;
1294    private final boolean mIsInputStream;
1295    private int mMimeType;
1296    private final HashMap[] mAttributes = new HashMap[EXIF_TAGS.length];
1297    private ByteOrder mExifByteOrder = ByteOrder.BIG_ENDIAN;
1298    private boolean mHasThumbnail;
1299    // The following values used for indicating a thumbnail position.
1300    private int mThumbnailOffset;
1301    private int mThumbnailLength;
1302    private byte[] mThumbnailBytes;
1303    private int mThumbnailCompression;
1304    private int mExifOffset;
1305    private int mOrfMakerNoteOffset;
1306    private int mOrfThumbnailOffset;
1307    private int mOrfThumbnailLength;
1308    private int mRw2JpgFromRawOffset;
1309    private boolean mIsSupportedFile;
1310
1311    // Pattern to check non zero timestamp
1312    private static final Pattern sNonZeroTimePattern = Pattern.compile(".*[1-9].*");
1313    // Pattern to check gps timestamp
1314    private static final Pattern sGpsTimestampPattern =
1315            Pattern.compile("^([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$");
1316
1317    /**
1318     * Reads Exif tags from the specified image file.
1319     */
1320    public ExifInterface(String filename) throws IOException {
1321        if (filename == null) {
1322            throw new IllegalArgumentException("filename cannot be null");
1323        }
1324        FileInputStream in = null;
1325        mAssetInputStream = null;
1326        mFilename = filename;
1327        mIsInputStream = false;
1328        try {
1329            in = new FileInputStream(filename);
1330            if (isSeekableFD(in.getFD())) {
1331                mSeekableFileDescriptor = in.getFD();
1332            } else {
1333                mSeekableFileDescriptor = null;
1334            }
1335            loadAttributes(in);
1336        } finally {
1337            IoUtils.closeQuietly(in);
1338        }
1339    }
1340
1341    /**
1342     * Reads Exif tags from the specified image file descriptor. Attribute mutation is supported
1343     * for writable and seekable file descriptors only. This constructor will not rewind the offset
1344     * of the given file descriptor. Developers should close the file descriptor after use.
1345     */
1346    public ExifInterface(FileDescriptor fileDescriptor) throws IOException {
1347        if (fileDescriptor == null) {
1348            throw new IllegalArgumentException("fileDescriptor cannot be null");
1349        }
1350        mAssetInputStream = null;
1351        mFilename = null;
1352        if (isSeekableFD(fileDescriptor)) {
1353            mSeekableFileDescriptor = fileDescriptor;
1354            // Keep the original file descriptor in order to save attributes when it's seekable.
1355            // Otherwise, just close the given file descriptor after reading it because the save
1356            // feature won't be working.
1357            try {
1358                fileDescriptor = Os.dup(fileDescriptor);
1359            } catch (ErrnoException e) {
1360                throw e.rethrowAsIOException();
1361            }
1362        } else {
1363            mSeekableFileDescriptor = null;
1364        }
1365        mIsInputStream = false;
1366        FileInputStream in = null;
1367        try {
1368            in = new FileInputStream(fileDescriptor);
1369            loadAttributes(in);
1370        } finally {
1371            IoUtils.closeQuietly(in);
1372        }
1373    }
1374
1375    /**
1376     * Reads Exif tags from the specified image input stream. Attribute mutation is not supported
1377     * for input streams. The given input stream will proceed its current position. Developers
1378     * should close the input stream after use.
1379     */
1380    public ExifInterface(InputStream inputStream) throws IOException {
1381        if (inputStream == null) {
1382            throw new IllegalArgumentException("inputStream cannot be null");
1383        }
1384        mFilename = null;
1385        if (inputStream instanceof AssetManager.AssetInputStream) {
1386            mAssetInputStream = (AssetManager.AssetInputStream) inputStream;
1387            mSeekableFileDescriptor = null;
1388        } else if (inputStream instanceof FileInputStream
1389                && isSeekableFD(((FileInputStream) inputStream).getFD())) {
1390            mAssetInputStream = null;
1391            mSeekableFileDescriptor = ((FileInputStream) inputStream).getFD();
1392        } else {
1393            mAssetInputStream = null;
1394            mSeekableFileDescriptor = null;
1395        }
1396        mIsInputStream = true;
1397        loadAttributes(inputStream);
1398    }
1399
1400    /**
1401     * Returns the EXIF attribute of the specified tag or {@code null} if there is no such tag in
1402     * the image file.
1403     *
1404     * @param tag the name of the tag.
1405     */
1406    private ExifAttribute getExifAttribute(String tag) {
1407        // Retrieves all tag groups. The value from primary image tag group has a higher priority
1408        // than the value from the thumbnail tag group if there are more than one candidates.
1409        for (int i = 0; i < EXIF_TAGS.length; ++i) {
1410            Object value = mAttributes[i].get(tag);
1411            if (value != null) {
1412                return (ExifAttribute) value;
1413            }
1414        }
1415        return null;
1416    }
1417
1418    /**
1419     * Returns the value of the specified tag or {@code null} if there
1420     * is no such tag in the image file.
1421     *
1422     * @param tag the name of the tag.
1423     */
1424    public String getAttribute(String tag) {
1425        ExifAttribute attribute = getExifAttribute(tag);
1426        if (attribute != null) {
1427            if (!sTagSetForCompatibility.contains(tag)) {
1428                return attribute.getStringValue(mExifByteOrder);
1429            }
1430            if (tag.equals(TAG_GPS_TIMESTAMP)) {
1431                // Convert the rational values to the custom formats for backwards compatibility.
1432                if (attribute.format != IFD_FORMAT_URATIONAL
1433                        && attribute.format != IFD_FORMAT_SRATIONAL) {
1434                    return null;
1435                }
1436                Rational[] array = (Rational[]) attribute.getValue(mExifByteOrder);
1437                if (array.length != 3) {
1438                    return null;
1439                }
1440                return String.format("%02d:%02d:%02d",
1441                        (int) ((float) array[0].numerator / array[0].denominator),
1442                        (int) ((float) array[1].numerator / array[1].denominator),
1443                        (int) ((float) array[2].numerator / array[2].denominator));
1444            }
1445            try {
1446                return Double.toString(attribute.getDoubleValue(mExifByteOrder));
1447            } catch (NumberFormatException e) {
1448                return null;
1449            }
1450        }
1451        return null;
1452    }
1453
1454    /**
1455     * Returns the integer value of the specified tag. If there is no such tag
1456     * in the image file or the value cannot be parsed as integer, return
1457     * <var>defaultValue</var>.
1458     *
1459     * @param tag the name of the tag.
1460     * @param defaultValue the value to return if the tag is not available.
1461     */
1462    public int getAttributeInt(String tag, int defaultValue) {
1463        ExifAttribute exifAttribute = getExifAttribute(tag);
1464        if (exifAttribute == null) {
1465            return defaultValue;
1466        }
1467
1468        try {
1469            return exifAttribute.getIntValue(mExifByteOrder);
1470        } catch (NumberFormatException e) {
1471            return defaultValue;
1472        }
1473    }
1474
1475    /**
1476     * Returns the double value of the tag that is specified as rational or contains a
1477     * double-formatted value. If there is no such tag in the image file or the value cannot be
1478     * parsed as double, return <var>defaultValue</var>.
1479     *
1480     * @param tag the name of the tag.
1481     * @param defaultValue the value to return if the tag is not available.
1482     */
1483    public double getAttributeDouble(String tag, double defaultValue) {
1484        ExifAttribute exifAttribute = getExifAttribute(tag);
1485        if (exifAttribute == null) {
1486            return defaultValue;
1487        }
1488
1489        try {
1490            return exifAttribute.getDoubleValue(mExifByteOrder);
1491        } catch (NumberFormatException e) {
1492            return defaultValue;
1493        }
1494    }
1495
1496    /**
1497     * Set the value of the specified tag.
1498     *
1499     * @param tag the name of the tag.
1500     * @param value the value of the tag.
1501     */
1502    public void setAttribute(String tag, String value) {
1503        // Convert the given value to rational values for backwards compatibility.
1504        if (value != null && sTagSetForCompatibility.contains(tag)) {
1505            if (tag.equals(TAG_GPS_TIMESTAMP)) {
1506                Matcher m = sGpsTimestampPattern.matcher(value);
1507                if (!m.find()) {
1508                    Log.w(TAG, "Invalid value for " + tag + " : " + value);
1509                    return;
1510                }
1511                value = Integer.parseInt(m.group(1)) + "/1," + Integer.parseInt(m.group(2)) + "/1,"
1512                        + Integer.parseInt(m.group(3)) + "/1";
1513            } else {
1514                try {
1515                    double doubleValue = Double.parseDouble(value);
1516                    value = (long) (doubleValue * 10000L) + "/10000";
1517                } catch (NumberFormatException e) {
1518                    Log.w(TAG, "Invalid value for " + tag + " : " + value);
1519                    return;
1520                }
1521            }
1522        }
1523
1524        for (int i = 0 ; i < EXIF_TAGS.length; ++i) {
1525            if (i == IFD_TYPE_THUMBNAIL && !mHasThumbnail) {
1526                continue;
1527            }
1528            final Object obj = sExifTagMapsForWriting[i].get(tag);
1529            if (obj != null) {
1530                if (value == null) {
1531                    mAttributes[i].remove(tag);
1532                    continue;
1533                }
1534                final ExifTag exifTag = (ExifTag) obj;
1535                Pair<Integer, Integer> guess = guessDataFormat(value);
1536                int dataFormat;
1537                if (exifTag.primaryFormat == guess.first || exifTag.primaryFormat == guess.second) {
1538                    dataFormat = exifTag.primaryFormat;
1539                } else if (exifTag.secondaryFormat != -1 && (exifTag.secondaryFormat == guess.first
1540                        || exifTag.secondaryFormat == guess.second)) {
1541                    dataFormat = exifTag.secondaryFormat;
1542                } else if (exifTag.primaryFormat == IFD_FORMAT_BYTE
1543                        || exifTag.primaryFormat == IFD_FORMAT_UNDEFINED
1544                        || exifTag.primaryFormat == IFD_FORMAT_STRING) {
1545                    dataFormat = exifTag.primaryFormat;
1546                } else {
1547                    Log.w(TAG, "Given tag (" + tag + ") value didn't match with one of expected "
1548                            + "formats: " + IFD_FORMAT_NAMES[exifTag.primaryFormat]
1549                            + (exifTag.secondaryFormat == -1 ? "" : ", "
1550                            + IFD_FORMAT_NAMES[exifTag.secondaryFormat]) + " (guess: "
1551                            + IFD_FORMAT_NAMES[guess.first] + (guess.second == -1 ? "" : ", "
1552                            + IFD_FORMAT_NAMES[guess.second]) + ")");
1553                    continue;
1554                }
1555                switch (dataFormat) {
1556                    case IFD_FORMAT_BYTE: {
1557                        mAttributes[i].put(tag, ExifAttribute.createByte(value));
1558                        break;
1559                    }
1560                    case IFD_FORMAT_UNDEFINED:
1561                    case IFD_FORMAT_STRING: {
1562                        mAttributes[i].put(tag, ExifAttribute.createString(value));
1563                        break;
1564                    }
1565                    case IFD_FORMAT_USHORT: {
1566                        final String[] values = value.split(",");
1567                        final int[] intArray = new int[values.length];
1568                        for (int j = 0; j < values.length; ++j) {
1569                            intArray[j] = Integer.parseInt(values[j]);
1570                        }
1571                        mAttributes[i].put(tag,
1572                                ExifAttribute.createUShort(intArray, mExifByteOrder));
1573                        break;
1574                    }
1575                    case IFD_FORMAT_SLONG: {
1576                        final String[] values = value.split(",");
1577                        final int[] intArray = new int[values.length];
1578                        for (int j = 0; j < values.length; ++j) {
1579                            intArray[j] = Integer.parseInt(values[j]);
1580                        }
1581                        mAttributes[i].put(tag,
1582                                ExifAttribute.createSLong(intArray, mExifByteOrder));
1583                        break;
1584                    }
1585                    case IFD_FORMAT_ULONG: {
1586                        final String[] values = value.split(",");
1587                        final long[] longArray = new long[values.length];
1588                        for (int j = 0; j < values.length; ++j) {
1589                            longArray[j] = Long.parseLong(values[j]);
1590                        }
1591                        mAttributes[i].put(tag,
1592                                ExifAttribute.createULong(longArray, mExifByteOrder));
1593                        break;
1594                    }
1595                    case IFD_FORMAT_URATIONAL: {
1596                        final String[] values = value.split(",");
1597                        final Rational[] rationalArray = new Rational[values.length];
1598                        for (int j = 0; j < values.length; ++j) {
1599                            final String[] numbers = values[j].split("/");
1600                            rationalArray[j] = new Rational(Long.parseLong(numbers[0]),
1601                                    Long.parseLong(numbers[1]));
1602                        }
1603                        mAttributes[i].put(tag,
1604                                ExifAttribute.createURational(rationalArray, mExifByteOrder));
1605                        break;
1606                    }
1607                    case IFD_FORMAT_SRATIONAL: {
1608                        final String[] values = value.split(",");
1609                        final Rational[] rationalArray = new Rational[values.length];
1610                        for (int j = 0; j < values.length; ++j) {
1611                            final String[] numbers = values[j].split("/");
1612                            rationalArray[j] = new Rational(Long.parseLong(numbers[0]),
1613                                    Long.parseLong(numbers[1]));
1614                        }
1615                        mAttributes[i].put(tag,
1616                                ExifAttribute.createSRational(rationalArray, mExifByteOrder));
1617                        break;
1618                    }
1619                    case IFD_FORMAT_DOUBLE: {
1620                        final String[] values = value.split(",");
1621                        final double[] doubleArray = new double[values.length];
1622                        for (int j = 0; j < values.length; ++j) {
1623                            doubleArray[j] = Double.parseDouble(values[j]);
1624                        }
1625                        mAttributes[i].put(tag,
1626                                ExifAttribute.createDouble(doubleArray, mExifByteOrder));
1627                        break;
1628                    }
1629                    default:
1630                        Log.w(TAG, "Data format isn't one of expected formats: " + dataFormat);
1631                        continue;
1632                }
1633            }
1634        }
1635    }
1636
1637    /**
1638     * Update the values of the tags in the tag groups if any value for the tag already was stored.
1639     *
1640     * @param tag the name of the tag.
1641     * @param value the value of the tag in a form of {@link ExifAttribute}.
1642     * @return Returns {@code true} if updating is placed.
1643     */
1644    private boolean updateAttribute(String tag, ExifAttribute value) {
1645        boolean updated = false;
1646        for (int i = 0 ; i < EXIF_TAGS.length; ++i) {
1647            if (mAttributes[i].containsKey(tag)) {
1648                mAttributes[i].put(tag, value);
1649                updated = true;
1650            }
1651        }
1652        return updated;
1653    }
1654
1655    /**
1656     * Remove any values of the specified tag.
1657     *
1658     * @param tag the name of the tag.
1659     */
1660    private void removeAttribute(String tag) {
1661        for (int i = 0 ; i < EXIF_TAGS.length; ++i) {
1662            mAttributes[i].remove(tag);
1663        }
1664    }
1665
1666    /**
1667     * This function decides which parser to read the image data according to the given input stream
1668     * type and the content of the input stream. In each case, it reads the first three bytes to
1669     * determine whether the image data format is JPEG or not.
1670     */
1671    private void loadAttributes(@NonNull InputStream in) throws IOException {
1672        try {
1673            // Initialize mAttributes.
1674            for (int i = 0; i < EXIF_TAGS.length; ++i) {
1675                mAttributes[i] = new HashMap();
1676            }
1677
1678            // Check file type
1679            in = new BufferedInputStream(in, SIGNATURE_CHECK_SIZE);
1680            mMimeType = getMimeType((BufferedInputStream) in);
1681
1682            // Create byte-ordered input stream
1683            ByteOrderedDataInputStream inputStream = new ByteOrderedDataInputStream(in);
1684
1685            switch (mMimeType) {
1686                case IMAGE_TYPE_JPEG: {
1687                    getJpegAttributes(inputStream, 0, IFD_TYPE_PRIMARY); // 0 is offset
1688                    break;
1689                }
1690                case IMAGE_TYPE_RAF: {
1691                    getRafAttributes(inputStream);
1692                    break;
1693                }
1694                case IMAGE_TYPE_ORF: {
1695                    getOrfAttributes(inputStream);
1696                    break;
1697                }
1698                case IMAGE_TYPE_RW2: {
1699                    getRw2Attributes(inputStream);
1700                    break;
1701                }
1702                case IMAGE_TYPE_ARW:
1703                case IMAGE_TYPE_CR2:
1704                case IMAGE_TYPE_DNG:
1705                case IMAGE_TYPE_NEF:
1706                case IMAGE_TYPE_NRW:
1707                case IMAGE_TYPE_PEF:
1708                case IMAGE_TYPE_SRW:
1709                case IMAGE_TYPE_UNKNOWN: {
1710                    getRawAttributes(inputStream);
1711                    break;
1712                }
1713                default: {
1714                    break;
1715                }
1716            }
1717            // Set thumbnail image offset and length
1718            setThumbnailData(inputStream);
1719            mIsSupportedFile = true;
1720        } catch (IOException e) {
1721            // Ignore exceptions in order to keep the compatibility with the old versions of
1722            // ExifInterface.
1723            mIsSupportedFile = false;
1724            if (DEBUG) {
1725                Log.w(TAG, "Invalid image: ExifInterface got an unsupported image format file"
1726                        + "(ExifInterface supports JPEG and some RAW image formats only) "
1727                        + "or a corrupted JPEG file to ExifInterface.", e);
1728            }
1729        } finally {
1730            addDefaultValuesForCompatibility();
1731
1732            if (DEBUG) {
1733                printAttributes();
1734            }
1735        }
1736    }
1737
1738    private static boolean isSeekableFD(FileDescriptor fd) throws IOException {
1739        try {
1740            Os.lseek(fd, 0, OsConstants.SEEK_CUR);
1741            return true;
1742        } catch (ErrnoException e) {
1743            return false;
1744        }
1745    }
1746
1747    // Prints out attributes for debugging.
1748    private void printAttributes() {
1749        for (int i = 0; i < mAttributes.length; ++i) {
1750            Log.d(TAG, "The size of tag group[" + i + "]: " + mAttributes[i].size());
1751            for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) {
1752                final ExifAttribute tagValue = (ExifAttribute) entry.getValue();
1753                Log.d(TAG, "tagName: " + entry.getKey() + ", tagType: " + tagValue.toString()
1754                        + ", tagValue: '" + tagValue.getStringValue(mExifByteOrder) + "'");
1755            }
1756        }
1757    }
1758
1759    /**
1760     * Save the tag data into the original image file. This is expensive because it involves
1761     * copying all the data from one file to another and deleting the old file and renaming the
1762     * other. It's best to use {@link #setAttribute(String,String)} to set all attributes to write
1763     * and make a single call rather than multiple calls for each attribute.
1764     */
1765    public void saveAttributes() throws IOException {
1766        if (!mIsSupportedFile || mMimeType != IMAGE_TYPE_JPEG) {
1767            throw new UnsupportedOperationException(
1768                    "ExifInterface only supports saving attributes on JPEG formats.");
1769        }
1770        if (mIsInputStream || (mSeekableFileDescriptor == null && mFilename == null)) {
1771            throw new UnsupportedOperationException(
1772                    "ExifInterface does not support saving attributes for the current input.");
1773        }
1774
1775        // Keep the thumbnail in memory
1776        mThumbnailBytes = getThumbnail();
1777
1778        FileInputStream in = null;
1779        FileOutputStream out = null;
1780        File tempFile = null;
1781        try {
1782            // Move the original file to temporary file.
1783            if (mFilename != null) {
1784                tempFile = new File(mFilename + ".tmp");
1785                File originalFile = new File(mFilename);
1786                if (!originalFile.renameTo(tempFile)) {
1787                    throw new IOException("Could'nt rename to " + tempFile.getAbsolutePath());
1788                }
1789            } else if (mSeekableFileDescriptor != null) {
1790                tempFile = File.createTempFile("temp", "jpg");
1791                Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET);
1792                in = new FileInputStream(mSeekableFileDescriptor);
1793                out = new FileOutputStream(tempFile);
1794                Streams.copy(in, out);
1795            }
1796        } catch (ErrnoException e) {
1797            throw e.rethrowAsIOException();
1798        } finally {
1799            IoUtils.closeQuietly(in);
1800            IoUtils.closeQuietly(out);
1801        }
1802
1803        in = null;
1804        out = null;
1805        try {
1806            // Save the new file.
1807            in = new FileInputStream(tempFile);
1808            if (mFilename != null) {
1809                out = new FileOutputStream(mFilename);
1810            } else if (mSeekableFileDescriptor != null) {
1811                Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET);
1812                out = new FileOutputStream(mSeekableFileDescriptor);
1813            }
1814            saveJpegAttributes(in, out);
1815        } catch (ErrnoException e) {
1816            throw e.rethrowAsIOException();
1817        } finally {
1818            IoUtils.closeQuietly(in);
1819            IoUtils.closeQuietly(out);
1820            tempFile.delete();
1821        }
1822
1823        // Discard the thumbnail in memory
1824        mThumbnailBytes = null;
1825    }
1826
1827    /**
1828     * Returns true if the image file has a thumbnail.
1829     */
1830    public boolean hasThumbnail() {
1831        return mHasThumbnail;
1832    }
1833
1834    /**
1835     * Returns the JPEG compressed thumbnail inside the image file, or {@code null} if there is no
1836     * JPEG compressed thumbnail.
1837     * The returned data can be decoded using
1838     * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)}
1839     */
1840    public byte[] getThumbnail() {
1841        if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) {
1842            return getThumbnailBytes();
1843        }
1844        return null;
1845    }
1846
1847    /**
1848     * Returns the thumbnail bytes inside the image file, regardless of the compression type of the
1849     * thumbnail image.
1850     */
1851    public byte[] getThumbnailBytes() {
1852        if (!mHasThumbnail) {
1853            return null;
1854        }
1855        if (mThumbnailBytes != null) {
1856            return mThumbnailBytes;
1857        }
1858
1859        // Read the thumbnail.
1860        InputStream in = null;
1861        try {
1862            if (mAssetInputStream != null) {
1863                in = mAssetInputStream;
1864                if (in.markSupported()) {
1865                    in.reset();
1866                } else {
1867                    Log.d(TAG, "Cannot read thumbnail from inputstream without mark/reset support");
1868                    return null;
1869                }
1870            } else if (mFilename != null) {
1871                in = new FileInputStream(mFilename);
1872            } else if (mSeekableFileDescriptor != null) {
1873                FileDescriptor fileDescriptor = Os.dup(mSeekableFileDescriptor);
1874                Os.lseek(fileDescriptor, 0, OsConstants.SEEK_SET);
1875                in = new FileInputStream(fileDescriptor);
1876            }
1877            if (in == null) {
1878                // Should not be reached this.
1879                throw new FileNotFoundException();
1880            }
1881            if (in.skip(mThumbnailOffset) != mThumbnailOffset) {
1882                throw new IOException("Corrupted image");
1883            }
1884            byte[] buffer = new byte[mThumbnailLength];
1885            if (in.read(buffer) != mThumbnailLength) {
1886                throw new IOException("Corrupted image");
1887            }
1888            mThumbnailBytes = buffer;
1889            return buffer;
1890        } catch (IOException | ErrnoException e) {
1891            // Couldn't get a thumbnail image.
1892            Log.d(TAG, "Encountered exception while getting thumbnail", e);
1893        } finally {
1894            IoUtils.closeQuietly(in);
1895        }
1896        return null;
1897    }
1898
1899    /**
1900     * Creates and returns a Bitmap object of the thumbnail image based on the byte array and the
1901     * thumbnail compression value, or {@code null} if the compression type is unsupported.
1902     */
1903    public Bitmap getThumbnailBitmap() {
1904        if (!mHasThumbnail) {
1905            return null;
1906        } else if (mThumbnailBytes == null) {
1907            mThumbnailBytes = getThumbnailBytes();
1908        }
1909
1910        if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) {
1911            return BitmapFactory.decodeByteArray(mThumbnailBytes, 0, mThumbnailLength);
1912        } else if (mThumbnailCompression == DATA_UNCOMPRESSED) {
1913            int[] rgbValues = new int[mThumbnailBytes.length / 3];
1914            byte alpha = (byte) 0xff000000;
1915            for (int i = 0; i < rgbValues.length; i++) {
1916                rgbValues[i] = alpha + (mThumbnailBytes[3 * i] << 16)
1917                        + (mThumbnailBytes[3 * i + 1] << 8) + mThumbnailBytes[3 * i + 2];
1918            }
1919
1920            ExifAttribute imageLengthAttribute =
1921                    (ExifAttribute) mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_IMAGE_LENGTH);
1922            ExifAttribute imageWidthAttribute =
1923                    (ExifAttribute) mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_IMAGE_WIDTH);
1924            if (imageLengthAttribute != null && imageWidthAttribute != null) {
1925                int imageLength = imageLengthAttribute.getIntValue(mExifByteOrder);
1926                int imageWidth = imageWidthAttribute.getIntValue(mExifByteOrder);
1927                return Bitmap.createBitmap(
1928                        rgbValues, imageWidth, imageLength, Bitmap.Config.ARGB_8888);
1929            }
1930        }
1931        return null;
1932    }
1933
1934    /**
1935     * Returns true if thumbnail image is JPEG Compressed, or false if either thumbnail image does
1936     * not exist or thumbnail image is uncompressed.
1937     */
1938    public boolean isThumbnailCompressed() {
1939        if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) {
1940            return true;
1941        }
1942        return false;
1943    }
1944
1945    /**
1946     * Returns the offset and length of thumbnail inside the image file, or
1947     * {@code null} if there is no thumbnail.
1948     *
1949     * @return two-element array, the offset in the first value, and length in
1950     *         the second, or {@code null} if no thumbnail was found.
1951     */
1952    public long[] getThumbnailRange() {
1953        if (!mHasThumbnail) {
1954            return null;
1955        }
1956
1957        long[] range = new long[2];
1958        range[0] = mThumbnailOffset;
1959        range[1] = mThumbnailLength;
1960
1961        return range;
1962    }
1963
1964    /**
1965     * Stores the latitude and longitude value in a float array. The first element is
1966     * the latitude, and the second element is the longitude. Returns false if the
1967     * Exif tags are not available.
1968     */
1969    public boolean getLatLong(float output[]) {
1970        String latValue = getAttribute(TAG_GPS_LATITUDE);
1971        String latRef = getAttribute(TAG_GPS_LATITUDE_REF);
1972        String lngValue = getAttribute(TAG_GPS_LONGITUDE);
1973        String lngRef = getAttribute(TAG_GPS_LONGITUDE_REF);
1974
1975        if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
1976            try {
1977                output[0] = convertRationalLatLonToFloat(latValue, latRef);
1978                output[1] = convertRationalLatLonToFloat(lngValue, lngRef);
1979                return true;
1980            } catch (IllegalArgumentException e) {
1981                // if values are not parseable
1982            }
1983        }
1984
1985        return false;
1986    }
1987
1988    /**
1989     * Return the altitude in meters. If the exif tag does not exist, return
1990     * <var>defaultValue</var>.
1991     *
1992     * @param defaultValue the value to return if the tag is not available.
1993     */
1994    public double getAltitude(double defaultValue) {
1995        double altitude = getAttributeDouble(TAG_GPS_ALTITUDE, -1);
1996        int ref = getAttributeInt(TAG_GPS_ALTITUDE_REF, -1);
1997
1998        if (altitude >= 0 && ref >= 0) {
1999            return (altitude * ((ref == 1) ? -1 : 1));
2000        } else {
2001            return defaultValue;
2002        }
2003    }
2004
2005    /**
2006     * Returns number of milliseconds since Jan. 1, 1970, midnight local time.
2007     * Returns -1 if the date time information if not available.
2008     * @hide
2009     */
2010    public long getDateTime() {
2011        String dateTimeString = getAttribute(TAG_DATETIME);
2012        if (dateTimeString == null
2013                || !sNonZeroTimePattern.matcher(dateTimeString).matches()) return -1;
2014
2015        ParsePosition pos = new ParsePosition(0);
2016        try {
2017            // The exif field is in local time. Parsing it as if it is UTC will yield time
2018            // since 1/1/1970 local time
2019            Date datetime = sFormatter.parse(dateTimeString, pos);
2020            if (datetime == null) return -1;
2021            long msecs = datetime.getTime();
2022
2023            String subSecs = getAttribute(TAG_SUBSEC_TIME);
2024            if (subSecs != null) {
2025                try {
2026                    long sub = Long.parseLong(subSecs);
2027                    while (sub > 1000) {
2028                        sub /= 10;
2029                    }
2030                    msecs += sub;
2031                } catch (NumberFormatException e) {
2032                    // Ignored
2033                }
2034            }
2035            return msecs;
2036        } catch (IllegalArgumentException e) {
2037            return -1;
2038        }
2039    }
2040
2041    /**
2042     * Returns number of milliseconds since Jan. 1, 1970, midnight UTC.
2043     * Returns -1 if the date time information if not available.
2044     * @hide
2045     */
2046    public long getGpsDateTime() {
2047        String date = getAttribute(TAG_GPS_DATESTAMP);
2048        String time = getAttribute(TAG_GPS_TIMESTAMP);
2049        if (date == null || time == null
2050                || (!sNonZeroTimePattern.matcher(date).matches()
2051                && !sNonZeroTimePattern.matcher(time).matches())) {
2052            return -1;
2053        }
2054
2055        String dateTimeString = date + ' ' + time;
2056
2057        ParsePosition pos = new ParsePosition(0);
2058        try {
2059            Date datetime = sFormatter.parse(dateTimeString, pos);
2060            if (datetime == null) return -1;
2061            return datetime.getTime();
2062        } catch (IllegalArgumentException e) {
2063            return -1;
2064        }
2065    }
2066
2067    private static float convertRationalLatLonToFloat(String rationalString, String ref) {
2068        try {
2069            String [] parts = rationalString.split(",");
2070
2071            String [] pair;
2072            pair = parts[0].split("/");
2073            double degrees = Double.parseDouble(pair[0].trim())
2074                    / Double.parseDouble(pair[1].trim());
2075
2076            pair = parts[1].split("/");
2077            double minutes = Double.parseDouble(pair[0].trim())
2078                    / Double.parseDouble(pair[1].trim());
2079
2080            pair = parts[2].split("/");
2081            double seconds = Double.parseDouble(pair[0].trim())
2082                    / Double.parseDouble(pair[1].trim());
2083
2084            double result = degrees + (minutes / 60.0) + (seconds / 3600.0);
2085            if ((ref.equals("S") || ref.equals("W"))) {
2086                return (float) -result;
2087            }
2088            return (float) result;
2089        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
2090            // Not valid
2091            throw new IllegalArgumentException();
2092        }
2093    }
2094
2095    // Checks the type of image file
2096    private int getMimeType(BufferedInputStream in) throws IOException {
2097        in.mark(SIGNATURE_CHECK_SIZE);
2098        byte[] signatureCheckBytes = new byte[SIGNATURE_CHECK_SIZE];
2099        if (in.read(signatureCheckBytes) != SIGNATURE_CHECK_SIZE) {
2100            throw new EOFException();
2101        }
2102        in.reset();
2103        if (isJpegFormat(signatureCheckBytes)) {
2104            return IMAGE_TYPE_JPEG;
2105        } else if (isRafFormat(signatureCheckBytes)) {
2106            return IMAGE_TYPE_RAF;
2107        } else if (isOrfFormat(signatureCheckBytes)) {
2108            return IMAGE_TYPE_ORF;
2109        } else if (isRw2Format(signatureCheckBytes)) {
2110            return IMAGE_TYPE_RW2;
2111        }
2112        // Certain file formats (PEF) are identified in readImageFileDirectory()
2113        return IMAGE_TYPE_UNKNOWN;
2114    }
2115
2116    /**
2117     * This method looks at the first 3 bytes to determine if this file is a JPEG file.
2118     * See http://www.media.mit.edu/pia/Research/deepview/exif.html, "JPEG format and Marker"
2119     */
2120    private static boolean isJpegFormat(byte[] signatureCheckBytes) throws IOException {
2121        for (int i = 0; i < JPEG_SIGNATURE.length; i++) {
2122            if (signatureCheckBytes[i] != JPEG_SIGNATURE[i]) {
2123                return false;
2124            }
2125        }
2126        return true;
2127    }
2128
2129    /**
2130     * This method looks at the first 15 bytes to determine if this file is a RAF file.
2131     * There is no official specification for RAF files from Fuji, but there is an online archive of
2132     * image file specifications:
2133     * http://fileformats.archiveteam.org/wiki/Fujifilm_RAF
2134     */
2135    private boolean isRafFormat(byte[] signatureCheckBytes) throws IOException {
2136        byte[] rafSignatureBytes = RAF_SIGNATURE.getBytes();
2137        for (int i = 0; i < rafSignatureBytes.length; i++) {
2138            if (signatureCheckBytes[i] != rafSignatureBytes[i]) {
2139                return false;
2140            }
2141        }
2142        return true;
2143    }
2144
2145    /**
2146     * ORF has a similar structure to TIFF but it contains a different signature at the TIFF Header.
2147     * This method looks at the 2 bytes following the Byte Order bytes to determine if this file is
2148     * an ORF file.
2149     * There is no official specification for ORF files from Olympus, but there is an online archive
2150     * of image file specifications:
2151     * http://fileformats.archiveteam.org/wiki/Olympus_ORF
2152     */
2153    private boolean isOrfFormat(byte[] signatureCheckBytes) throws IOException {
2154        ByteOrderedDataInputStream signatureInputStream =
2155                new ByteOrderedDataInputStream(signatureCheckBytes);
2156        // Read byte order
2157        mExifByteOrder = readByteOrder(signatureInputStream);
2158        // Set byte order
2159        signatureInputStream.setByteOrder(mExifByteOrder);
2160
2161        short orfSignature = signatureInputStream.readShort();
2162        if (orfSignature == ORF_SIGNATURE_1 || orfSignature == ORF_SIGNATURE_2) {
2163            return true;
2164        }
2165        return false;
2166    }
2167
2168    /**
2169     * RW2 is TIFF-based, but stores 0x55 signature byte instead of 0x42 at the header
2170     * See http://lclevy.free.fr/raw/
2171     */
2172    private boolean isRw2Format(byte[] signatureCheckBytes) throws IOException {
2173        ByteOrderedDataInputStream signatureInputStream =
2174                new ByteOrderedDataInputStream(signatureCheckBytes);
2175        // Read byte order
2176        mExifByteOrder = readByteOrder(signatureInputStream);
2177        // Set byte order
2178        signatureInputStream.setByteOrder(mExifByteOrder);
2179
2180        short signatureByte = signatureInputStream.readShort();
2181        if (signatureByte == RW2_SIGNATURE) {
2182            return true;
2183        }
2184        return false;
2185    }
2186
2187    /**
2188     * Loads EXIF attributes from a JPEG input stream.
2189     *
2190     * @param inputStream The input stream that starts with the JPEG data.
2191     * @param jpegOffset The offset value in input stream for JPEG data.
2192     * @param imageTypes The image type from which to retrieve metadata. Use IFD_TYPE_PRIMARY for
2193     *                   primary image, IFD_TYPE_PREVIEW for preview image, and
2194     *                   IFD_TYPE_THUMBNAIL for thumbnail image.
2195     * @throws IOException If the data contains invalid JPEG markers, offsets, or length values.
2196     */
2197    private void getJpegAttributes(ByteOrderedDataInputStream in, int jpegOffset, int imageType)
2198            throws IOException {
2199        // See JPEG File Interchange Format Specification, "JFIF Specification"
2200        if (DEBUG) {
2201            Log.d(TAG, "getJpegAttributes starting with: " + in);
2202        }
2203
2204        // JPEG uses Big Endian by default. See https://people.cs.umass.edu/~verts/cs32/endian.html
2205        in.setByteOrder(ByteOrder.BIG_ENDIAN);
2206
2207        // Skip to JPEG data
2208        in.seek(jpegOffset);
2209        int bytesRead = jpegOffset;
2210
2211        byte marker;
2212        if ((marker = in.readByte()) != MARKER) {
2213            throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff));
2214        }
2215        ++bytesRead;
2216        if (in.readByte() != MARKER_SOI) {
2217            throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff));
2218        }
2219        ++bytesRead;
2220        while (true) {
2221            marker = in.readByte();
2222            if (marker != MARKER) {
2223                throw new IOException("Invalid marker:" + Integer.toHexString(marker & 0xff));
2224            }
2225            ++bytesRead;
2226            marker = in.readByte();
2227            if (DEBUG) {
2228                Log.d(TAG, "Found JPEG segment indicator: " + Integer.toHexString(marker & 0xff));
2229            }
2230            ++bytesRead;
2231
2232            // EOI indicates the end of an image and in case of SOS, JPEG image stream starts and
2233            // the image data will terminate right after.
2234            if (marker == MARKER_EOI || marker == MARKER_SOS) {
2235                break;
2236            }
2237            int length = in.readUnsignedShort() - 2;
2238            bytesRead += 2;
2239            if (DEBUG) {
2240                Log.d(TAG, "JPEG segment: " + Integer.toHexString(marker & 0xff) + " (length: "
2241                        + (length + 2) + ")");
2242            }
2243            if (length < 0) {
2244                throw new IOException("Invalid length");
2245            }
2246            switch (marker) {
2247                case MARKER_APP1: {
2248                    if (DEBUG) {
2249                        Log.d(TAG, "MARKER_APP1");
2250                    }
2251                    if (length < 6) {
2252                        // Skip if it's not an EXIF APP1 segment.
2253                        break;
2254                    }
2255                    byte[] identifier = new byte[6];
2256                    if (in.read(identifier) != 6) {
2257                        throw new IOException("Invalid exif");
2258                    }
2259                    bytesRead += 6;
2260                    length -= 6;
2261                    if (!Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) {
2262                        // Skip if it's not an EXIF APP1 segment.
2263                        break;
2264                    }
2265                    if (length <= 0) {
2266                        throw new IOException("Invalid exif");
2267                    }
2268                    if (DEBUG) {
2269                        Log.d(TAG, "readExifSegment with a byte array (length: " + length + ")");
2270                    }
2271                    // Save offset values for createJpegThumbnailBitmap() function
2272                    mExifOffset = bytesRead;
2273
2274                    byte[] bytes = new byte[length];
2275                    if (in.read(bytes) != length) {
2276                        throw new IOException("Invalid exif");
2277                    }
2278                    bytesRead += length;
2279                    length = 0;
2280
2281                    readExifSegment(bytes, imageType);
2282                    break;
2283                }
2284
2285                case MARKER_COM: {
2286                    byte[] bytes = new byte[length];
2287                    if (in.read(bytes) != length) {
2288                        throw new IOException("Invalid exif");
2289                    }
2290                    length = 0;
2291                    if (getAttribute(TAG_USER_COMMENT) == null) {
2292                        mAttributes[IFD_TYPE_EXIF].put(TAG_USER_COMMENT, ExifAttribute.createString(
2293                                new String(bytes, ASCII)));
2294                    }
2295                    break;
2296                }
2297
2298                case MARKER_SOF0:
2299                case MARKER_SOF1:
2300                case MARKER_SOF2:
2301                case MARKER_SOF3:
2302                case MARKER_SOF5:
2303                case MARKER_SOF6:
2304                case MARKER_SOF7:
2305                case MARKER_SOF9:
2306                case MARKER_SOF10:
2307                case MARKER_SOF11:
2308                case MARKER_SOF13:
2309                case MARKER_SOF14:
2310                case MARKER_SOF15: {
2311                    if (in.skipBytes(1) != 1) {
2312                        throw new IOException("Invalid SOFx");
2313                    }
2314                    mAttributes[imageType].put(TAG_IMAGE_LENGTH, ExifAttribute.createULong(
2315                            in.readUnsignedShort(), mExifByteOrder));
2316                    mAttributes[imageType].put(TAG_IMAGE_WIDTH, ExifAttribute.createULong(
2317                            in.readUnsignedShort(), mExifByteOrder));
2318                    length -= 5;
2319                    break;
2320                }
2321
2322                default: {
2323                    break;
2324                }
2325            }
2326            if (length < 0) {
2327                throw new IOException("Invalid length");
2328            }
2329            if (in.skipBytes(length) != length) {
2330                throw new IOException("Invalid JPEG segment");
2331            }
2332            bytesRead += length;
2333        }
2334        // Restore original byte order
2335        in.setByteOrder(mExifByteOrder);
2336    }
2337
2338    private void getRawAttributes(ByteOrderedDataInputStream in) throws IOException {
2339        // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1.
2340        parseTiffHeaders(in, in.available());
2341
2342        // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6.
2343        readImageFileDirectory(in, IFD_TYPE_PRIMARY);
2344
2345        // Update ImageLength/Width tags for all image data.
2346        updateImageSizeValues(in, IFD_TYPE_PRIMARY);
2347        updateImageSizeValues(in, IFD_TYPE_PREVIEW);
2348        updateImageSizeValues(in, IFD_TYPE_THUMBNAIL);
2349
2350        // Check if each image data is in valid position.
2351        validateImages(in);
2352
2353        if (mMimeType == IMAGE_TYPE_PEF) {
2354            // PEF files contain a MakerNote data, which contains the data for ColorSpace tag.
2355            // See http://lclevy.free.fr/raw/ and piex.cc PefGetPreviewData()
2356            ExifAttribute makerNoteAttribute =
2357                    (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE);
2358            if (makerNoteAttribute != null) {
2359                // Create an ordered DataInputStream for MakerNote
2360                ByteOrderedDataInputStream makerNoteDataInputStream =
2361                        new ByteOrderedDataInputStream(makerNoteAttribute.bytes);
2362                makerNoteDataInputStream.setByteOrder(mExifByteOrder);
2363
2364                // Seek to MakerNote data
2365                makerNoteDataInputStream.seek(PEF_MAKER_NOTE_SKIP_SIZE);
2366
2367                // Read IFD data from MakerNote
2368                readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_PEF);
2369
2370                // Update ColorSpace tag
2371                ExifAttribute colorSpaceAttribute =
2372                        (ExifAttribute) mAttributes[IFD_TYPE_PEF].get(TAG_COLOR_SPACE);
2373                if (colorSpaceAttribute != null) {
2374                    mAttributes[IFD_TYPE_EXIF].put(TAG_COLOR_SPACE, colorSpaceAttribute);
2375                }
2376            }
2377        }
2378    }
2379
2380    /**
2381     * RAF files contains a JPEG and a CFA data.
2382     * The JPEG contains two images, a preview and a thumbnail, while the CFA contains a RAW image.
2383     * This method looks at the first 160 bytes of a RAF file to retrieve the offset and length
2384     * values for the JPEG and CFA data.
2385     * Using that data, it parses the JPEG data to retrieve the preview and thumbnail image data,
2386     * then parses the CFA metadata to retrieve the primary image length/width values.
2387     * For data format details, see http://fileformats.archiveteam.org/wiki/Fujifilm_RAF
2388     */
2389    private void getRafAttributes(ByteOrderedDataInputStream in) throws IOException {
2390        // Retrieve offset & length values
2391        in.skipBytes(RAF_OFFSET_TO_JPEG_IMAGE_OFFSET);
2392        byte[] jpegOffsetBytes = new byte[4];
2393        byte[] cfaHeaderOffsetBytes = new byte[4];
2394        in.read(jpegOffsetBytes);
2395        // Skip JPEG length value since it is not needed
2396        in.skipBytes(RAF_JPEG_LENGTH_VALUE_SIZE);
2397        in.read(cfaHeaderOffsetBytes);
2398        int rafJpegOffset = ByteBuffer.wrap(jpegOffsetBytes).getInt();
2399        int rafCfaHeaderOffset = ByteBuffer.wrap(cfaHeaderOffsetBytes).getInt();
2400
2401        // Retrieve JPEG image metadata
2402        getJpegAttributes(in, rafJpegOffset, IFD_TYPE_PREVIEW);
2403
2404        // Skip to CFA header offset.
2405        in.seek(rafCfaHeaderOffset);
2406
2407        // Retrieve primary image length/width values, if TAG_RAF_IMAGE_SIZE exists
2408        in.setByteOrder(ByteOrder.BIG_ENDIAN);
2409        int numberOfDirectoryEntry = in.readInt();
2410        if (DEBUG) {
2411            Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry);
2412        }
2413        // CFA stores some metadata about the RAW image. Since CFA uses proprietary tags, can only
2414        // find and retrieve image size information tags, while skipping others.
2415        // See piex.cc RafGetDimension()
2416        for (int i = 0; i < numberOfDirectoryEntry; ++i) {
2417            int tagNumber = in.readUnsignedShort();
2418            int numberOfBytes = in.readUnsignedShort();
2419            if (tagNumber == TAG_RAF_IMAGE_SIZE.number) {
2420                int imageLength = in.readShort();
2421                int imageWidth = in.readShort();
2422                ExifAttribute imageLengthAttribute =
2423                        ExifAttribute.createUShort(imageLength, mExifByteOrder);
2424                ExifAttribute imageWidthAttribute =
2425                        ExifAttribute.createUShort(imageWidth, mExifByteOrder);
2426                mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, imageLengthAttribute);
2427                mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, imageWidthAttribute);
2428                if (DEBUG) {
2429                    Log.d(TAG, "Updated to length: " + imageLength + ", width: " + imageWidth);
2430                }
2431                return;
2432            }
2433            in.skipBytes(numberOfBytes);
2434        }
2435    }
2436
2437    /**
2438     * ORF files contains a primary image data and a MakerNote data that contains preview/thumbnail
2439     * images. Both data takes the form of IFDs and can therefore be read with the
2440     * readImageFileDirectory() method.
2441     * This method reads all the necessary data and updates the primary/preview/thumbnail image
2442     * information according to the GetOlympusPreviewImage() method in piex.cc.
2443     * For data format details, see the following:
2444     * http://fileformats.archiveteam.org/wiki/Olympus_ORF
2445     * https://libopenraw.freedesktop.org/wiki/Olympus_ORF
2446     */
2447    private void getOrfAttributes(ByteOrderedDataInputStream in) throws IOException {
2448        // Retrieve primary image data
2449        // Other Exif data will be located in the Makernote.
2450        getRawAttributes(in);
2451
2452        // Additionally retrieve preview/thumbnail information from MakerNote tag, which contains
2453        // proprietary tags and therefore does not have offical documentation
2454        // See GetOlympusPreviewImage() in piex.cc & http://www.exiv2.org/tags-olympus.html
2455        ExifAttribute makerNoteAttribute =
2456                (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE);
2457        if (makerNoteAttribute != null) {
2458            // Create an ordered DataInputStream for MakerNote
2459            ByteOrderedDataInputStream makerNoteDataInputStream =
2460                    new ByteOrderedDataInputStream(makerNoteAttribute.bytes);
2461            makerNoteDataInputStream.setByteOrder(mExifByteOrder);
2462
2463            // There are two types of headers for Olympus MakerNotes
2464            // See http://www.exiv2.org/makernote.html#R1
2465            byte[] makerNoteHeader1Bytes = new byte[ORF_MAKER_NOTE_HEADER_1.length];
2466            makerNoteDataInputStream.readFully(makerNoteHeader1Bytes);
2467            makerNoteDataInputStream.seek(0);
2468            byte[] makerNoteHeader2Bytes = new byte[ORF_MAKER_NOTE_HEADER_2.length];
2469            makerNoteDataInputStream.readFully(makerNoteHeader2Bytes);
2470            // Skip the corresponding amount of bytes for each header type
2471            if (Arrays.equals(makerNoteHeader1Bytes, ORF_MAKER_NOTE_HEADER_1)) {
2472                makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_1_SIZE);
2473            } else if (Arrays.equals(makerNoteHeader2Bytes, ORF_MAKER_NOTE_HEADER_2)) {
2474                makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_2_SIZE);
2475            }
2476
2477            // Read IFD data from MakerNote
2478            readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_ORF_MAKER_NOTE);
2479
2480            // Retrieve & update preview image offset & length values
2481            ExifAttribute imageLengthAttribute = (ExifAttribute)
2482                    mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_START);
2483            ExifAttribute bitsPerSampleAttribute = (ExifAttribute)
2484                    mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_LENGTH);
2485
2486            if (imageLengthAttribute != null && bitsPerSampleAttribute != null) {
2487                mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT,
2488                        imageLengthAttribute);
2489                mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
2490                        bitsPerSampleAttribute);
2491            }
2492
2493            // TODO: Check this behavior in other ORF files
2494            // Retrieve primary image length & width values
2495            // See piex.cc GetOlympusPreviewImage()
2496            ExifAttribute aspectFrameAttribute = (ExifAttribute)
2497                    mAttributes[IFD_TYPE_ORF_IMAGE_PROCESSING].get(TAG_ORF_ASPECT_FRAME);
2498            if (aspectFrameAttribute != null) {
2499                int[] aspectFrameValues = new int[4];
2500                aspectFrameValues = (int[]) aspectFrameAttribute.getValue(mExifByteOrder);
2501                if (aspectFrameValues[2] > aspectFrameValues[0] &&
2502                        aspectFrameValues[3] > aspectFrameValues[1]) {
2503                    int primaryImageWidth = aspectFrameValues[2] - aspectFrameValues[0] + 1;
2504                    int primaryImageLength = aspectFrameValues[3] - aspectFrameValues[1] + 1;
2505                    // Swap width & length values
2506                    if (primaryImageWidth < primaryImageLength) {
2507                        primaryImageWidth += primaryImageLength;
2508                        primaryImageLength = primaryImageWidth - primaryImageLength;
2509                        primaryImageWidth -= primaryImageLength;
2510                    }
2511                    ExifAttribute primaryImageWidthAttribute =
2512                            ExifAttribute.createUShort(primaryImageWidth, mExifByteOrder);
2513                    ExifAttribute primaryImageLengthAttribute =
2514                            ExifAttribute.createUShort(primaryImageLength, mExifByteOrder);
2515
2516                    mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, primaryImageWidthAttribute);
2517                    mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, primaryImageLengthAttribute);
2518                }
2519            }
2520        }
2521    }
2522
2523    // RW2 contains the primary image data in IFD0 and the preview and/or thumbnail image data in
2524    // the JpgFromRaw tag
2525    // See https://libopenraw.freedesktop.org/wiki/Panasonic_RAW/ and piex.cc Rw2GetPreviewData()
2526    private void getRw2Attributes(ByteOrderedDataInputStream in) throws IOException {
2527        // Retrieve primary image data
2528        getRawAttributes(in);
2529
2530        // Retrieve preview and/or thumbnail image data
2531        ExifAttribute jpgFromRawAttribute =
2532                (ExifAttribute) mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_JPG_FROM_RAW);
2533        if (jpgFromRawAttribute != null) {
2534            getJpegAttributes(in, mRw2JpgFromRawOffset, IFD_TYPE_PREVIEW);
2535        }
2536
2537        // Set ISO tag value if necessary
2538        ExifAttribute rw2IsoAttribute =
2539                (ExifAttribute) mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_ISO);
2540        ExifAttribute exifIsoAttribute =
2541                (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_ISO_SPEED_RATINGS);
2542        if (rw2IsoAttribute != null && exifIsoAttribute == null) {
2543            // Place this attribute only if it doesn't exist
2544            mAttributes[IFD_TYPE_EXIF].put(TAG_ISO_SPEED_RATINGS, rw2IsoAttribute);
2545        }
2546    }
2547
2548    // Stores a new JPEG image with EXIF attributes into a given output stream.
2549    private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream)
2550            throws IOException {
2551        // See JPEG File Interchange Format Specification, "JFIF Specification"
2552        if (DEBUG) {
2553            Log.d(TAG, "saveJpegAttributes starting with (inputStream: " + inputStream
2554                    + ", outputStream: " + outputStream + ")");
2555        }
2556        DataInputStream dataInputStream = new DataInputStream(inputStream);
2557        ByteOrderedDataOutputStream dataOutputStream =
2558                new ByteOrderedDataOutputStream(outputStream, ByteOrder.BIG_ENDIAN);
2559        if (dataInputStream.readByte() != MARKER) {
2560            throw new IOException("Invalid marker");
2561        }
2562        dataOutputStream.writeByte(MARKER);
2563        if (dataInputStream.readByte() != MARKER_SOI) {
2564            throw new IOException("Invalid marker");
2565        }
2566        dataOutputStream.writeByte(MARKER_SOI);
2567
2568        // Write EXIF APP1 segment
2569        dataOutputStream.writeByte(MARKER);
2570        dataOutputStream.writeByte(MARKER_APP1);
2571        writeExifSegment(dataOutputStream, 6);
2572
2573        byte[] bytes = new byte[4096];
2574
2575        while (true) {
2576            byte marker = dataInputStream.readByte();
2577            if (marker != MARKER) {
2578                throw new IOException("Invalid marker");
2579            }
2580            marker = dataInputStream.readByte();
2581            switch (marker) {
2582                case MARKER_APP1: {
2583                    int length = dataInputStream.readUnsignedShort() - 2;
2584                    if (length < 0) {
2585                        throw new IOException("Invalid length");
2586                    }
2587                    byte[] identifier = new byte[6];
2588                    if (length >= 6) {
2589                        if (dataInputStream.read(identifier) != 6) {
2590                            throw new IOException("Invalid exif");
2591                        }
2592                        if (Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) {
2593                            // Skip the original EXIF APP1 segment.
2594                            if (dataInputStream.skipBytes(length - 6) != length - 6) {
2595                                throw new IOException("Invalid length");
2596                            }
2597                            break;
2598                        }
2599                    }
2600                    // Copy non-EXIF APP1 segment.
2601                    dataOutputStream.writeByte(MARKER);
2602                    dataOutputStream.writeByte(marker);
2603                    dataOutputStream.writeUnsignedShort(length + 2);
2604                    if (length >= 6) {
2605                        length -= 6;
2606                        dataOutputStream.write(identifier);
2607                    }
2608                    int read;
2609                    while (length > 0 && (read = dataInputStream.read(
2610                            bytes, 0, Math.min(length, bytes.length))) >= 0) {
2611                        dataOutputStream.write(bytes, 0, read);
2612                        length -= read;
2613                    }
2614                    break;
2615                }
2616                case MARKER_EOI:
2617                case MARKER_SOS: {
2618                    dataOutputStream.writeByte(MARKER);
2619                    dataOutputStream.writeByte(marker);
2620                    // Copy all the remaining data
2621                    Streams.copy(dataInputStream, dataOutputStream);
2622                    return;
2623                }
2624                default: {
2625                    // Copy JPEG segment
2626                    dataOutputStream.writeByte(MARKER);
2627                    dataOutputStream.writeByte(marker);
2628                    int length = dataInputStream.readUnsignedShort();
2629                    dataOutputStream.writeUnsignedShort(length);
2630                    length -= 2;
2631                    if (length < 0) {
2632                        throw new IOException("Invalid length");
2633                    }
2634                    int read;
2635                    while (length > 0 && (read = dataInputStream.read(
2636                            bytes, 0, Math.min(length, bytes.length))) >= 0) {
2637                        dataOutputStream.write(bytes, 0, read);
2638                        length -= read;
2639                    }
2640                    break;
2641                }
2642            }
2643        }
2644    }
2645
2646    // Reads the given EXIF byte area and save its tag data into attributes.
2647    private void readExifSegment(byte[] exifBytes, int imageType) throws IOException {
2648        ByteOrderedDataInputStream dataInputStream =
2649                new ByteOrderedDataInputStream(exifBytes);
2650
2651        // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1.
2652        parseTiffHeaders(dataInputStream, exifBytes.length);
2653
2654        // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6.
2655        readImageFileDirectory(dataInputStream, imageType);
2656    }
2657
2658    private void addDefaultValuesForCompatibility() {
2659        // The value of DATETIME tag has the same value of DATETIME_ORIGINAL tag.
2660        String valueOfDateTimeOriginal = getAttribute(TAG_DATETIME_ORIGINAL);
2661        if (valueOfDateTimeOriginal != null) {
2662            mAttributes[IFD_TYPE_PRIMARY].put(TAG_DATETIME,
2663                    ExifAttribute.createString(valueOfDateTimeOriginal));
2664        }
2665
2666        // Add the default value.
2667        if (getAttribute(TAG_IMAGE_WIDTH) == null) {
2668            mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH,
2669                    ExifAttribute.createULong(0, mExifByteOrder));
2670        }
2671        if (getAttribute(TAG_IMAGE_LENGTH) == null) {
2672            mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH,
2673                    ExifAttribute.createULong(0, mExifByteOrder));
2674        }
2675        if (getAttribute(TAG_ORIENTATION) == null) {
2676            mAttributes[IFD_TYPE_PRIMARY].put(TAG_ORIENTATION,
2677                    ExifAttribute.createULong(0, mExifByteOrder));
2678        }
2679        if (getAttribute(TAG_LIGHT_SOURCE) == null) {
2680            mAttributes[IFD_TYPE_EXIF].put(TAG_LIGHT_SOURCE,
2681                    ExifAttribute.createULong(0, mExifByteOrder));
2682        }
2683    }
2684
2685    private ByteOrder readByteOrder(ByteOrderedDataInputStream dataInputStream)
2686            throws IOException {
2687        // Read byte order.
2688        short byteOrder = dataInputStream.readShort();
2689        switch (byteOrder) {
2690            case BYTE_ALIGN_II:
2691                if (DEBUG) {
2692                    Log.d(TAG, "readExifSegment: Byte Align II");
2693                }
2694                return ByteOrder.LITTLE_ENDIAN;
2695            case BYTE_ALIGN_MM:
2696                if (DEBUG) {
2697                    Log.d(TAG, "readExifSegment: Byte Align MM");
2698                }
2699                return ByteOrder.BIG_ENDIAN;
2700            default:
2701                throw new IOException("Invalid byte order: " + Integer.toHexString(byteOrder));
2702        }
2703    }
2704
2705    private void parseTiffHeaders(ByteOrderedDataInputStream dataInputStream,
2706            int exifBytesLength) throws IOException {
2707        // Read byte order
2708        mExifByteOrder = readByteOrder(dataInputStream);
2709        // Set byte order
2710        dataInputStream.setByteOrder(mExifByteOrder);
2711
2712        // Check start code
2713        int startCode = dataInputStream.readUnsignedShort();
2714        if (mMimeType != IMAGE_TYPE_ORF && mMimeType != IMAGE_TYPE_RW2 && startCode != START_CODE) {
2715            throw new IOException("Invalid start code: " + Integer.toHexString(startCode));
2716        }
2717
2718        // Read and skip to first ifd offset
2719        int firstIfdOffset = dataInputStream.readInt();
2720        if (firstIfdOffset < 8 || firstIfdOffset >= exifBytesLength) {
2721            throw new IOException("Invalid first Ifd offset: " + firstIfdOffset);
2722        }
2723        firstIfdOffset -= 8;
2724        if (firstIfdOffset > 0) {
2725            if (dataInputStream.skipBytes(firstIfdOffset) != firstIfdOffset) {
2726                throw new IOException("Couldn't jump to first Ifd: " + firstIfdOffset);
2727            }
2728        }
2729    }
2730
2731    // Reads image file directory, which is a tag group in EXIF.
2732    private void readImageFileDirectory(ByteOrderedDataInputStream dataInputStream,
2733            @IfdType int ifdType) throws IOException {
2734        if (dataInputStream.mPosition + 2 > dataInputStream.mLength) {
2735            // Return if there is no data from the offset.
2736            return;
2737        }
2738        // See TIFF 6.0 Section 2: TIFF Structure, Figure 1.
2739        short numberOfDirectoryEntry = dataInputStream.readShort();
2740        if (dataInputStream.mPosition + 12 * numberOfDirectoryEntry > dataInputStream.mLength) {
2741            // Return if the size of entries is too big.
2742            return;
2743        }
2744
2745        if (DEBUG) {
2746            Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry);
2747        }
2748
2749        // See TIFF 6.0 Section 2: TIFF Structure, "Image File Directory".
2750        for (short i = 0; i < numberOfDirectoryEntry; ++i) {
2751            int tagNumber = dataInputStream.readUnsignedShort();
2752            int dataFormat = dataInputStream.readUnsignedShort();
2753            int numberOfComponents = dataInputStream.readInt();
2754            // Next four bytes is for data offset or value.
2755            long nextEntryOffset = dataInputStream.peek() + 4;
2756
2757            // Look up a corresponding tag from tag number
2758            ExifTag tag = (ExifTag) sExifTagMapsForReading[ifdType].get(tagNumber);
2759
2760            if (DEBUG) {
2761                Log.d(TAG, String.format("ifdType: %d, tagNumber: %d, tagName: %s, dataFormat: %d, "
2762                        + "numberOfComponents: %d", ifdType, tagNumber,
2763                        tag != null ? tag.name : null, dataFormat, numberOfComponents));
2764            }
2765
2766            if (tag == null || dataFormat <= 0 ||
2767                    dataFormat >= IFD_FORMAT_BYTES_PER_FORMAT.length) {
2768                // Skip if the parsed tag number is not defined or invalid data format.
2769                if (DEBUG) {
2770                    if (tag == null) {
2771                        Log.w(TAG, "Skip tag entry since tag number is not defined: " + tagNumber);
2772                    } else {
2773                        Log.w(TAG, "Skip tag entry since data format is invalid: " + dataFormat);
2774                    }
2775                }
2776                dataInputStream.seek(nextEntryOffset);
2777                continue;
2778            }
2779
2780            // Read a value from data field or seek to the value offset which is stored in data
2781            // field if the size of the entry value is bigger than 4.
2782            int byteCount = numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat];
2783            if (byteCount > 4) {
2784                int offset = dataInputStream.readInt();
2785                if (DEBUG) {
2786                    Log.d(TAG, "seek to data offset: " + offset);
2787                }
2788                if (mMimeType == IMAGE_TYPE_ORF) {
2789                    if (tag.name == TAG_MAKER_NOTE) {
2790                        // Save offset value for reading thumbnail
2791                        mOrfMakerNoteOffset = offset;
2792                    } else if (ifdType == IFD_TYPE_ORF_MAKER_NOTE
2793                            && tag.name == TAG_ORF_THUMBNAIL_IMAGE) {
2794                        // Retrieve & update values for thumbnail offset and length values for ORF
2795                        mOrfThumbnailOffset = offset;
2796                        mOrfThumbnailLength = numberOfComponents;
2797
2798                        ExifAttribute compressionAttribute =
2799                                ExifAttribute.createUShort(DATA_JPEG, mExifByteOrder);
2800                        ExifAttribute jpegInterchangeFormatAttribute =
2801                                ExifAttribute.createULong(mOrfThumbnailOffset, mExifByteOrder);
2802                        ExifAttribute jpegInterchangeFormatLengthAttribute =
2803                                ExifAttribute.createULong(mOrfThumbnailLength, mExifByteOrder);
2804
2805                        mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_COMPRESSION, compressionAttribute);
2806                        mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT,
2807                                jpegInterchangeFormatAttribute);
2808                        mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
2809                                jpegInterchangeFormatLengthAttribute);
2810                    }
2811                } else if (mMimeType == IMAGE_TYPE_RW2) {
2812                    if (tag.name == TAG_RW2_JPG_FROM_RAW) {
2813                        mRw2JpgFromRawOffset = offset;
2814                    }
2815                }
2816                if (offset + byteCount <= dataInputStream.mLength) {
2817                    dataInputStream.seek(offset);
2818                } else {
2819                    // Skip if invalid data offset.
2820                    Log.w(TAG, "Skip the tag entry since data offset is invalid: " + offset);
2821                    dataInputStream.seek(nextEntryOffset);
2822                    continue;
2823                }
2824            }
2825
2826            // Recursively parse IFD when a IFD pointer tag appears.
2827            Object nextIfdType = sExifPointerTagMap.get(tagNumber);
2828            if (DEBUG) {
2829                Log.d(TAG, "nextIfdType: " + nextIfdType + " byteCount: " + byteCount);
2830            }
2831
2832            if (nextIfdType != null) {
2833                long offset = -1L;
2834                // Get offset from data field
2835                switch (dataFormat) {
2836                    case IFD_FORMAT_USHORT: {
2837                        offset = dataInputStream.readUnsignedShort();
2838                        break;
2839                    }
2840                    case IFD_FORMAT_SSHORT: {
2841                        offset = dataInputStream.readShort();
2842                        break;
2843                    }
2844                    case IFD_FORMAT_ULONG: {
2845                        offset = dataInputStream.readUnsignedInt();
2846                        break;
2847                    }
2848                    case IFD_FORMAT_SLONG:
2849                    case IFD_FORMAT_IFD: {
2850                        offset = dataInputStream.readInt();
2851                        break;
2852                    }
2853                    default: {
2854                        // Nothing to do
2855                        break;
2856                    }
2857                }
2858                if (DEBUG) {
2859                    Log.d(TAG, String.format("Offset: %d, tagName: %s", offset, tag.name));
2860                }
2861                if (offset > 0L && offset < dataInputStream.mLength) {
2862                    dataInputStream.seek(offset);
2863                    readImageFileDirectory(dataInputStream, (int) nextIfdType);
2864                } else {
2865                    Log.w(TAG, "Skip jump into the IFD since its offset is invalid: " + offset);
2866                }
2867
2868                dataInputStream.seek(nextEntryOffset);
2869                continue;
2870            }
2871
2872            byte[] bytes = new byte[byteCount];
2873            dataInputStream.readFully(bytes);
2874            ExifAttribute attribute = new ExifAttribute(dataFormat, numberOfComponents, bytes);
2875            mAttributes[ifdType].put(tag.name, attribute);
2876
2877            // DNG files have a DNG Version tag specifying the version of specifications that the
2878            // image file is following.
2879            // See http://fileformats.archiveteam.org/wiki/DNG
2880            if (tag.name == TAG_DNG_VERSION) {
2881                mMimeType = IMAGE_TYPE_DNG;
2882            }
2883
2884            // PEF files have a Make or Model tag that begins with "PENTAX" or a compression tag
2885            // that is 65535.
2886            // See http://fileformats.archiveteam.org/wiki/Pentax_PEF
2887            if (((tag.name == TAG_MAKE || tag.name == TAG_MODEL)
2888                    && attribute.getStringValue(mExifByteOrder).contains(PEF_SIGNATURE))
2889                    || (tag.name == TAG_COMPRESSION
2890                    && attribute.getIntValue(mExifByteOrder) == 65535)) {
2891                mMimeType = IMAGE_TYPE_PEF;
2892            }
2893
2894            // Seek to next tag offset
2895            if (dataInputStream.peek() != nextEntryOffset) {
2896                dataInputStream.seek(nextEntryOffset);
2897            }
2898        }
2899
2900        if (dataInputStream.peek() + 4 <= dataInputStream.mLength) {
2901            int nextIfdOffset = dataInputStream.readInt();
2902            if (DEBUG) {
2903                Log.d(TAG, String.format("nextIfdOffset: %d", nextIfdOffset));
2904            }
2905            // The next IFD offset needs to be bigger than 8
2906            // since the first IFD offset is at least 8.
2907            if (nextIfdOffset > 8 && nextIfdOffset < dataInputStream.mLength) {
2908                dataInputStream.seek(nextIfdOffset);
2909                if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) {
2910                    // Do not overwrite thumbnail IFD data if it alreay exists.
2911                    readImageFileDirectory(dataInputStream, IFD_TYPE_THUMBNAIL);
2912                } else if (mAttributes[IFD_TYPE_PREVIEW].isEmpty()) {
2913                    readImageFileDirectory(dataInputStream, IFD_TYPE_PREVIEW);
2914                }
2915            }
2916        }
2917    }
2918
2919    /**
2920     * JPEG compressed images do not contain IMAGE_LENGTH & IMAGE_WIDTH tags.
2921     * This value uses JpegInterchangeFormat(JPEG data offset) value, and calls getJpegAttributes()
2922     * to locate SOF(Start of Frame) marker and update the image length & width values.
2923     * See JEITA CP-3451C Table 5 and Section 4.8.1. B.
2924     */
2925    private void retrieveJpegImageSize(ByteOrderedDataInputStream in, int imageType)
2926            throws IOException {
2927        // Check if image already has IMAGE_LENGTH & IMAGE_WIDTH values
2928        ExifAttribute imageLengthAttribute =
2929                (ExifAttribute) mAttributes[imageType].get(TAG_IMAGE_LENGTH);
2930        ExifAttribute imageWidthAttribute =
2931                (ExifAttribute) mAttributes[imageType].get(TAG_IMAGE_WIDTH);
2932
2933        if (imageLengthAttribute == null || imageWidthAttribute == null) {
2934            // Find if offset for JPEG data exists
2935            ExifAttribute jpegInterchangeFormatAttribute =
2936                    (ExifAttribute) mAttributes[imageType].get(TAG_JPEG_INTERCHANGE_FORMAT);
2937            if (jpegInterchangeFormatAttribute != null) {
2938                int jpegInterchangeFormat =
2939                        jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder);
2940
2941                // Searches for SOF marker in JPEG data and updates IMAGE_LENGTH & IMAGE_WIDTH tags
2942                getJpegAttributes(in, jpegInterchangeFormat, imageType);
2943            }
2944        }
2945    }
2946
2947    // Sets thumbnail offset & length attributes based on JpegInterchangeFormat or StripOffsets tags
2948    private void setThumbnailData(ByteOrderedDataInputStream in) throws IOException {
2949        HashMap thumbnailData = mAttributes[IFD_TYPE_THUMBNAIL];
2950
2951        ExifAttribute compressionAttribute =
2952                (ExifAttribute) thumbnailData.get(TAG_COMPRESSION);
2953        if (compressionAttribute != null) {
2954            mThumbnailCompression = compressionAttribute.getIntValue(mExifByteOrder);
2955            switch (mThumbnailCompression) {
2956                case DATA_JPEG: {
2957                    handleThumbnailFromJfif(in, thumbnailData);
2958                    break;
2959                }
2960                case DATA_UNCOMPRESSED:
2961                case DATA_JPEG_COMPRESSED: {
2962                    if (isSupportedDataType(thumbnailData)) {
2963                        handleThumbnailFromStrips(in, thumbnailData);
2964                    }
2965                    break;
2966                }
2967            }
2968        } else {
2969            // Thumbnail data may not contain Compression tag value
2970            mThumbnailCompression = DATA_JPEG;
2971            handleThumbnailFromJfif(in, thumbnailData);
2972        }
2973    }
2974
2975    // Check JpegInterchangeFormat(JFIF) tags to retrieve thumbnail offset & length values
2976    // and reads the corresponding bytes if stream does not support seek function
2977    private void handleThumbnailFromJfif(ByteOrderedDataInputStream in, HashMap thumbnailData)
2978            throws IOException {
2979        ExifAttribute jpegInterchangeFormatAttribute =
2980                (ExifAttribute) thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT);
2981        ExifAttribute jpegInterchangeFormatLengthAttribute =
2982                (ExifAttribute) thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH);
2983        if (jpegInterchangeFormatAttribute != null
2984                && jpegInterchangeFormatLengthAttribute != null) {
2985            int thumbnailOffset = jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder);
2986            int thumbnailLength = jpegInterchangeFormatLengthAttribute.getIntValue(mExifByteOrder);
2987
2988            // The following code limits the size of thumbnail size not to overflow EXIF data area.
2989            thumbnailLength = Math.min(thumbnailLength, in.available() - thumbnailOffset);
2990            if (mMimeType == IMAGE_TYPE_JPEG || mMimeType == IMAGE_TYPE_RAF
2991                    || mMimeType == IMAGE_TYPE_RW2) {
2992                thumbnailOffset += mExifOffset;
2993            } else if (mMimeType == IMAGE_TYPE_ORF) {
2994                // Update offset value since RAF files have IFD data preceding MakerNote data.
2995                thumbnailOffset += mOrfMakerNoteOffset;
2996            }
2997            if (DEBUG) {
2998                Log.d(TAG, "Setting thumbnail attributes with offset: " + thumbnailOffset
2999                        + ", length: " + thumbnailLength);
3000            }
3001            if (thumbnailOffset > 0 && thumbnailLength > 0) {
3002                mHasThumbnail = true;
3003                mThumbnailOffset = thumbnailOffset;
3004                mThumbnailLength = thumbnailLength;
3005                if (mFilename == null && mAssetInputStream == null
3006                        && mSeekableFileDescriptor == null) {
3007                    // Save the thumbnail in memory if the input doesn't support reading again.
3008                    byte[] thumbnailBytes = new byte[thumbnailLength];
3009                    in.seek(thumbnailOffset);
3010                    in.readFully(thumbnailBytes);
3011                    mThumbnailBytes = thumbnailBytes;
3012                }
3013            }
3014        }
3015    }
3016
3017    // Check StripOffsets & StripByteCounts tags to retrieve thumbnail offset & length values
3018    private void handleThumbnailFromStrips(ByteOrderedDataInputStream in, HashMap thumbnailData)
3019            throws IOException {
3020        ExifAttribute stripOffsetsAttribute =
3021                (ExifAttribute) thumbnailData.get(TAG_STRIP_OFFSETS);
3022        ExifAttribute stripByteCountsAttribute =
3023                (ExifAttribute) thumbnailData.get(TAG_STRIP_BYTE_COUNTS);
3024
3025        if (stripOffsetsAttribute != null && stripByteCountsAttribute != null) {
3026            long[] stripOffsets =
3027                    (long[]) stripOffsetsAttribute.getValue(mExifByteOrder);
3028            long[] stripByteCounts =
3029                    (long[]) stripByteCountsAttribute.getValue(mExifByteOrder);
3030
3031            // Set thumbnail byte array data for non-consecutive strip bytes
3032            byte[] totalStripBytes =
3033                    new byte[(int) Arrays.stream(stripByteCounts).sum()];
3034
3035            int bytesRead = 0;
3036            int bytesAdded = 0;
3037            for (int i = 0; i < stripOffsets.length; i++) {
3038                int stripOffset = (int) stripOffsets[i];
3039                int stripByteCount = (int) stripByteCounts[i];
3040
3041                // Skip to offset
3042                int skipBytes = stripOffset - bytesRead;
3043                if (skipBytes < 0) {
3044                    Log.d(TAG, "Invalid strip offset value");
3045                }
3046                in.seek(skipBytes);
3047                bytesRead += skipBytes;
3048
3049                // Read strip bytes
3050                byte[] stripBytes = new byte[stripByteCount];
3051                in.read(stripBytes);
3052                bytesRead += stripByteCount;
3053
3054                // Add bytes to array
3055                System.arraycopy(stripBytes, 0, totalStripBytes, bytesAdded,
3056                        stripBytes.length);
3057                bytesAdded += stripBytes.length;
3058            }
3059
3060            mHasThumbnail = true;
3061            mThumbnailBytes = totalStripBytes;
3062            mThumbnailLength = totalStripBytes.length;
3063        }
3064    }
3065
3066    // Check if thumbnail data type is currently supported or not
3067    private boolean isSupportedDataType(HashMap thumbnailData) throws IOException {
3068        ExifAttribute bitsPerSampleAttribute =
3069                (ExifAttribute) thumbnailData.get(TAG_BITS_PER_SAMPLE);
3070        if (bitsPerSampleAttribute != null) {
3071            int[] bitsPerSampleValue = (int[]) bitsPerSampleAttribute.getValue(mExifByteOrder);
3072
3073            if (Arrays.equals(BITS_PER_SAMPLE_RGB, bitsPerSampleValue)) {
3074                return true;
3075            }
3076
3077            // See DNG Specification 1.4.0.0. Section 3, Compression.
3078            if (mMimeType == IMAGE_TYPE_DNG) {
3079                ExifAttribute photometricInterpretationAttribute =
3080                        (ExifAttribute) thumbnailData.get(TAG_PHOTOMETRIC_INTERPRETATION);
3081                if (photometricInterpretationAttribute != null) {
3082                    int photometricInterpretationValue
3083                            = photometricInterpretationAttribute.getIntValue(mExifByteOrder);
3084                    if ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO
3085                            && Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_GREYSCALE_2))
3086                            || ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_YCBCR)
3087                            && (Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_RGB)))) {
3088                        return true;
3089                    } else {
3090                        // TODO: Add support for lossless Huffman JPEG data
3091                    }
3092                }
3093            }
3094        }
3095        if (DEBUG) {
3096            Log.d(TAG, "Unsupported data type value");
3097        }
3098        return false;
3099    }
3100
3101    // Returns true if the image length and width values are <= 512.
3102    // See Section 4.8 of http://standardsproposals.bsigroup.com/Home/getPDF/567
3103    private boolean isThumbnail(HashMap map) throws IOException {
3104        ExifAttribute imageLengthAttribute = (ExifAttribute) map.get(TAG_IMAGE_LENGTH);
3105        ExifAttribute imageWidthAttribute = (ExifAttribute) map.get(TAG_IMAGE_WIDTH);
3106
3107        if (imageLengthAttribute != null && imageWidthAttribute != null) {
3108            int imageLengthValue = imageLengthAttribute.getIntValue(mExifByteOrder);
3109            int imageWidthValue = imageWidthAttribute.getIntValue(mExifByteOrder);
3110            if (imageLengthValue <= MAX_THUMBNAIL_SIZE && imageWidthValue <= MAX_THUMBNAIL_SIZE) {
3111                return true;
3112            }
3113        }
3114        return false;
3115    }
3116
3117    // Validate primary, preview, thumbnail image data by comparing image size
3118    private void validateImages(InputStream in) throws IOException {
3119        // Swap images based on size (primary > preview > thumbnail)
3120        swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_PREVIEW);
3121        swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_THUMBNAIL);
3122        swapBasedOnImageSize(IFD_TYPE_PREVIEW, IFD_TYPE_THUMBNAIL);
3123
3124        // Check if image has PixelXDimension/PixelYDimension tags, which contain valid image
3125        // sizes, excluding padding at the right end or bottom end of the image to make sure that
3126        // the values are multiples of 64. See JEITA CP-3451C Table 5 and Section 4.8.1. B.
3127        ExifAttribute pixelXDimAttribute =
3128                (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_X_DIMENSION);
3129        ExifAttribute pixelYDimAttribute =
3130                (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_Y_DIMENSION);
3131        if (pixelXDimAttribute != null && pixelYDimAttribute != null) {
3132            mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, pixelXDimAttribute);
3133            mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, pixelYDimAttribute);
3134        }
3135
3136        // Check whether thumbnail image exists and whether preview image satisfies the thumbnail
3137        // image requirements
3138        if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) {
3139            if (isThumbnail(mAttributes[IFD_TYPE_PREVIEW])) {
3140                mAttributes[IFD_TYPE_THUMBNAIL] = mAttributes[IFD_TYPE_PREVIEW];
3141                mAttributes[IFD_TYPE_PREVIEW] = new HashMap();
3142            }
3143        }
3144
3145        // Check if the thumbnail image satisfies the thumbnail size requirements
3146        if (!isThumbnail(mAttributes[IFD_TYPE_THUMBNAIL])) {
3147            Log.d(TAG, "No image meets the size requirements of a thumbnail image.");
3148        }
3149    }
3150
3151    /**
3152     * If image is uncompressed, ImageWidth/Length tags are used to store size info.
3153     * However, uncompressed images often store extra pixels around the edges of the final image,
3154     * which results in larger values for TAG_IMAGE_WIDTH and TAG_IMAGE_LENGTH tags.
3155     * This method corrects those tag values by checking first the values of TAG_DEFAULT_CROP_SIZE
3156     * See DNG Specification 1.4.0.0. Section 4. (DefaultCropSize)
3157     *
3158     * If image is a RW2 file, valid image sizes are stored in SensorBorder tags.
3159     * See tiff_parser.cc GetFullDimension32()
3160     * */
3161    private void updateImageSizeValues(ByteOrderedDataInputStream in, int imageType)
3162            throws IOException {
3163        // Uncompressed image valid image size values
3164        ExifAttribute defaultCropSizeAttribute =
3165                (ExifAttribute) mAttributes[imageType].get(TAG_DEFAULT_CROP_SIZE);
3166        // RW2 image valid image size values
3167        ExifAttribute topBorderAttribute =
3168                (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_TOP_BORDER);
3169        ExifAttribute leftBorderAttribute =
3170                (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_LEFT_BORDER);
3171        ExifAttribute bottomBorderAttribute =
3172                (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_BOTTOM_BORDER);
3173        ExifAttribute rightBorderAttribute =
3174                (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_RIGHT_BORDER);
3175
3176        if (defaultCropSizeAttribute != null) {
3177            // Update for uncompressed image
3178            ExifAttribute defaultCropSizeXAttribute, defaultCropSizeYAttribute;
3179            if (defaultCropSizeAttribute.format == IFD_FORMAT_URATIONAL) {
3180                Rational[] defaultCropSizeValue =
3181                        (Rational[]) defaultCropSizeAttribute.getValue(mExifByteOrder);
3182                defaultCropSizeXAttribute =
3183                        ExifAttribute.createURational(defaultCropSizeValue[0], mExifByteOrder);
3184                defaultCropSizeYAttribute =
3185                        ExifAttribute.createURational(defaultCropSizeValue[1], mExifByteOrder);
3186            } else {
3187                int[] defaultCropSizeValue =
3188                        (int[]) defaultCropSizeAttribute.getValue(mExifByteOrder);
3189                defaultCropSizeXAttribute =
3190                        ExifAttribute.createUShort(defaultCropSizeValue[0], mExifByteOrder);
3191                defaultCropSizeYAttribute =
3192                        ExifAttribute.createUShort(defaultCropSizeValue[1], mExifByteOrder);
3193            }
3194            mAttributes[imageType].put(TAG_IMAGE_WIDTH, defaultCropSizeXAttribute);
3195            mAttributes[imageType].put(TAG_IMAGE_LENGTH, defaultCropSizeYAttribute);
3196        } else if (topBorderAttribute != null && leftBorderAttribute != null &&
3197                bottomBorderAttribute != null && rightBorderAttribute != null) {
3198            // Update for RW2 image
3199            int topBorderValue = topBorderAttribute.getIntValue(mExifByteOrder);
3200            int bottomBorderValue = bottomBorderAttribute.getIntValue(mExifByteOrder);
3201            int rightBorderValue = rightBorderAttribute.getIntValue(mExifByteOrder);
3202            int leftBorderValue = leftBorderAttribute.getIntValue(mExifByteOrder);
3203            if (bottomBorderValue > topBorderValue && rightBorderValue > leftBorderValue) {
3204                int length = bottomBorderValue - topBorderValue;
3205                int width = rightBorderValue - leftBorderValue;
3206                ExifAttribute imageLengthAttribute =
3207                        ExifAttribute.createUShort(length, mExifByteOrder);
3208                ExifAttribute imageWidthAttribute =
3209                        ExifAttribute.createUShort(width, mExifByteOrder);
3210                mAttributes[imageType].put(TAG_IMAGE_LENGTH, imageLengthAttribute);
3211                mAttributes[imageType].put(TAG_IMAGE_WIDTH, imageWidthAttribute);
3212            }
3213        } else {
3214            retrieveJpegImageSize(in, imageType);
3215        }
3216    }
3217
3218    // Writes an Exif segment into the given output stream.
3219    private int writeExifSegment(ByteOrderedDataOutputStream dataOutputStream,
3220            int exifOffsetFromBeginning) throws IOException {
3221        // The following variables are for calculating each IFD tag group size in bytes.
3222        int[] ifdOffsets = new int[EXIF_TAGS.length];
3223        int[] ifdDataSizes = new int[EXIF_TAGS.length];
3224
3225        // Remove IFD pointer tags (we'll re-add it later.)
3226        for (ExifTag tag : EXIF_POINTER_TAGS) {
3227            removeAttribute(tag.name);
3228        }
3229        // Remove old thumbnail data
3230        removeAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name);
3231        removeAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name);
3232
3233        // Remove null value tags.
3234        for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) {
3235            for (Object obj : mAttributes[ifdType].entrySet().toArray()) {
3236                final Map.Entry entry = (Map.Entry) obj;
3237                if (entry.getValue() == null) {
3238                    mAttributes[ifdType].remove(entry.getKey());
3239                }
3240            }
3241        }
3242
3243        // Add IFD pointer tags. The next offset of primary image TIFF IFD will have thumbnail IFD
3244        // offset when there is one or more tags in the thumbnail IFD.
3245        if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) {
3246            mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name,
3247                    ExifAttribute.createULong(0, mExifByteOrder));
3248        }
3249        if (!mAttributes[IFD_TYPE_GPS].isEmpty()) {
3250            mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name,
3251                    ExifAttribute.createULong(0, mExifByteOrder));
3252        }
3253        if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) {
3254            mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name,
3255                    ExifAttribute.createULong(0, mExifByteOrder));
3256        }
3257        if (mHasThumbnail) {
3258            mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_TAG.name,
3259                    ExifAttribute.createULong(0, mExifByteOrder));
3260            mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name,
3261                    ExifAttribute.createULong(mThumbnailLength, mExifByteOrder));
3262        }
3263
3264        // Calculate IFD group data area sizes. IFD group data area is assigned to save the entry
3265        // value which has a bigger size than 4 bytes.
3266        for (int i = 0; i < EXIF_TAGS.length; ++i) {
3267            int sum = 0;
3268            for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) {
3269                final ExifAttribute exifAttribute = (ExifAttribute) entry.getValue();
3270                final int size = exifAttribute.size();
3271                if (size > 4) {
3272                    sum += size;
3273                }
3274            }
3275            ifdDataSizes[i] += sum;
3276        }
3277
3278        // Calculate IFD offsets.
3279        int position = 8;
3280        for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) {
3281            if (!mAttributes[ifdType].isEmpty()) {
3282                ifdOffsets[ifdType] = position;
3283                position += 2 + mAttributes[ifdType].size() * 12 + 4 + ifdDataSizes[ifdType];
3284            }
3285        }
3286        if (mHasThumbnail) {
3287            int thumbnailOffset = position;
3288            mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_TAG.name,
3289                    ExifAttribute.createULong(thumbnailOffset, mExifByteOrder));
3290            mThumbnailOffset = exifOffsetFromBeginning + thumbnailOffset;
3291            position += mThumbnailLength;
3292        }
3293
3294        // Calculate the total size
3295        int totalSize = position + 8;  // eight bytes is for header part.
3296        if (DEBUG) {
3297            Log.d(TAG, "totalSize length: " + totalSize);
3298            for (int i = 0; i < EXIF_TAGS.length; ++i) {
3299                Log.d(TAG, String.format("index: %d, offsets: %d, tag count: %d, data sizes: %d",
3300                        i, ifdOffsets[i], mAttributes[i].size(), ifdDataSizes[i]));
3301            }
3302        }
3303
3304        // Update IFD pointer tags with the calculated offsets.
3305        if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) {
3306            mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name,
3307                    ExifAttribute.createULong(ifdOffsets[IFD_TYPE_EXIF], mExifByteOrder));
3308        }
3309        if (!mAttributes[IFD_TYPE_GPS].isEmpty()) {
3310            mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name,
3311                    ExifAttribute.createULong(ifdOffsets[IFD_TYPE_GPS], mExifByteOrder));
3312        }
3313        if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) {
3314            mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name, ExifAttribute.createULong(
3315                    ifdOffsets[IFD_TYPE_INTEROPERABILITY], mExifByteOrder));
3316        }
3317
3318        // Write TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1.
3319        dataOutputStream.writeUnsignedShort(totalSize);
3320        dataOutputStream.write(IDENTIFIER_EXIF_APP1);
3321        dataOutputStream.writeShort(mExifByteOrder == ByteOrder.BIG_ENDIAN
3322                ? BYTE_ALIGN_MM : BYTE_ALIGN_II);
3323        dataOutputStream.setByteOrder(mExifByteOrder);
3324        dataOutputStream.writeUnsignedShort(START_CODE);
3325        dataOutputStream.writeUnsignedInt(IFD_OFFSET);
3326
3327        // Write IFD groups. See JEITA CP-3451C Section 4.5.8. Figure 9.
3328        for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) {
3329            if (!mAttributes[ifdType].isEmpty()) {
3330                // See JEITA CP-3451C Section 4.6.2: IFD structure.
3331                // Write entry count
3332                dataOutputStream.writeUnsignedShort(mAttributes[ifdType].size());
3333
3334                // Write entry info
3335                int dataOffset = ifdOffsets[ifdType] + 2 + mAttributes[ifdType].size() * 12 + 4;
3336                for (Map.Entry entry : (Set<Map.Entry>) mAttributes[ifdType].entrySet()) {
3337                    // Convert tag name to tag number.
3338                    final ExifTag tag =
3339                            (ExifTag) sExifTagMapsForWriting[ifdType].get(entry.getKey());
3340                    final int tagNumber = tag.number;
3341                    final ExifAttribute attribute = (ExifAttribute) entry.getValue();
3342                    final int size = attribute.size();
3343
3344                    dataOutputStream.writeUnsignedShort(tagNumber);
3345                    dataOutputStream.writeUnsignedShort(attribute.format);
3346                    dataOutputStream.writeInt(attribute.numberOfComponents);
3347                    if (size > 4) {
3348                        dataOutputStream.writeUnsignedInt(dataOffset);
3349                        dataOffset += size;
3350                    } else {
3351                        dataOutputStream.write(attribute.bytes);
3352                        // Fill zero up to 4 bytes
3353                        if (size < 4) {
3354                            for (int i = size; i < 4; ++i) {
3355                                dataOutputStream.writeByte(0);
3356                            }
3357                        }
3358                    }
3359                }
3360
3361                // Write the next offset. It writes the offset of thumbnail IFD if there is one or
3362                // more tags in the thumbnail IFD when the current IFD is the primary image TIFF
3363                // IFD; Otherwise 0.
3364                if (ifdType == 0 && !mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) {
3365                    dataOutputStream.writeUnsignedInt(ifdOffsets[IFD_TYPE_THUMBNAIL]);
3366                } else {
3367                    dataOutputStream.writeUnsignedInt(0);
3368                }
3369
3370                // Write values of data field exceeding 4 bytes after the next offset.
3371                for (Map.Entry entry : (Set<Map.Entry>) mAttributes[ifdType].entrySet()) {
3372                    ExifAttribute attribute = (ExifAttribute) entry.getValue();
3373
3374                    if (attribute.bytes.length > 4) {
3375                        dataOutputStream.write(attribute.bytes, 0, attribute.bytes.length);
3376                    }
3377                }
3378            }
3379        }
3380
3381        // Write thumbnail
3382        if (mHasThumbnail) {
3383            dataOutputStream.write(getThumbnailBytes());
3384        }
3385
3386        // Reset the byte order to big endian in order to write remaining parts of the JPEG file.
3387        dataOutputStream.setByteOrder(ByteOrder.BIG_ENDIAN);
3388
3389        return totalSize;
3390    }
3391
3392    /**
3393     * Determines the data format of EXIF entry value.
3394     *
3395     * @param entryValue The value to be determined.
3396     * @return Returns two data formats gussed as a pair in integer. If there is no two candidate
3397               data formats for the given entry value, returns {@code -1} in the second of the pair.
3398     */
3399    private static Pair<Integer, Integer> guessDataFormat(String entryValue) {
3400        // See TIFF 6.0 Section 2, "Image File Directory".
3401        // Take the first component if there are more than one component.
3402        if (entryValue.contains(",")) {
3403            String[] entryValues = entryValue.split(",");
3404            Pair<Integer, Integer> dataFormat = guessDataFormat(entryValues[0]);
3405            if (dataFormat.first == IFD_FORMAT_STRING) {
3406                return dataFormat;
3407            }
3408            for (int i = 1; i < entryValues.length; ++i) {
3409                final Pair<Integer, Integer> guessDataFormat = guessDataFormat(entryValues[i]);
3410                int first = -1, second = -1;
3411                if (guessDataFormat.first == dataFormat.first
3412                        || guessDataFormat.second == dataFormat.first) {
3413                    first = dataFormat.first;
3414                }
3415                if (dataFormat.second != -1 && (guessDataFormat.first == dataFormat.second
3416                        || guessDataFormat.second == dataFormat.second)) {
3417                    second = dataFormat.second;
3418                }
3419                if (first == -1 && second == -1) {
3420                    return new Pair<>(IFD_FORMAT_STRING, -1);
3421                }
3422                if (first == -1) {
3423                    dataFormat = new Pair<>(second, -1);
3424                    continue;
3425                }
3426                if (second == -1) {
3427                    dataFormat = new Pair<>(first, -1);
3428                    continue;
3429                }
3430            }
3431            return dataFormat;
3432        }
3433
3434        if (entryValue.contains("/")) {
3435            String[] rationalNumber = entryValue.split("/");
3436            if (rationalNumber.length == 2) {
3437                try {
3438                    long numerator = Long.parseLong(rationalNumber[0]);
3439                    long denominator = Long.parseLong(rationalNumber[1]);
3440                    if (numerator < 0L || denominator < 0L) {
3441                        return new Pair<>(IFD_FORMAT_SRATIONAL, -1);
3442                    }
3443                    if (numerator > Integer.MAX_VALUE || denominator > Integer.MAX_VALUE) {
3444                        return new Pair<>(IFD_FORMAT_URATIONAL, -1);
3445                    }
3446                    return new Pair<>(IFD_FORMAT_SRATIONAL, IFD_FORMAT_URATIONAL);
3447                } catch (NumberFormatException e)  {
3448                    // Ignored
3449                }
3450            }
3451            return new Pair<>(IFD_FORMAT_STRING, -1);
3452        }
3453        try {
3454            Long longValue = Long.parseLong(entryValue);
3455            if (longValue >= 0 && longValue <= 65535) {
3456                return new Pair<>(IFD_FORMAT_USHORT, IFD_FORMAT_ULONG);
3457            }
3458            if (longValue < 0) {
3459                return new Pair<>(IFD_FORMAT_SLONG, -1);
3460            }
3461            return new Pair<>(IFD_FORMAT_ULONG, -1);
3462        } catch (NumberFormatException e) {
3463            // Ignored
3464        }
3465        try {
3466            Double.parseDouble(entryValue);
3467            return new Pair<>(IFD_FORMAT_DOUBLE, -1);
3468        } catch (NumberFormatException e) {
3469            // Ignored
3470        }
3471        return new Pair<>(IFD_FORMAT_STRING, -1);
3472    }
3473
3474    // An input stream to parse EXIF data area, which can be written in either little or big endian
3475    // order.
3476    private static class ByteOrderedDataInputStream extends InputStream implements DataInput {
3477        private static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN;
3478        private static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN;
3479
3480        private DataInputStream mDataInputStream;
3481        private InputStream mInputStream;
3482        private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN;
3483        private final int mLength;
3484        private int mPosition;
3485
3486        public ByteOrderedDataInputStream(InputStream in) throws IOException {
3487            mInputStream = in;
3488            mDataInputStream = new DataInputStream(in);
3489            mLength = mDataInputStream.available();
3490            mPosition = 0;
3491            mDataInputStream.mark(mLength);
3492        }
3493
3494        public ByteOrderedDataInputStream(byte[] bytes) throws IOException {
3495            this(new ByteArrayInputStream(bytes));
3496        }
3497
3498        public void setByteOrder(ByteOrder byteOrder) {
3499            mByteOrder = byteOrder;
3500        }
3501
3502        public void seek(long byteCount) throws IOException {
3503            if (mPosition > byteCount) {
3504                mPosition = 0;
3505                mDataInputStream.reset();
3506                mDataInputStream.mark(mLength);
3507            } else {
3508                byteCount -= mPosition;
3509            }
3510
3511            if (skipBytes((int) byteCount) != (int) byteCount) {
3512                throw new IOException("Couldn't seek up to the byteCount");
3513            }
3514        }
3515
3516        public int peek() {
3517            return mPosition;
3518        }
3519
3520        @Override
3521        public int available() throws IOException {
3522            return mDataInputStream.available();
3523        }
3524
3525        @Override
3526        public int read() throws IOException {
3527            ++mPosition;
3528            return mDataInputStream.read();
3529        }
3530
3531        @Override
3532        public int readUnsignedByte() throws IOException {
3533            ++mPosition;
3534            return mDataInputStream.readUnsignedByte();
3535        }
3536
3537        @Override
3538        public String readLine() throws IOException {
3539            Log.d(TAG, "Currently unsupported");
3540            return null;
3541        }
3542
3543        @Override
3544        public boolean readBoolean() throws IOException {
3545            ++mPosition;
3546            return mDataInputStream.readBoolean();
3547        }
3548
3549        @Override
3550        public char readChar() throws IOException {
3551            mPosition += 2;
3552            return mDataInputStream.readChar();
3553        }
3554
3555        @Override
3556        public String readUTF() throws IOException {
3557            mPosition += 2;
3558            return mDataInputStream.readUTF();
3559        }
3560
3561        @Override
3562        public void readFully(byte[] buffer, int offset, int length) throws IOException {
3563            mPosition += length;
3564            if (mPosition > mLength) {
3565                throw new EOFException();
3566            }
3567            if (mDataInputStream.read(buffer, offset, length) != length) {
3568                throw new IOException("Couldn't read up to the length of buffer");
3569            }
3570        }
3571
3572        @Override
3573        public void readFully(byte[] buffer) throws IOException {
3574            mPosition += buffer.length;
3575            if (mPosition > mLength) {
3576                throw new EOFException();
3577            }
3578            if (mDataInputStream.read(buffer, 0, buffer.length) != buffer.length) {
3579                throw new IOException("Couldn't read up to the length of buffer");
3580            }
3581        }
3582
3583        @Override
3584        public byte readByte() throws IOException {
3585            ++mPosition;
3586            if (mPosition > mLength) {
3587                throw new EOFException();
3588            }
3589            int ch = mDataInputStream.read();
3590            if (ch < 0) {
3591                throw new EOFException();
3592            }
3593            return (byte) ch;
3594        }
3595
3596        @Override
3597        public short readShort() throws IOException {
3598            mPosition += 2;
3599            if (mPosition > mLength) {
3600                throw new EOFException();
3601            }
3602            int ch1 = mDataInputStream.read();
3603            int ch2 = mDataInputStream.read();
3604            if ((ch1 | ch2) < 0) {
3605                throw new EOFException();
3606            }
3607            if (mByteOrder == LITTLE_ENDIAN) {
3608                return (short) ((ch2 << 8) + (ch1));
3609            } else if (mByteOrder == BIG_ENDIAN) {
3610                return (short) ((ch1 << 8) + (ch2));
3611            }
3612            throw new IOException("Invalid byte order: " + mByteOrder);
3613        }
3614
3615        @Override
3616        public int readInt() throws IOException {
3617            mPosition += 4;
3618            if (mPosition > mLength) {
3619                throw new EOFException();
3620            }
3621            int ch1 = mDataInputStream.read();
3622            int ch2 = mDataInputStream.read();
3623            int ch3 = mDataInputStream.read();
3624            int ch4 = mDataInputStream.read();
3625            if ((ch1 | ch2 | ch3 | ch4) < 0) {
3626                throw new EOFException();
3627            }
3628            if (mByteOrder == LITTLE_ENDIAN) {
3629                return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1);
3630            } else if (mByteOrder == BIG_ENDIAN) {
3631                return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4);
3632            }
3633            throw new IOException("Invalid byte order: " + mByteOrder);
3634        }
3635
3636        @Override
3637        public int skipBytes(int byteCount) throws IOException {
3638            int totalSkip = Math.min(byteCount, mLength - mPosition);
3639            int skipped = 0;
3640            while (skipped < totalSkip) {
3641                skipped += mDataInputStream.skipBytes(totalSkip - skipped);
3642            }
3643            mPosition += skipped;
3644            return skipped;
3645        }
3646
3647        public int readUnsignedShort() throws IOException {
3648            mPosition += 2;
3649            if (mPosition > mLength) {
3650                throw new EOFException();
3651            }
3652            int ch1 = mDataInputStream.read();
3653            int ch2 = mDataInputStream.read();
3654            if ((ch1 | ch2) < 0) {
3655                throw new EOFException();
3656            }
3657            if (mByteOrder == LITTLE_ENDIAN) {
3658                return ((ch2 << 8) + (ch1));
3659            } else if (mByteOrder == BIG_ENDIAN) {
3660                return ((ch1 << 8) + (ch2));
3661            }
3662            throw new IOException("Invalid byte order: " + mByteOrder);
3663        }
3664
3665        public long readUnsignedInt() throws IOException {
3666            return readInt() & 0xffffffffL;
3667        }
3668
3669        @Override
3670        public long readLong() throws IOException {
3671            mPosition += 8;
3672            if (mPosition > mLength) {
3673                throw new EOFException();
3674            }
3675            int ch1 = mDataInputStream.read();
3676            int ch2 = mDataInputStream.read();
3677            int ch3 = mDataInputStream.read();
3678            int ch4 = mDataInputStream.read();
3679            int ch5 = mDataInputStream.read();
3680            int ch6 = mDataInputStream.read();
3681            int ch7 = mDataInputStream.read();
3682            int ch8 = mDataInputStream.read();
3683            if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) {
3684                throw new EOFException();
3685            }
3686            if (mByteOrder == LITTLE_ENDIAN) {
3687                return (((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40)
3688                        + ((long) ch5 << 32) + ((long) ch4 << 24) + ((long) ch3 << 16)
3689                        + ((long) ch2 << 8) + (long) ch1);
3690            } else if (mByteOrder == BIG_ENDIAN) {
3691                return (((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40)
3692                        + ((long) ch4 << 32) + ((long) ch5 << 24) + ((long) ch6 << 16)
3693                        + ((long) ch7 << 8) + (long) ch8);
3694            }
3695            throw new IOException("Invalid byte order: " + mByteOrder);
3696        }
3697
3698        @Override
3699        public float readFloat() throws IOException {
3700            return Float.intBitsToFloat(readInt());
3701        }
3702
3703        @Override
3704        public double readDouble() throws IOException {
3705            return Double.longBitsToDouble(readLong());
3706        }
3707    }
3708
3709    // An output stream to write EXIF data area, which can be written in either little or big endian
3710    // order.
3711    private static class ByteOrderedDataOutputStream extends FilterOutputStream {
3712        private final OutputStream mOutputStream;
3713        private ByteOrder mByteOrder;
3714
3715        public ByteOrderedDataOutputStream(OutputStream out, ByteOrder byteOrder) {
3716            super(out);
3717            mOutputStream = out;
3718            mByteOrder = byteOrder;
3719        }
3720
3721        public void setByteOrder(ByteOrder byteOrder) {
3722            mByteOrder = byteOrder;
3723        }
3724
3725        public void write(byte[] bytes) throws IOException {
3726            mOutputStream.write(bytes);
3727        }
3728
3729        public void write(byte[] bytes, int offset, int length) throws IOException {
3730            mOutputStream.write(bytes, offset, length);
3731        }
3732
3733        public void writeByte(int val) throws IOException {
3734            mOutputStream.write(val);
3735        }
3736
3737        public void writeShort(short val) throws IOException {
3738            if (mByteOrder == ByteOrder.LITTLE_ENDIAN) {
3739                mOutputStream.write((val >>> 0) & 0xFF);
3740                mOutputStream.write((val >>> 8) & 0xFF);
3741            } else if (mByteOrder == ByteOrder.BIG_ENDIAN) {
3742                mOutputStream.write((val >>> 8) & 0xFF);
3743                mOutputStream.write((val >>> 0) & 0xFF);
3744            }
3745        }
3746
3747        public void writeInt(int val) throws IOException {
3748            if (mByteOrder == ByteOrder.LITTLE_ENDIAN) {
3749                mOutputStream.write((val >>> 0) & 0xFF);
3750                mOutputStream.write((val >>> 8) & 0xFF);
3751                mOutputStream.write((val >>> 16) & 0xFF);
3752                mOutputStream.write((val >>> 24) & 0xFF);
3753            } else if (mByteOrder == ByteOrder.BIG_ENDIAN) {
3754                mOutputStream.write((val >>> 24) & 0xFF);
3755                mOutputStream.write((val >>> 16) & 0xFF);
3756                mOutputStream.write((val >>> 8) & 0xFF);
3757                mOutputStream.write((val >>> 0) & 0xFF);
3758            }
3759        }
3760
3761        public void writeUnsignedShort(int val) throws IOException {
3762            writeShort((short) val);
3763        }
3764
3765        public void writeUnsignedInt(long val) throws IOException {
3766            writeInt((int) val);
3767        }
3768    }
3769
3770    // Swaps image data based on image size
3771    private void swapBasedOnImageSize(@IfdType int firstIfdType, @IfdType int secondIfdType)
3772            throws IOException {
3773        if (mAttributes[firstIfdType].isEmpty() || mAttributes[secondIfdType].isEmpty()) {
3774            if (DEBUG) {
3775                Log.d(TAG, "Cannot perform swap since only one image data exists");
3776            }
3777            return;
3778        }
3779
3780        ExifAttribute firstImageLengthAttribute =
3781                (ExifAttribute) mAttributes[firstIfdType].get(TAG_IMAGE_LENGTH);
3782        ExifAttribute firstImageWidthAttribute =
3783                (ExifAttribute) mAttributes[firstIfdType].get(TAG_IMAGE_WIDTH);
3784        ExifAttribute secondImageLengthAttribute =
3785                (ExifAttribute) mAttributes[secondIfdType].get(TAG_IMAGE_LENGTH);
3786        ExifAttribute secondImageWidthAttribute =
3787                (ExifAttribute) mAttributes[secondIfdType].get(TAG_IMAGE_WIDTH);
3788
3789        if (firstImageLengthAttribute == null || firstImageWidthAttribute == null) {
3790            if (DEBUG) {
3791                Log.d(TAG, "First image does not contain valid size information");
3792            }
3793        } else if (secondImageLengthAttribute == null || secondImageWidthAttribute == null) {
3794            if (DEBUG) {
3795                Log.d(TAG, "Second image does not contain valid size information");
3796            }
3797        } else {
3798            int firstImageLengthValue = firstImageLengthAttribute.getIntValue(mExifByteOrder);
3799            int firstImageWidthValue = firstImageWidthAttribute.getIntValue(mExifByteOrder);
3800            int secondImageLengthValue = secondImageLengthAttribute.getIntValue(mExifByteOrder);
3801            int secondImageWidthValue = secondImageWidthAttribute.getIntValue(mExifByteOrder);
3802
3803            if (firstImageLengthValue < secondImageLengthValue &&
3804                    firstImageWidthValue < secondImageWidthValue) {
3805                HashMap tempMap = mAttributes[firstIfdType];
3806                mAttributes[firstIfdType] = mAttributes[secondIfdType];
3807                mAttributes[secondIfdType] = tempMap;
3808            }
3809        }
3810    }
3811
3812    // Checks if there is a match
3813    private boolean containsMatch(byte[] mainBytes, byte[] findBytes) {
3814        for (int i = 0; i < mainBytes.length - findBytes.length; i++) {
3815            for (int j = 0; j < findBytes.length; j++) {
3816                if (mainBytes[i + j] != findBytes[j]) {
3817                    break;
3818                }
3819                if (j == findBytes.length - 1) {
3820                    return true;
3821                }
3822            }
3823        }
3824        return false;
3825    }
3826}
3827