ExifInterface.java revision f2a1076cd3d8fa1e5e6b9ced4380860e720675f7
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;
27
28import java.io.BufferedInputStream;
29import java.io.ByteArrayInputStream;
30import java.io.DataInputStream;
31import java.io.DataOutputStream;
32import java.io.EOFException;
33import java.io.File;
34import java.io.FileDescriptor;
35import java.io.FileInputStream;
36import java.io.FileNotFoundException;
37import java.io.FileOutputStream;
38import java.io.IOException;
39import java.io.InputStream;
40import java.io.OutputStream;
41import java.nio.ByteOrder;
42import java.nio.charset.Charset;
43import java.text.ParsePosition;
44import java.text.SimpleDateFormat;
45import java.util.Arrays;
46import java.util.Date;
47import java.util.HashMap;
48import java.util.Map;
49import java.util.Set;
50import java.util.TimeZone;
51import java.util.regex.Pattern;
52
53import libcore.io.IoUtils;
54import libcore.io.Streams;
55
56/**
57 * This is a class for reading and writing Exif tags in a JPEG file or a RAW image file.
58 * <p>
59 * Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF and RAF.
60 * <p>
61 * Attribute mutation is supported for JPEG image files.
62 */
63public class ExifInterface {
64    private static final String TAG = "ExifInterface";
65    private static final boolean DEBUG = false;
66
67    // The Exif tag names
68    /** Type is String. */
69    public static final String TAG_ARTIST = "Artist";
70    /** Type is int. */
71    public static final String TAG_BITS_PER_SAMPLE = "BitsPerSample";
72    /** Type is int. */
73    public static final String TAG_COMPRESSION = "Compression";
74    /** Type is String. */
75    public static final String TAG_COPYRIGHT = "Copyright";
76    /** Type is String. */
77    public static final String TAG_DATETIME = "DateTime";
78    /** Type is String. */
79    public static final String TAG_IMAGE_DESCRIPTION = "ImageDescription";
80    /** Type is int. */
81    public static final String TAG_IMAGE_LENGTH = "ImageLength";
82    /** Type is int. */
83    public static final String TAG_IMAGE_WIDTH = "ImageWidth";
84    /** Type is int. */
85    public static final String TAG_JPEG_INTERCHANGE_FORMAT = "JPEGInterchangeFormat";
86    /** Type is int. */
87    public static final String TAG_JPEG_INTERCHANGE_FORMAT_LENGTH = "JPEGInterchangeFormatLength";
88    /** Type is String. */
89    public static final String TAG_MAKE = "Make";
90    /** Type is String. */
91    public static final String TAG_MODEL = "Model";
92    /** Type is int. */
93    public static final String TAG_ORIENTATION = "Orientation";
94    /** Type is int. */
95    public static final String TAG_PHOTOMETRIC_INTERPRETATION = "PhotometricInterpretation";
96    /** Type is int. */
97    public static final String TAG_PLANAR_CONFIGURATION = "PlanarConfiguration";
98    /** Type is rational. */
99    public static final String TAG_PRIMARY_CHROMATICITIES = "PrimaryChromaticities";
100    /** Type is rational. */
101    public static final String TAG_REFERENCE_BLACK_WHITE = "ReferenceBlackWhite";
102    /** Type is int. */
103    public static final String TAG_RESOLUTION_UNIT = "ResolutionUnit";
104    /** Type is int. */
105    public static final String TAG_ROWS_PER_STRIP = "RowsPerStrip";
106    /** Type is int. */
107    public static final String TAG_SAMPLES_PER_PIXEL = "SamplesPerPixel";
108    /** Type is String. */
109    public static final String TAG_SOFTWARE = "Software";
110    /** Type is int. */
111    public static final String TAG_STRIP_BYTE_COUNTS = "StripByteCounts";
112    /** Type is int. */
113    public static final String TAG_STRIP_OFFSETS = "StripOffsets";
114    /** Type is int. */
115    public static final String TAG_TRANSFER_FUNCTION = "TransferFunction";
116    /** Type is rational. */
117    public static final String TAG_WHITE_POINT = "WhitePoint";
118    /** Type is rational. */
119    public static final String TAG_X_RESOLUTION = "XResolution";
120    /** Type is rational. */
121    public static final String TAG_Y_CB_CR_COEFFICIENTS = "YCbCrCoefficients";
122    /** Type is int. */
123    public static final String TAG_Y_CB_CR_POSITIONING = "YCbCrPositioning";
124    /** Type is int. */
125    public static final String TAG_Y_CB_CR_SUB_SAMPLING = "YCbCrSubSampling";
126    /** Type is rational. */
127    public static final String TAG_Y_RESOLUTION = "YResolution";
128    /** Type is rational. */
129    public static final String TAG_APERTURE_VALUE = "ApertureValue";
130    /** Type is rational. */
131    public static final String TAG_BRIGHTNESS_VALUE = "BrightnessValue";
132    /** Type is String. */
133    public static final String TAG_CFA_PATTERN = "CFAPattern";
134    /** Type is int. */
135    public static final String TAG_COLOR_SPACE = "ColorSpace";
136    /** Type is String. */
137    public static final String TAG_COMPONENTS_CONFIGURATION = "ComponentsConfiguration";
138    /** Type is rational. */
139    public static final String TAG_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel";
140    /** Type is int. */
141    public static final String TAG_CONTRAST = "Contrast";
142    /** Type is int. */
143    public static final String TAG_CUSTOM_RENDERED = "CustomRendered";
144    /** Type is String. */
145    public static final String TAG_DATETIME_DIGITIZED = "DateTimeDigitized";
146    /** Type is String. */
147    public static final String TAG_DATETIME_ORIGINAL = "DateTimeOriginal";
148    /** Type is String. */
149    public static final String TAG_DEVICE_SETTING_DESCRIPTION = "DeviceSettingDescription";
150    /** Type is double. */
151    public static final String TAG_DIGITAL_ZOOM_RATIO = "DigitalZoomRatio";
152    /** Type is String. */
153    public static final String TAG_EXIF_VERSION = "ExifVersion";
154    /** Type is double. */
155    public static final String TAG_EXPOSURE_BIAS_VALUE = "ExposureBiasValue";
156    /** Type is rational. */
157    public static final String TAG_EXPOSURE_INDEX = "ExposureIndex";
158    /** Type is int. */
159    public static final String TAG_EXPOSURE_MODE = "ExposureMode";
160    /** Type is int. */
161    public static final String TAG_EXPOSURE_PROGRAM = "ExposureProgram";
162    /** Type is double. */
163    public static final String TAG_EXPOSURE_TIME = "ExposureTime";
164    /** Type is String. */
165    public static final String TAG_F_NUMBER = "FNumber";
166    /** Type is String. */
167    public static final String TAG_APERTURE = "FNumber";
168    /** Type is String. */
169    public static final String TAG_FILE_SOURCE = "FileSource";
170    /** Type is int. */
171    public static final String TAG_FLASH = "Flash";
172    /** Type is rational. */
173    public static final String TAG_FLASH_ENERGY = "FlashEnergy";
174    /** Type is String. */
175    public static final String TAG_FLASHPIX_VERSION = "FlashpixVersion";
176    /** Type is rational. */
177    public static final String TAG_FOCAL_LENGTH = "FocalLength";
178    /** Type is int. */
179    public static final String TAG_FOCAL_LENGTH_IN_35MM_FILM = "FocalLengthIn35mmFilm";
180    /** Type is int. */
181    public static final String TAG_FOCAL_PLANE_RESOLUTION_UNIT = "FocalPlaneResolutionUnit";
182    /** Type is rational. */
183    public static final String TAG_FOCAL_PLANE_X_RESOLUTION = "FocalPlaneXResolution";
184    /** Type is rational. */
185    public static final String TAG_FOCAL_PLANE_Y_RESOLUTION = "FocalPlaneYResolution";
186    /** Type is rational. */
187    public static final String TAG_GAIN_CONTROL = "GainControl";
188    /** Type is String. */
189    public static final String TAG_ISO_SPEED_RATINGS = "ISOSpeedRatings";
190    /** Type is String. */
191    public static final String TAG_ISO = "ISOSpeedRatings";
192    /** Type is String. */
193    public static final String TAG_IMAGE_UNIQUE_ID = "ImageUniqueID";
194    /** Type is int. */
195    public static final String TAG_LIGHT_SOURCE = "LightSource";
196    /** Type is String. */
197    public static final String TAG_MAKER_NOTE = "MakerNote";
198    /** Type is rational. */
199    public static final String TAG_MAX_APERTURE_VALUE = "MaxApertureValue";
200    /** Type is int. */
201    public static final String TAG_METERING_MODE = "MeteringMode";
202    /** Type is String. */
203    public static final String TAG_OECF = "OECF";
204    /** Type is int. */
205    public static final String TAG_PIXEL_X_DIMENSION = "PixelXDimension";
206    /** Type is int. */
207    public static final String TAG_PIXEL_Y_DIMENSION = "PixelYDimension";
208    /** Type is String. */
209    public static final String TAG_RELATED_SOUND_FILE = "RelatedSoundFile";
210    /** Type is int. */
211    public static final String TAG_SATURATION = "Saturation";
212    /** Type is int. */
213    public static final String TAG_SCENE_CAPTURE_TYPE = "SceneCaptureType";
214    /** Type is String. */
215    public static final String TAG_SCENE_TYPE = "SceneType";
216    /** Type is int. */
217    public static final String TAG_SENSING_METHOD = "SensingMethod";
218    /** Type is int. */
219    public static final String TAG_SHARPNESS = "Sharpness";
220    /** Type is rational. */
221    public static final String TAG_SHUTTER_SPEED_VALUE = "ShutterSpeedValue";
222    /** Type is String. */
223    public static final String TAG_SPATIAL_FREQUENCY_RESPONSE = "SpatialFrequencyResponse";
224    /** Type is String. */
225    public static final String TAG_SPECTRAL_SENSITIVITY = "SpectralSensitivity";
226    /** Type is int. */
227    public static final String TAG_SUBSEC_TIME = "SubSecTime";
228    /** Type is int. @hide */
229    public static final String TAG_SUBSECTIME = "SubSecTime";
230    /** Type is int. */
231    public static final String TAG_SUBSEC_TIME_DIGITIZED = "SubSecTimeDigitized";
232    /** Type is int. */
233    public static final String TAG_SUBSEC_TIME_DIG = "SubSecTimeDigitized";
234    /** Type is int. */
235    public static final String TAG_SUBSEC_TIME_ORIG = "SubSecTimeOriginal";
236    /** Type is int. */
237    public static final String TAG_SUBSEC_TIME_ORIGINAL = "SubSecTimeOriginal";
238    /** Type is int. */
239    public static final String TAG_SUBJECT_AREA = "SubjectArea";
240    /** Type is double. */
241    public static final String TAG_SUBJECT_DISTANCE = "SubjectDistance";
242    /** Type is int. */
243    public static final String TAG_SUBJECT_DISTANCE_RANGE = "SubjectDistanceRange";
244    /** Type is int. */
245    public static final String TAG_SUBJECT_LOCATION = "SubjectLocation";
246    /** Type is String. */
247    public static final String TAG_USER_COMMENT = "UserComment";
248    /** Type is int. */
249    public static final String TAG_WHITE_BALANCE = "WhiteBalance";
250    /**
251     * The altitude (in meters) based on the reference in TAG_GPS_ALTITUDE_REF.
252     * Type is rational.
253     */
254    public static final String TAG_GPS_ALTITUDE = "GPSAltitude";
255    /**
256     * 0 if the altitude is above sea level. 1 if the altitude is below sea
257     * level. Type is int.
258     */
259    public static final String TAG_GPS_ALTITUDE_REF = "GPSAltitudeRef";
260    /** Type is String. */
261    public static final String TAG_GPS_AREA_INFORMATION = "GPSAreaInformation";
262    /** Type is rational. */
263    public static final String TAG_GPS_DOP = "GPSDOP";
264    /** Type is String. */
265    public static final String TAG_GPS_DATESTAMP = "GPSDateStamp";
266    /** Type is rational. */
267    public static final String TAG_GPS_DEST_BEARING = "GPSDestBearing";
268    /** Type is String. */
269    public static final String TAG_GPS_DEST_BEARING_REF = "GPSDestBearingRef";
270    /** Type is rational. */
271    public static final String TAG_GPS_DEST_DISTANCE = "GPSDestDistance";
272    /** Type is String. */
273    public static final String TAG_GPS_DEST_DISTANCE_REF = "GPSDestDistanceRef";
274    /** Type is rational. */
275    public static final String TAG_GPS_DEST_LATITUDE = "GPSDestLatitude";
276    /** Type is String. */
277    public static final String TAG_GPS_DEST_LATITUDE_REF = "GPSDestLatitudeRef";
278    /** Type is rational. */
279    public static final String TAG_GPS_DEST_LONGITUDE = "GPSDestLongitude";
280    /** Type is String. */
281    public static final String TAG_GPS_DEST_LONGITUDE_REF = "GPSDestLongitudeRef";
282    /** Type is int. */
283    public static final String TAG_GPS_DIFFERENTIAL = "GPSDifferential";
284    /** Type is rational. */
285    public static final String TAG_GPS_IMG_DIRECTION = "GPSImgDirection";
286    /** Type is String. */
287    public static final String TAG_GPS_IMG_DIRECTION_REF = "GPSImgDirectionRef";
288    /** String. Format is "num1/denom1,num2/denom2,num3/denom3". */
289    public static final String TAG_GPS_LATITUDE = "GPSLatitude";
290    /** Type is String. */
291    public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef";
292    /** String. Format is "num1/denom1,num2/denom2,num3/denom3". */
293    public static final String TAG_GPS_LONGITUDE = "GPSLongitude";
294    /** Type is String. */
295    public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef";
296    /** Type is String. */
297    public static final String TAG_GPS_MAP_DATUM = "GPSMapDatum";
298    /** Type is String. */
299    public static final String TAG_GPS_MEASURE_MODE = "GPSMeasureMode";
300    /** Type is String. Name of GPS processing method used for location finding. */
301    public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod";
302    /** Type is String. */
303    public static final String TAG_GPS_SATELLITES = "GPSSatellites";
304    /** Type is rational. */
305    public static final String TAG_GPS_SPEED = "GPSSpeed";
306    /** Type is String. */
307    public static final String TAG_GPS_SPEED_REF = "GPSSpeedRef";
308    /** Type is String. */
309    public static final String TAG_GPS_STATUS = "GPSStatus";
310    /** Type is String. */
311    public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp";
312    /** Type is rational. */
313    public static final String TAG_GPS_TRACK = "GPSTrack";
314    /** Type is String. */
315    public static final String TAG_GPS_TRACK_REF = "GPSTrackRef";
316    /** Type is String. */
317    public static final String TAG_GPS_VERSION_ID = "GPSVersionID";
318    /** Type is String. */
319    public static final String TAG_INTEROPERABILITY_INDEX = "InteroperabilityIndex";
320    /** Type is int. */
321    public static final String TAG_THUMBNAIL_IMAGE_LENGTH = "ThumbnailImageLength";
322    /** Type is int. */
323    public static final String TAG_THUMBNAIL_IMAGE_WIDTH = "ThumbnailImageWidth";
324
325    // Private tags used for pointing the other IFD offset. The types of the following tags are int.
326    private static final String TAG_EXIF_IFD_POINTER = "ExifIFDPointer";
327    private static final String TAG_GPS_INFO_IFD_POINTER = "GPSInfoIFDPointer";
328    private static final String TAG_INTEROPERABILITY_IFD_POINTER = "InteroperabilityIFDPointer";
329
330    // Private tags used for thumbnail information.
331    private static final String TAG_HAS_THUMBNAIL = "hasThumbnail";
332    private static final String TAG_THUMBNAIL_OFFSET = "thumbnailOffset";
333    private static final String TAG_THUMBNAIL_LENGTH = "thumbnailLength";
334    private static final String TAG_THUMBNAIL_DATA = "thumbnailData";
335
336    // Constants used for the Orientation Exif tag.
337    public static final int ORIENTATION_UNDEFINED = 0;
338    public static final int ORIENTATION_NORMAL = 1;
339    public static final int ORIENTATION_FLIP_HORIZONTAL = 2;  // left right reversed mirror
340    public static final int ORIENTATION_ROTATE_180 = 3;
341    public static final int ORIENTATION_FLIP_VERTICAL = 4;  // upside down mirror
342    // flipped about top-left <--> bottom-right axis
343    public static final int ORIENTATION_TRANSPOSE = 5;
344    public static final int ORIENTATION_ROTATE_90 = 6;  // rotate 90 cw to right it
345    // flipped about top-right <--> bottom-left axis
346    public static final int ORIENTATION_TRANSVERSE = 7;
347    public static final int ORIENTATION_ROTATE_270 = 8;  // rotate 270 to right it
348
349    // Constants used for white balance
350    public static final int WHITEBALANCE_AUTO = 0;
351    public static final int WHITEBALANCE_MANUAL = 1;
352
353    private static final byte[] JPEG_SIGNATURE = new byte[] {(byte) 0xff, (byte) 0xd8, (byte) 0xff};
354    private static final int JPEG_SIGNATURE_SIZE = 3;
355
356    private static SimpleDateFormat sFormatter;
357
358    // See Exchangeable image file format for digital still cameras: Exif version 2.2.
359    // The following values are for parsing EXIF data area. There are tag groups in EXIF data area.
360    // They are called "Image File Directory". They have multiple data formats to cover various
361    // image metadata from GPS longitude to camera model name.
362
363    // Types of Exif byte alignments (see JEITA CP-3451 page 10)
364    private static final short BYTE_ALIGN_II = 0x4949;  // II: Intel order
365    private static final short BYTE_ALIGN_MM = 0x4d4d;  // MM: Motorola order
366
367    // Formats for the value in IFD entry (See TIFF 6.0 spec Types page 15).
368    private static final int IFD_FORMAT_BYTE = 1;
369    private static final int IFD_FORMAT_STRING = 2;
370    private static final int IFD_FORMAT_USHORT = 3;
371    private static final int IFD_FORMAT_ULONG = 4;
372    private static final int IFD_FORMAT_URATIONAL = 5;
373    private static final int IFD_FORMAT_SBYTE = 6;
374    private static final int IFD_FORMAT_UNDEFINED = 7;
375    private static final int IFD_FORMAT_SSHORT = 8;
376    private static final int IFD_FORMAT_SLONG = 9;
377    private static final int IFD_FORMAT_SRATIONAL = 10;
378    private static final int IFD_FORMAT_SINGLE = 11;
379    private static final int IFD_FORMAT_DOUBLE = 12;
380    // Sizes of the components of each IFD value format
381    private static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[] {
382            0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8
383    };
384    private static final byte[] EXIF_ASCII_PREFIX = new byte[] {
385            0x41, 0x53, 0x43, 0x49, 0x49, 0x0, 0x0, 0x0
386    };
387
388    // A class for indicating EXIF tag.
389    private static class ExifTag {
390        public final int number;
391        public final String name;
392
393        private ExifTag(String name, int number) {
394            this.name = name;
395            this.number = number;
396        }
397    }
398
399    // Primary image IFD TIFF tags (See JEITA CP-3451 Table 14. page 54).
400    private static final ExifTag[] IFD_TIFF_TAGS = new ExifTag[] {
401            new ExifTag(TAG_IMAGE_WIDTH, 256),
402            new ExifTag(TAG_IMAGE_LENGTH, 257),
403            new ExifTag(TAG_BITS_PER_SAMPLE, 258),
404            new ExifTag(TAG_COMPRESSION, 259),
405            new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262),
406            new ExifTag(TAG_IMAGE_DESCRIPTION, 270),
407            new ExifTag(TAG_MAKE, 271),
408            new ExifTag(TAG_MODEL, 272),
409            new ExifTag(TAG_STRIP_OFFSETS, 273),
410            new ExifTag(TAG_ORIENTATION, 274),
411            new ExifTag(TAG_SAMPLES_PER_PIXEL, 277),
412            new ExifTag(TAG_ROWS_PER_STRIP, 278),
413            new ExifTag(TAG_STRIP_BYTE_COUNTS, 279),
414            new ExifTag(TAG_X_RESOLUTION, 282),
415            new ExifTag(TAG_Y_RESOLUTION, 283),
416            new ExifTag(TAG_PLANAR_CONFIGURATION, 284),
417            new ExifTag(TAG_RESOLUTION_UNIT, 296),
418            new ExifTag(TAG_TRANSFER_FUNCTION, 301),
419            new ExifTag(TAG_SOFTWARE, 305),
420            new ExifTag(TAG_DATETIME, 306),
421            new ExifTag(TAG_ARTIST, 315),
422            new ExifTag(TAG_WHITE_POINT, 318),
423            new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319),
424            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513),
425            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514),
426            new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529),
427            new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530),
428            new ExifTag(TAG_Y_CB_CR_POSITIONING, 531),
429            new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532),
430            new ExifTag(TAG_COPYRIGHT, 33432),
431            new ExifTag(TAG_EXIF_IFD_POINTER, 34665),
432            new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853),
433    };
434    // Primary image IFD Exif Private tags (See JEITA CP-3451 Table 15. page 55).
435    private static final ExifTag[] IFD_EXIF_TAGS = new ExifTag[] {
436            new ExifTag(TAG_EXPOSURE_TIME, 33434),
437            new ExifTag(TAG_F_NUMBER, 33437),
438            new ExifTag(TAG_EXPOSURE_PROGRAM, 34850),
439            new ExifTag(TAG_SPECTRAL_SENSITIVITY, 34852),
440            new ExifTag(TAG_ISO, 34855),
441            new ExifTag(TAG_OECF, 34856),
442            new ExifTag(TAG_EXIF_VERSION, 36864),
443            new ExifTag(TAG_DATETIME_ORIGINAL, 36867),
444            new ExifTag(TAG_DATETIME_DIGITIZED, 36868),
445            new ExifTag(TAG_COMPONENTS_CONFIGURATION, 37121),
446            new ExifTag(TAG_COMPRESSED_BITS_PER_PIXEL, 37122),
447            new ExifTag(TAG_SHUTTER_SPEED_VALUE, 37377),
448            new ExifTag(TAG_APERTURE_VALUE, 37378),
449            new ExifTag(TAG_BRIGHTNESS_VALUE, 37379),
450            new ExifTag(TAG_EXPOSURE_BIAS_VALUE, 37380),
451            new ExifTag(TAG_MAX_APERTURE_VALUE, 37381),
452            new ExifTag(TAG_SUBJECT_DISTANCE, 37382),
453            new ExifTag(TAG_METERING_MODE, 37383),
454            new ExifTag(TAG_LIGHT_SOURCE, 37384),
455            new ExifTag(TAG_FLASH, 37385),
456            new ExifTag(TAG_FOCAL_LENGTH, 37386),
457            new ExifTag(TAG_SUBJECT_AREA, 37396),
458            new ExifTag(TAG_MAKER_NOTE, 37500),
459            new ExifTag(TAG_USER_COMMENT, 37510),
460            new ExifTag(TAG_SUBSEC_TIME, 37520),
461            new ExifTag(TAG_SUBSEC_TIME_ORIG, 37521),
462            new ExifTag(TAG_SUBSEC_TIME_DIG, 37522),
463            new ExifTag(TAG_FLASHPIX_VERSION, 40960),
464            new ExifTag(TAG_COLOR_SPACE, 40961),
465            new ExifTag(TAG_PIXEL_X_DIMENSION, 40962),
466            new ExifTag(TAG_PIXEL_Y_DIMENSION, 40963),
467            new ExifTag(TAG_RELATED_SOUND_FILE, 40964),
468            new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965),
469            new ExifTag(TAG_FLASH_ENERGY, 41483),
470            new ExifTag(TAG_SPATIAL_FREQUENCY_RESPONSE, 41484),
471            new ExifTag(TAG_FOCAL_PLANE_X_RESOLUTION, 41486),
472            new ExifTag(TAG_FOCAL_PLANE_Y_RESOLUTION, 41487),
473            new ExifTag(TAG_FOCAL_PLANE_RESOLUTION_UNIT, 41488),
474            new ExifTag(TAG_SUBJECT_LOCATION, 41492),
475            new ExifTag(TAG_EXPOSURE_INDEX, 41493),
476            new ExifTag(TAG_SENSING_METHOD, 41495),
477            new ExifTag(TAG_FILE_SOURCE, 41728),
478            new ExifTag(TAG_SCENE_TYPE, 41729),
479            new ExifTag(TAG_CFA_PATTERN, 41730),
480            new ExifTag(TAG_CUSTOM_RENDERED, 41985),
481            new ExifTag(TAG_EXPOSURE_MODE, 41986),
482            new ExifTag(TAG_WHITE_BALANCE, 41987),
483            new ExifTag(TAG_DIGITAL_ZOOM_RATIO, 41988),
484            new ExifTag(TAG_FOCAL_LENGTH_IN_35MM_FILM, 41989),
485            new ExifTag(TAG_SCENE_CAPTURE_TYPE, 41990),
486            new ExifTag(TAG_GAIN_CONTROL, 41991),
487            new ExifTag(TAG_CONTRAST, 41992),
488            new ExifTag(TAG_SATURATION, 41993),
489            new ExifTag(TAG_SHARPNESS, 41994),
490            new ExifTag(TAG_DEVICE_SETTING_DESCRIPTION, 41995),
491            new ExifTag(TAG_SUBJECT_DISTANCE_RANGE, 41996),
492            new ExifTag(TAG_IMAGE_UNIQUE_ID, 42016),
493    };
494    // Primary image IFD GPS Info tags (See JEITA CP-3451 Table 16. page 56).
495    private static final ExifTag[] IFD_GPS_TAGS = new ExifTag[] {
496            new ExifTag(TAG_GPS_VERSION_ID, 0),
497            new ExifTag(TAG_GPS_LATITUDE_REF, 1),
498            new ExifTag(TAG_GPS_LATITUDE, 2),
499            new ExifTag(TAG_GPS_LONGITUDE_REF, 3),
500            new ExifTag(TAG_GPS_LONGITUDE, 4),
501            new ExifTag(TAG_GPS_ALTITUDE_REF, 5),
502            new ExifTag(TAG_GPS_ALTITUDE, 6),
503            new ExifTag(TAG_GPS_TIMESTAMP, 7),
504            new ExifTag(TAG_GPS_SATELLITES, 8),
505            new ExifTag(TAG_GPS_STATUS, 9),
506            new ExifTag(TAG_GPS_MEASURE_MODE, 10),
507            new ExifTag(TAG_GPS_DOP, 11),
508            new ExifTag(TAG_GPS_SPEED_REF, 12),
509            new ExifTag(TAG_GPS_SPEED, 13),
510            new ExifTag(TAG_GPS_TRACK_REF, 14),
511            new ExifTag(TAG_GPS_TRACK, 15),
512            new ExifTag(TAG_GPS_IMG_DIRECTION_REF, 16),
513            new ExifTag(TAG_GPS_IMG_DIRECTION, 17),
514            new ExifTag(TAG_GPS_MAP_DATUM, 18),
515            new ExifTag(TAG_GPS_DEST_LATITUDE_REF, 19),
516            new ExifTag(TAG_GPS_DEST_LATITUDE, 20),
517            new ExifTag(TAG_GPS_DEST_LONGITUDE_REF, 21),
518            new ExifTag(TAG_GPS_DEST_LONGITUDE, 22),
519            new ExifTag(TAG_GPS_DEST_BEARING_REF, 23),
520            new ExifTag(TAG_GPS_DEST_BEARING, 24),
521            new ExifTag(TAG_GPS_DEST_DISTANCE_REF, 25),
522            new ExifTag(TAG_GPS_DEST_DISTANCE, 26),
523            new ExifTag(TAG_GPS_PROCESSING_METHOD, 27),
524            new ExifTag(TAG_GPS_AREA_INFORMATION, 28),
525            new ExifTag(TAG_GPS_DATESTAMP, 29),
526            new ExifTag(TAG_GPS_DIFFERENTIAL, 30),
527    };
528    // Primary image IFD Interoperability tag (See JEITA CP-3451 Table 17. page 56).
529    private static final ExifTag[] IFD_INTEROPERABILITY_TAGS = new ExifTag[] {
530            new ExifTag(TAG_INTEROPERABILITY_INDEX, 1),
531    };
532    // IFD Thumbnail tags (See JEITA CP-3451 Table 18. page 57).
533    private static final ExifTag[] IFD_THUMBNAIL_TAGS = new ExifTag[] {
534            new ExifTag(TAG_THUMBNAIL_IMAGE_WIDTH, 256),
535            new ExifTag(TAG_THUMBNAIL_IMAGE_LENGTH, 257),
536            new ExifTag(TAG_BITS_PER_SAMPLE, 258),
537            new ExifTag(TAG_COMPRESSION, 259),
538            new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262),
539            new ExifTag(TAG_IMAGE_DESCRIPTION, 270),
540            new ExifTag(TAG_MAKE, 271),
541            new ExifTag(TAG_MODEL, 272),
542            new ExifTag(TAG_STRIP_OFFSETS, 273),
543            new ExifTag(TAG_ORIENTATION, 274),
544            new ExifTag(TAG_SAMPLES_PER_PIXEL, 277),
545            new ExifTag(TAG_ROWS_PER_STRIP, 278),
546            new ExifTag(TAG_STRIP_BYTE_COUNTS, 279),
547            new ExifTag(TAG_X_RESOLUTION, 282),
548            new ExifTag(TAG_Y_RESOLUTION, 283),
549            new ExifTag(TAG_PLANAR_CONFIGURATION, 284),
550            new ExifTag(TAG_RESOLUTION_UNIT, 296),
551            new ExifTag(TAG_TRANSFER_FUNCTION, 301),
552            new ExifTag(TAG_SOFTWARE, 305),
553            new ExifTag(TAG_DATETIME, 306),
554            new ExifTag(TAG_ARTIST, 315),
555            new ExifTag(TAG_WHITE_POINT, 318),
556            new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319),
557            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513),
558            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514),
559            new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529),
560            new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530),
561            new ExifTag(TAG_Y_CB_CR_POSITIONING, 531),
562            new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532),
563            new ExifTag(TAG_COPYRIGHT, 33432),
564            new ExifTag(TAG_EXIF_IFD_POINTER, 34665),
565            new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853),
566    };
567
568    // See JEITA CP-3451 Figure 5. page 9.
569    // The following values are used for indicating pointers to the other Image File Directorys.
570
571    // Indices of Exif Ifd tag groups
572    private static final int IFD_TIFF_HINT = 0;
573    private static final int IFD_EXIF_HINT = 1;
574    private static final int IFD_GPS_HINT = 2;
575    private static final int IFD_INTEROPERABILITY_HINT = 3;
576    private static final int IFD_THUMBNAIL_HINT = 4;
577    // List of Exif tag groups
578    private static final ExifTag[][] EXIF_TAGS = new ExifTag[][] {
579            IFD_TIFF_TAGS, IFD_EXIF_TAGS, IFD_GPS_TAGS, IFD_INTEROPERABILITY_TAGS,
580            IFD_THUMBNAIL_TAGS
581    };
582    // List of tags for pointing to the other image file directory offset.
583    private static final ExifTag[] IFD_POINTER_TAGS = new ExifTag[] {
584            new ExifTag(TAG_EXIF_IFD_POINTER, 34665),
585            new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853),
586            new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965),
587    };
588    // List of indices of the indicated tag groups according to the IFD_POINTER_TAGS
589    private static final int[] IFD_POINTER_TAG_HINTS = new int[] {
590            IFD_EXIF_HINT, IFD_GPS_HINT, IFD_INTEROPERABILITY_HINT
591    };
592    // Tags for indicating the thumbnail offset and length
593    private static final ExifTag JPEG_INTERCHANGE_FORMAT_TAG =
594            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513);
595    private static final ExifTag JPEG_INTERCHANGE_FORMAT_LENGTH_TAG =
596            new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514);
597
598    // Mappings from tag number to tag name and each item represents one IFD tag group.
599    private static final HashMap[] sExifTagMapsForReading = new HashMap[EXIF_TAGS.length];
600    // Mappings from tag name to tag number and each item represents one IFD tag group.
601    private static final HashMap[] sExifTagMapsForWriting = new HashMap[EXIF_TAGS.length];
602
603    // See JPEG File Interchange Format Version 1.02.
604    // The following values are defined for handling JPEG streams. In this implementation, we are
605    // not only getting information from EXIF but also from some JPEG special segments such as
606    // MARKER_COM for user comment and MARKER_SOFx for image width and height.
607
608    // Identifier for EXIF APP1 segment in JPEG
609    private static final byte[] IDENTIFIER_EXIF_APP1 =
610            "Exif\0\0".getBytes(Charset.forName("US-ASCII"));
611    // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with
612    // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start
613    // of frame(baseline DCT) and the image size info exists in its beginning part.
614    private static final byte MARKER = (byte) 0xff;
615    private static final byte MARKER_SOI = (byte) 0xd8;
616    private static final byte MARKER_SOF0 = (byte) 0xc0;
617    private static final byte MARKER_SOF1 = (byte) 0xc1;
618    private static final byte MARKER_SOF2 = (byte) 0xc2;
619    private static final byte MARKER_SOF3 = (byte) 0xc3;
620    private static final byte MARKER_SOF5 = (byte) 0xc5;
621    private static final byte MARKER_SOF6 = (byte) 0xc6;
622    private static final byte MARKER_SOF7 = (byte) 0xc7;
623    private static final byte MARKER_SOF9 = (byte) 0xc9;
624    private static final byte MARKER_SOF10 = (byte) 0xca;
625    private static final byte MARKER_SOF11 = (byte) 0xcb;
626    private static final byte MARKER_SOF13 = (byte) 0xcd;
627    private static final byte MARKER_SOF14 = (byte) 0xce;
628    private static final byte MARKER_SOF15 = (byte) 0xcf;
629    private static final byte MARKER_SOS = (byte) 0xda;
630    private static final byte MARKER_APP1 = (byte) 0xe1;
631    private static final byte MARKER_COM = (byte) 0xfe;
632    private static final byte MARKER_EOI = (byte) 0xd9;
633
634    static {
635        System.loadLibrary("media_jni");
636        nativeInitRaw();
637        sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
638        sFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
639
640        // Build up the hash tables to look up Exif tags for reading Exif tags.
641        for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
642            sExifTagMapsForReading[hint] = new HashMap();
643            sExifTagMapsForWriting[hint] = new HashMap();
644            for (ExifTag tag : EXIF_TAGS[hint]) {
645                sExifTagMapsForReading[hint].put(tag.number, tag.name);
646                sExifTagMapsForWriting[hint].put(tag.name, tag.number);
647            }
648        }
649    }
650
651    private final String mFilename;
652    private final FileDescriptor mSeekableFileDescriptor;
653    private final AssetManager.AssetInputStream mAssetInputStream;
654    private boolean mIsRaw;
655    private final HashMap[] mAttributes = new HashMap[EXIF_TAGS.length];
656    private boolean mHasThumbnail;
657    // The following values used for indicating a thumbnail position.
658    private int mThumbnailOffset;
659    private int mThumbnailLength;
660    private byte[] mThumbnailBytes;
661
662    // Pattern to check non zero timestamp
663    private static final Pattern sNonZeroTimePattern = Pattern.compile(".*[1-9].*");
664
665    /**
666     * Reads Exif tags from the specified image file.
667     */
668    public ExifInterface(String filename) throws IOException {
669        if (filename == null) {
670            throw new IllegalArgumentException("filename cannot be null");
671        }
672        FileInputStream in = new FileInputStream(filename);
673        mAssetInputStream = null;
674        mFilename = filename;
675        if (isSeekableFD(in.getFD())) {
676            mSeekableFileDescriptor = in.getFD();
677        } else {
678            mSeekableFileDescriptor = null;
679        }
680        loadAttributes(in);
681    }
682
683    /**
684     * Reads Exif tags from the specified image file descriptor. Attribute mutation is supported
685     * for seekable file descriptors only.
686     */
687    public ExifInterface(FileDescriptor fileDescriptor) throws IOException {
688        if (fileDescriptor == null) {
689            throw new IllegalArgumentException("parcelFileDescriptor cannot be null");
690        }
691        mAssetInputStream = null;
692        mFilename = null;
693        if (isSeekableFD(fileDescriptor)) {
694            mSeekableFileDescriptor = fileDescriptor;
695        } else {
696            mSeekableFileDescriptor = null;
697        }
698        loadAttributes(new FileInputStream(fileDescriptor));
699    }
700
701    /**
702     * Reads Exif tags from the specified image input stream. Attribute mutation is not supported
703     * for input streams.
704     */
705    public ExifInterface(InputStream inputStream) throws IOException {
706        if (inputStream == null) {
707            throw new IllegalArgumentException("inputStream cannot be null");
708        }
709        mFilename = null;
710        if (inputStream instanceof AssetManager.AssetInputStream) {
711            mAssetInputStream = (AssetManager.AssetInputStream) inputStream;
712            mSeekableFileDescriptor = null;
713        } else if (inputStream instanceof FileInputStream
714                && isSeekableFD(((FileInputStream) inputStream).getFD())) {
715            mAssetInputStream = null;
716            mSeekableFileDescriptor = ((FileInputStream) inputStream).getFD();
717        } else {
718            mAssetInputStream = null;
719            mSeekableFileDescriptor = null;
720        }
721        loadAttributes(inputStream);
722    }
723
724    /**
725     * Returns the value of the specified tag or {@code null} if there
726     * is no such tag in the image file.
727     *
728     * @param tag the name of the tag.
729     */
730    public String getAttribute(String tag) {
731        // Retrieves all tag groups. The value from primary image tag group has a higher priority
732        // than the value from the thumbnail tag group if there are more than one candidates.
733        for (int i = 0; i < EXIF_TAGS.length; ++i) {
734            Object value = mAttributes[i].get(tag);
735            if (value != null) {
736                return (String) value;
737            }
738        }
739        return null;
740    }
741
742    /**
743     * Returns the integer value of the specified tag. If there is no such tag
744     * in the image file or the value cannot be parsed as integer, return
745     * <var>defaultValue</var>.
746     *
747     * @param tag the name of the tag.
748     * @param defaultValue the value to return if the tag is not available.
749     */
750    public int getAttributeInt(String tag, int defaultValue) {
751        String value = getAttribute(tag);
752        if (value == null) return defaultValue;
753        try {
754            return Integer.valueOf(value);
755        } catch (NumberFormatException e) {
756            return defaultValue;
757        }
758    }
759
760    /**
761     * Returns the double value of the tag that is specified as rational or contains a
762     * double-formatted value. If there is no such tag in the image file or the value cannot be
763     * parsed as double, return <var>defaultValue</var>.
764     *
765     * @param tag the name of the tag.
766     * @param defaultValue the value to return if the tag is not available.
767     */
768    public double getAttributeDouble(String tag, double defaultValue) {
769        String value = getAttribute(tag);
770        if (value == null) return defaultValue;
771        try {
772            int index = value.indexOf("/");
773            if (index == -1) return Double.parseDouble(value);
774            double denom = Double.parseDouble(value.substring(index + 1));
775            if (denom == 0) return defaultValue;
776            double num = Double.parseDouble(value.substring(0, index));
777            return num / denom;
778        } catch (NumberFormatException e) {
779            return defaultValue;
780        }
781    }
782
783    /**
784     * Set the value of the specified tag.
785     *
786     * @param tag the name of the tag.
787     * @param value the value of the tag.
788     */
789    public void setAttribute(String tag, String value) {
790        for (int i = 0 ; i < EXIF_TAGS.length; ++i) {
791            if (sExifTagMapsForWriting[i].containsKey(tag)) {
792                mAttributes[i].put(tag, value);
793            }
794        }
795    }
796
797    /**
798     * This function decides which parser to read the image data according to the given input stream
799     * type and the content of the input stream. In each case, it reads the first three bytes to
800     * determine whether the image data format is JPEG or not.
801     */
802    private void loadAttributes(@NonNull InputStream in) throws IOException {
803        // Initialize mAttributes.
804        for (int i = 0; i < EXIF_TAGS.length; ++i) {
805            mAttributes[i] = new HashMap();
806        }
807
808        // Process RAW input stream
809        if (mAssetInputStream != null) {
810            long asset = mAssetInputStream.getNativeAsset();
811            if (handleRawResult(nativeGetRawAttributesFromAsset(asset))) {
812                return;
813            }
814        } else if (mSeekableFileDescriptor != null) {
815            if (handleRawResult(nativeGetRawAttributesFromFileDescriptor(
816                    mSeekableFileDescriptor))) {
817                return;
818            }
819        } else {
820            in = new BufferedInputStream(in, JPEG_SIGNATURE_SIZE);
821            if (!isJpegInputStream((BufferedInputStream) in) && handleRawResult(
822                    nativeGetRawAttributesFromInputStream(in))) {
823                return;
824            }
825        }
826
827        // Process JPEG input stream
828        try {
829            getJpegAttributes(in);
830        } catch (IOException e) {
831            // Ignore exceptions in order to keep the compatibility with the old versions of
832            // ExifInterface.
833            Log.w(TAG, "Invalid JPEG", e);
834        }
835
836        if (DEBUG) {
837            printAttributes();
838        }
839    }
840
841    private static boolean isJpegInputStream(BufferedInputStream in) throws IOException {
842        in.mark(JPEG_SIGNATURE_SIZE);
843        byte[] signatureBytes = new byte[JPEG_SIGNATURE_SIZE];
844        if (in.read(signatureBytes) != JPEG_SIGNATURE_SIZE) {
845            throw new EOFException();
846        }
847        boolean isJpeg = Arrays.equals(JPEG_SIGNATURE, signatureBytes);
848        in.reset();
849        return isJpeg;
850    }
851
852    private boolean handleRawResult(HashMap map) {
853        if (map == null) {
854            return false;
855        }
856
857        // Mark for disabling the save feature.
858        mIsRaw = true;
859
860        for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
861            String attrName = (String) entry.getKey();
862
863            switch (attrName) {
864                case TAG_HAS_THUMBNAIL:
865                    mHasThumbnail = ((String) entry.getValue()).equalsIgnoreCase("true");
866                    break;
867                case TAG_THUMBNAIL_OFFSET:
868                    mThumbnailOffset = Integer.parseInt((String) entry.getValue());
869                    break;
870                case TAG_THUMBNAIL_LENGTH:
871                    mThumbnailLength = Integer.parseInt((String) entry.getValue());
872                    break;
873                case TAG_THUMBNAIL_DATA:
874                    mThumbnailBytes = (byte[]) entry.getValue();
875                    break;
876                default:
877                    setAttribute(attrName, (String) entry.getValue());
878                    break;
879            }
880        }
881
882        if (DEBUG) {
883            printAttributes();
884        }
885        return true;
886    }
887
888    private static boolean isSeekableFD(FileDescriptor fd) throws IOException {
889        try {
890            Os.lseek(fd, 0, OsConstants.SEEK_CUR);
891            return true;
892        } catch (ErrnoException e) {
893            return false;
894        }
895    }
896
897    // Prints out attributes for debugging.
898    private void printAttributes() {
899        for (int i = 0; i < mAttributes.length; ++i) {
900            Log.d(TAG, "The size of tag group[" + i + "]: " + mAttributes[i].size());
901            for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) {
902                Log.d(TAG, "tagName: " + entry.getKey() + ", tagValue: " + entry.getValue());
903            }
904        }
905    }
906
907    /**
908     * Save the tag data into the original image file. This is expensive because it involves
909     * copying all the data from one file to another and deleting the old file and renaming the
910     * other. It's best to use{@link #setAttribute(String,String)} to set all attributes to write
911     * and make a single call rather than multiple calls for each attribute.
912     */
913    public void saveAttributes() throws IOException {
914        if (mIsRaw) {
915            throw new UnsupportedOperationException(
916                    "ExifInterface does not support saving attributes on RAW formats.");
917        }
918        if (mSeekableFileDescriptor == null && mFilename == null) {
919            throw new UnsupportedOperationException(
920                    "ExifInterface does not support saving attributes for the current input.");
921        }
922
923        // Keep the thumbnail in memory
924        mThumbnailBytes = getThumbnail();
925
926        FileInputStream in = null;
927        FileOutputStream out = null;
928        File tempFile = null;
929        try {
930            // Move the original file to temporary file.
931            if (mFilename != null) {
932                tempFile = new File(mFilename + ".tmp");
933                File originalFile = new File(mFilename);
934                if (!originalFile.renameTo(tempFile)) {
935                    throw new IOException("Could'nt rename to " + tempFile.getAbsolutePath());
936                }
937            } else if (mSeekableFileDescriptor != null) {
938                tempFile = File.createTempFile("temp", "jpg");
939                Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET);
940                in = new FileInputStream(mSeekableFileDescriptor);
941                out = new FileOutputStream(tempFile);
942                Streams.copy(in, out);
943            }
944        } catch (ErrnoException e) {
945            e.rethrowAsIOException();
946        } finally {
947            IoUtils.closeQuietly(in);
948            IoUtils.closeQuietly(out);
949        }
950
951        in = null;
952        out = null;
953        try {
954            // Save the new file.
955            in = new FileInputStream(tempFile);
956            if (mFilename != null) {
957                out = new FileOutputStream(mFilename);
958            } else if (mSeekableFileDescriptor != null) {
959                Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET);
960                out = new FileOutputStream(mSeekableFileDescriptor);
961            }
962            saveJpegAttributes(in, out);
963        } catch (ErrnoException e) {
964            e.rethrowAsIOException();
965        } finally {
966            IoUtils.closeQuietly(in);
967            IoUtils.closeQuietly(out);
968            tempFile.delete();
969        }
970
971        // Discard the thumbnail in memory
972        mThumbnailBytes = null;
973    }
974
975    /**
976     * Returns true if the image file has a thumbnail.
977     */
978    public boolean hasThumbnail() {
979        return mHasThumbnail;
980    }
981
982    /**
983     * Returns the thumbnail inside the image file, or {@code null} if there is no thumbnail.
984     * The returned data is in JPEG format and can be decoded using
985     * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)}
986     */
987    public byte[] getThumbnail() {
988        if (!mHasThumbnail) {
989            return null;
990        }
991        if (mThumbnailBytes != null) {
992            return mThumbnailBytes;
993        }
994
995        // Read the thumbnail.
996        FileInputStream in = null;
997        try {
998            if (mAssetInputStream != null) {
999                return nativeGetThumbnailFromAsset(
1000                        mAssetInputStream.getNativeAsset(), mThumbnailOffset, mThumbnailLength);
1001            } else if (mFilename != null) {
1002                in = new FileInputStream(mFilename);
1003            } else if (mSeekableFileDescriptor != null) {
1004                Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET);
1005                in = new FileInputStream(mSeekableFileDescriptor);
1006            }
1007            if (in == null) {
1008                // Should not be reached this.
1009                throw new FileNotFoundException();
1010            }
1011            if (in.skip(mThumbnailOffset) != mThumbnailOffset) {
1012                throw new IOException("Corrupted image");
1013            }
1014            byte[] buffer = new byte[mThumbnailLength];
1015            if (in.read(buffer) != mThumbnailLength) {
1016                throw new IOException("Corrupted image");
1017            }
1018            return buffer;
1019        } catch (IOException | ErrnoException e) {
1020            // Couldn't get a thumbnail image.
1021        } finally {
1022            IoUtils.closeQuietly(in);
1023        }
1024        return null;
1025    }
1026
1027    /**
1028     * Returns the offset and length of thumbnail inside the image file, or
1029     * {@code null} if there is no thumbnail.
1030     *
1031     * @return two-element array, the offset in the first value, and length in
1032     *         the second, or {@code null} if no thumbnail was found.
1033     * @hide
1034     */
1035    public long[] getThumbnailRange() {
1036        long[] range = new long[2];
1037        range[0] = mThumbnailOffset;
1038        range[1] = mThumbnailLength;
1039        return range;
1040    }
1041
1042    /**
1043     * Stores the latitude and longitude value in a float array. The first element is
1044     * the latitude, and the second element is the longitude. Returns false if the
1045     * Exif tags are not available.
1046     */
1047    public boolean getLatLong(float output[]) {
1048        String latValue = getAttribute(TAG_GPS_LATITUDE);
1049        String latRef = getAttribute(TAG_GPS_LATITUDE_REF);
1050        String lngValue = getAttribute(TAG_GPS_LONGITUDE);
1051        String lngRef = getAttribute(TAG_GPS_LONGITUDE_REF);
1052
1053        if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
1054            try {
1055                output[0] = convertRationalLatLonToFloat(latValue, latRef);
1056                output[1] = convertRationalLatLonToFloat(lngValue, lngRef);
1057                return true;
1058            } catch (IllegalArgumentException e) {
1059                // if values are not parseable
1060            }
1061        }
1062
1063        return false;
1064    }
1065
1066    /**
1067     * Return the altitude in meters. If the exif tag does not exist, return
1068     * <var>defaultValue</var>.
1069     *
1070     * @param defaultValue the value to return if the tag is not available.
1071     */
1072    public double getAltitude(double defaultValue) {
1073        double altitude = getAttributeDouble(TAG_GPS_ALTITUDE, -1);
1074        int ref = getAttributeInt(TAG_GPS_ALTITUDE_REF, -1);
1075
1076        if (altitude >= 0 && ref >= 0) {
1077            return (altitude * ((ref == 1) ? -1 : 1));
1078        } else {
1079            return defaultValue;
1080        }
1081    }
1082
1083    /**
1084     * Returns number of milliseconds since Jan. 1, 1970, midnight local time.
1085     * Returns -1 if the date time information if not available.
1086     * @hide
1087     */
1088    public long getDateTime() {
1089        String dateTimeString = getAttribute(TAG_DATETIME);
1090        if (dateTimeString == null
1091                || !sNonZeroTimePattern.matcher(dateTimeString).matches()) return -1;
1092
1093        ParsePosition pos = new ParsePosition(0);
1094        try {
1095            // The exif field is in local time. Parsing it as if it is UTC will yield time
1096            // since 1/1/1970 local time
1097            Date datetime = sFormatter.parse(dateTimeString, pos);
1098            if (datetime == null) return -1;
1099            long msecs = datetime.getTime();
1100
1101            String subSecs = getAttribute(TAG_SUBSECTIME);
1102            if (subSecs != null) {
1103                try {
1104                    long sub = Long.valueOf(subSecs);
1105                    while (sub > 1000) {
1106                        sub /= 10;
1107                    }
1108                    msecs += sub;
1109                } catch (NumberFormatException e) {
1110                    // Ignored
1111                }
1112            }
1113            return msecs;
1114        } catch (IllegalArgumentException e) {
1115            return -1;
1116        }
1117    }
1118
1119    /**
1120     * Returns number of milliseconds since Jan. 1, 1970, midnight UTC.
1121     * Returns -1 if the date time information if not available.
1122     * @hide
1123     */
1124    public long getGpsDateTime() {
1125        String date = getAttribute(TAG_GPS_DATESTAMP);
1126        String time = getAttribute(TAG_GPS_TIMESTAMP);
1127        if (date == null || time == null
1128                || (!sNonZeroTimePattern.matcher(date).matches()
1129                && !sNonZeroTimePattern.matcher(time).matches())) {
1130            return -1;
1131        }
1132
1133        String dateTimeString = date + ' ' + time;
1134
1135        ParsePosition pos = new ParsePosition(0);
1136        try {
1137            Date datetime = sFormatter.parse(dateTimeString, pos);
1138            if (datetime == null) return -1;
1139            return datetime.getTime();
1140        } catch (IllegalArgumentException e) {
1141            return -1;
1142        }
1143    }
1144
1145    private static float convertRationalLatLonToFloat(String rationalString, String ref) {
1146        try {
1147            String [] parts = rationalString.split(",");
1148
1149            String [] pair;
1150            pair = parts[0].split("/");
1151            double degrees = Double.parseDouble(pair[0].trim())
1152                    / Double.parseDouble(pair[1].trim());
1153
1154            pair = parts[1].split("/");
1155            double minutes = Double.parseDouble(pair[0].trim())
1156                    / Double.parseDouble(pair[1].trim());
1157
1158            pair = parts[2].split("/");
1159            double seconds = Double.parseDouble(pair[0].trim())
1160                    / Double.parseDouble(pair[1].trim());
1161
1162            double result = degrees + (minutes / 60.0) + (seconds / 3600.0);
1163            if ((ref.equals("S") || ref.equals("W"))) {
1164                return (float) -result;
1165            }
1166            return (float) result;
1167        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
1168            // Not valid
1169            throw new IllegalArgumentException();
1170        }
1171    }
1172
1173    // Loads EXIF attributes from a JPEG input stream.
1174    private void getJpegAttributes(InputStream inputStream) throws IOException {
1175        // See JPEG File Interchange Format Specification page 5.
1176        if (DEBUG) {
1177            Log.d(TAG, "getJpegAttributes starting with: " + inputStream);
1178        }
1179        DataInputStream dataInputStream = new DataInputStream(inputStream);
1180        byte marker;
1181        int bytesRead = 0;
1182        if ((marker = dataInputStream.readByte()) != MARKER) {
1183            throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff));
1184        }
1185        ++bytesRead;
1186        if (dataInputStream.readByte() != MARKER_SOI) {
1187            throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff));
1188        }
1189        ++bytesRead;
1190        while (true) {
1191            marker = dataInputStream.readByte();
1192            if (marker != MARKER) {
1193                throw new IOException("Invalid marker:" + Integer.toHexString(marker & 0xff));
1194            }
1195            ++bytesRead;
1196            marker = dataInputStream.readByte();
1197            if (DEBUG) {
1198                Log.d(TAG, "Found JPEG segment indicator: " + Integer.toHexString(marker & 0xff));
1199            }
1200            ++bytesRead;
1201
1202            // EOI indicates the end of an image and in case of SOS, JPEG image stream starts and
1203            // the image data will terminate right after.
1204            if (marker == MARKER_EOI || marker == MARKER_SOS) {
1205                break;
1206            }
1207            int length = dataInputStream.readUnsignedShort() - 2;
1208            bytesRead += 2;
1209            if (DEBUG) {
1210                Log.d(TAG, "JPEG segment: " + marker + " (length: " + (length + 2) + ")");
1211            }
1212            if (length < 0) {
1213                throw new IOException("Invalid length");
1214            }
1215            switch (marker) {
1216                case MARKER_APP1: {
1217                    if (DEBUG) {
1218                        Log.d(TAG, "MARKER_APP1");
1219                    }
1220                    if (length < 6) {
1221                        // Skip if it's not an EXIF APP1 segment.
1222                        break;
1223                    }
1224                    byte[] identifier = new byte[6];
1225                    if (inputStream.read(identifier) != 6) {
1226                        throw new IOException("Invalid exif");
1227                    }
1228                    bytesRead += 6;
1229                    length -= 6;
1230                    if (!Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) {
1231                        // Skip if it's not an EXIF APP1 segment.
1232                        break;
1233                    }
1234                    if (length <= 0) {
1235                        throw new IOException("Invalid exif");
1236                    }
1237                    if (DEBUG) {
1238                        Log.d(TAG, "readExifSegment with a byte array (length: " + length + ")");
1239                    }
1240                    byte[] bytes = new byte[length];
1241                    if (dataInputStream.read(bytes) != length) {
1242                        throw new IOException("Invalid exif");
1243                    }
1244                    readExifSegment(bytes, bytesRead);
1245                    bytesRead += length;
1246                    length = 0;
1247                    break;
1248                }
1249
1250                case MARKER_COM: {
1251                    byte[] bytes = new byte[length];
1252                    if (dataInputStream.read(bytes) != length) {
1253                        throw new IOException("Invalid exif");
1254                    }
1255                    length = 0;
1256                    setAttribute("UserComment", new String(bytes, Charset.forName("US-ASCII")));
1257                    break;
1258                }
1259
1260                case MARKER_SOF0:
1261                case MARKER_SOF1:
1262                case MARKER_SOF2:
1263                case MARKER_SOF3:
1264                case MARKER_SOF5:
1265                case MARKER_SOF6:
1266                case MARKER_SOF7:
1267                case MARKER_SOF9:
1268                case MARKER_SOF10:
1269                case MARKER_SOF11:
1270                case MARKER_SOF13:
1271                case MARKER_SOF14:
1272                case MARKER_SOF15: {
1273                    dataInputStream.skipBytes(1);
1274                    setAttribute("ImageLength",
1275                            String.valueOf(dataInputStream.readUnsignedShort()));
1276                    setAttribute("ImageWidth", String.valueOf(dataInputStream.readUnsignedShort()));
1277                    length -= 5;
1278                    break;
1279                }
1280
1281                default: {
1282                    break;
1283                }
1284            }
1285            if (length < 0) {
1286                throw new IOException("Invalid length");
1287            }
1288            dataInputStream.skipBytes(length);
1289            bytesRead += length;
1290        }
1291    }
1292
1293    // Stores a new JPEG image with EXIF attributes into a given output stream.
1294    private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream)
1295            throws IOException {
1296        // See JPEG File Interchange Format Specification page 5.
1297        if (DEBUG) {
1298            Log.d(TAG, "saveJpegAttributes starting with (inputStream: " + inputStream
1299                    + ", outputStream: " + outputStream + ")");
1300        }
1301        DataInputStream dataInputStream = new DataInputStream(inputStream);
1302        ExifDataOutputStream dataOutputStream = new ExifDataOutputStream(outputStream);
1303        if (dataInputStream.readByte() != MARKER) {
1304            throw new IOException("Invalid marker");
1305        }
1306        dataOutputStream.writeByte(MARKER);
1307        if (dataInputStream.readByte() != MARKER_SOI) {
1308            throw new IOException("Invalid marker");
1309        }
1310        dataOutputStream.writeByte(MARKER_SOI);
1311
1312        // Write EXIF APP1 segment
1313        dataOutputStream.writeByte(MARKER);
1314        dataOutputStream.writeByte(MARKER_APP1);
1315        writeExifSegment(dataOutputStream, 6);
1316
1317        byte[] bytes = new byte[4096];
1318
1319        while (true) {
1320            if (dataInputStream.readByte() != MARKER) {
1321                throw new IOException("Invalid marker");
1322            }
1323            byte marker = dataInputStream.readByte();
1324            switch (marker) {
1325                case MARKER_APP1: {
1326                    int length = dataInputStream.readUnsignedShort() - 2;
1327                    if (length < 0) {
1328                        throw new IOException("Invalid length");
1329                    }
1330                    byte[] identifier = new byte[6];
1331                    if (length >= 6) {
1332                        if (dataInputStream.read(identifier) != 6) {
1333                            throw new IOException("Invalid exif");
1334                        }
1335                        if (Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) {
1336                            // Skip the original EXIF APP1 segment.
1337                            if (dataInputStream.skip(length - 6) != length - 6) {
1338                                throw new IOException("Invalid length");
1339                            }
1340                            break;
1341                        }
1342                    }
1343                    // Copy non-EXIF APP1 segment.
1344                    dataOutputStream.writeUnsignedShort(length + 2);
1345                    if (length >= 6) {
1346                        length -= 6;
1347                        dataOutputStream.write(identifier);
1348                    }
1349                    int read;
1350                    while (length > 0 && (read = dataInputStream.read(
1351                            bytes, 0, Math.min(length, bytes.length))) >= 0) {
1352                        dataOutputStream.write(bytes, 0, read);
1353                        length -= read;
1354                    }
1355                    break;
1356                }
1357                case MARKER_EOI:
1358                case MARKER_SOS: {
1359                    dataOutputStream.writeByte(MARKER);
1360                    dataOutputStream.writeByte(marker);
1361                    // Copy all the remaining data
1362                    Streams.copy(dataInputStream, dataOutputStream);
1363                    return;
1364                }
1365                default: {
1366                    // Copy JPEG segment
1367                    dataOutputStream.writeByte(MARKER);
1368                    dataOutputStream.writeByte(marker);
1369                    int length = dataInputStream.readUnsignedShort();
1370                    dataOutputStream.writeUnsignedShort(length);
1371                    length -= 2;
1372                    if (length < 0) {
1373                        throw new IOException("Invalid length");
1374                    }
1375                    int read;
1376                    while (length > 0 && (read = dataInputStream.read(
1377                            bytes, 0, Math.min(length, bytes.length))) >= 0) {
1378                        dataOutputStream.write(bytes, 0, read);
1379                        length -= read;
1380                    }
1381                    break;
1382                }
1383            }
1384        }
1385    }
1386
1387    // Reads the given EXIF byte area and save its tag data into attributes.
1388    private void readExifSegment(byte[] exifBytes, int exifOffsetFromBeginning) throws IOException {
1389        // Parse TIFF Headers. See JEITA CP-3451C Table 1. page 10.
1390        ByteOrderAwarenessDataInputStream dataInputStream =
1391                new ByteOrderAwarenessDataInputStream(exifBytes);
1392
1393        // Read byte align
1394        short byteOrder = dataInputStream.readShort();
1395        switch (byteOrder) {
1396            case BYTE_ALIGN_II:
1397                if (DEBUG) {
1398                    Log.d(TAG, "readExifSegment: Byte Align II");
1399                }
1400                dataInputStream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
1401                break;
1402            case BYTE_ALIGN_MM:
1403                if (DEBUG) {
1404                    Log.d(TAG, "readExifSegment: Byte Align MM");
1405                }
1406                dataInputStream.setByteOrder(ByteOrder.BIG_ENDIAN);
1407                break;
1408            default:
1409                throw new IOException("Invalid byte order: " + Integer.toHexString(byteOrder));
1410        }
1411
1412        int startCode = dataInputStream.readUnsignedShort();
1413        if (startCode != 0x2a) {
1414            throw new IOException("Invalid exif start: " + Integer.toHexString(startCode));
1415        }
1416
1417        // Read first ifd offset
1418        long firstIfdOffset = dataInputStream.readUnsignedInt();
1419        if (firstIfdOffset < 8 || firstIfdOffset >= exifBytes.length) {
1420            throw new IOException("Invalid first Ifd offset: " + firstIfdOffset);
1421        }
1422        firstIfdOffset -= 8;
1423        if (firstIfdOffset > 0) {
1424            if (dataInputStream.skip(firstIfdOffset) != firstIfdOffset) {
1425                throw new IOException("Couldn't jump to first Ifd: " + firstIfdOffset);
1426            }
1427        }
1428
1429        // Read primary image TIFF image file directory.
1430        readImageFileDirectory(dataInputStream, IFD_TIFF_HINT);
1431
1432        // Process thumbnail.
1433        String jpegInterchangeFormatString = getAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name);
1434        String jpegInterchangeFormatLengthString =
1435                getAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name);
1436        if (jpegInterchangeFormatString != null && jpegInterchangeFormatLengthString != null) {
1437            try {
1438                int jpegInterchangeFormat = Integer.parseInt(jpegInterchangeFormatString);
1439                int jpegInterchangeFormatLength = Integer
1440                        .parseInt(jpegInterchangeFormatLengthString);
1441                // The following code limits the size of thumbnail size not to overflow EXIF data area.
1442                jpegInterchangeFormatLength = Math.min(jpegInterchangeFormat
1443                        + jpegInterchangeFormatLength, exifOffsetFromBeginning + exifBytes.length)
1444                        - jpegInterchangeFormat;
1445                if (jpegInterchangeFormat > 0 && jpegInterchangeFormatLength > 0) {
1446                    mHasThumbnail = true;
1447                    mThumbnailOffset = exifOffsetFromBeginning + jpegInterchangeFormat;
1448                    mThumbnailLength = jpegInterchangeFormatLength;
1449
1450                    if (mFilename == null && mAssetInputStream == null
1451                            && mSeekableFileDescriptor == null) {
1452                        // Save the thumbnail in memory if the input doesn't support reading again.
1453                        byte[] thumbnailBytes = new byte[jpegInterchangeFormatLength];
1454                        dataInputStream.seek(jpegInterchangeFormat);
1455                        dataInputStream.readFully(thumbnailBytes);
1456                        mThumbnailBytes = thumbnailBytes;
1457
1458                        if (DEBUG) {
1459                            Bitmap bitmap = BitmapFactory.decodeByteArray(
1460                                    thumbnailBytes, 0, thumbnailBytes.length);
1461                            Log.d(TAG, "Thumbnail offset: " + mThumbnailOffset + ", length: "
1462                                    + mThumbnailLength + ", width: " + bitmap.getWidth()
1463                                    + ", height: "
1464                                    + bitmap.getHeight());
1465                        }
1466                    }
1467                }
1468            } catch (NumberFormatException e) {
1469                // Ignored the corrupted image.
1470            }
1471        }
1472
1473        // For compatibility, keep data formats as follows.
1474        convertToInt(TAG_IMAGE_WIDTH);
1475        convertToInt(TAG_IMAGE_LENGTH);
1476        convertToInt(TAG_ORIENTATION);
1477        convertToInt(TAG_FLASH);
1478        convertToRational(TAG_FOCAL_LENGTH);
1479        convertToDouble(TAG_DIGITAL_ZOOM_RATIO);
1480        convertToDouble(TAG_EXPOSURE_TIME);
1481        convertToDouble(TAG_F_NUMBER);
1482        convertToDouble(TAG_SUBJECT_DISTANCE);
1483        convertToInt(TAG_ISO);
1484        convertToDouble(TAG_EXPOSURE_BIAS_VALUE);
1485        convertToInt(TAG_WHITE_BALANCE);
1486        convertToInt(TAG_LIGHT_SOURCE);
1487        convertToInt(TAG_METERING_MODE);
1488        convertToInt(TAG_EXPOSURE_PROGRAM);
1489        convertToInt(TAG_EXPOSURE_MODE);
1490        convertToRational(TAG_GPS_ALTITUDE);
1491        convertToInt(TAG_GPS_ALTITUDE_REF);
1492        convertToRational(TAG_GPS_LONGITUDE);
1493        convertToRational(TAG_GPS_LATITUDE);
1494        convertToTimetamp(TAG_GPS_TIMESTAMP);
1495
1496        // The value of DATETIME tag has the same value of DATETIME_ORIGINAL tag.
1497        String valueOfDateTimeOriginal = getAttribute("DateTimeOriginal");
1498        if (valueOfDateTimeOriginal != null) {
1499            setAttribute(TAG_DATETIME, valueOfDateTimeOriginal);
1500        }
1501
1502        // Add the default value.
1503        if (getAttribute(TAG_IMAGE_WIDTH) == null) {
1504            setAttribute(TAG_IMAGE_WIDTH, "0");
1505        }
1506        if (getAttribute(TAG_IMAGE_LENGTH) == null) {
1507            setAttribute(TAG_IMAGE_LENGTH, "0");
1508        }
1509        if (getAttribute(TAG_ORIENTATION) == null) {
1510            setAttribute(TAG_ORIENTATION, "0");
1511        }
1512        if (getAttribute(TAG_LIGHT_SOURCE) == null) {
1513            setAttribute(TAG_LIGHT_SOURCE, "0");
1514        }
1515    }
1516
1517    // Converts the tag value to timestamp; Otherwise deletes the given tag.
1518    private void convertToTimetamp(String tagName) {
1519        String entryValue = getAttribute(tagName);
1520        if (entryValue == null) return;
1521        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1522        String[] components = entryValue.split(",");
1523        if (dataFormat == IFD_FORMAT_SRATIONAL && components.length == 3) {
1524            StringBuilder stringBuilder = new StringBuilder();
1525            for (String component : components) {
1526                if (stringBuilder.length() > 0) {
1527                    stringBuilder.append(":");
1528                }
1529                String[] rationalNumber = component.split("/");
1530                int numerator = Integer.parseInt(rationalNumber[0]);
1531                int denominator = Integer.parseInt(rationalNumber[1]);
1532                if (denominator == 0) {
1533                    numerator = 0;
1534                    denominator = 1;
1535                }
1536                int value = numerator / denominator;
1537                stringBuilder.append(String.format("%02d", value));
1538            }
1539            setAttribute(tagName, stringBuilder.toString());
1540        } else if (dataFormat != IFD_FORMAT_STRING) {
1541            setAttribute(tagName, null);
1542        }
1543    }
1544
1545    // Checks the tag value of a given tag formatted in double type; Otherwise try to convert it to
1546    // double type or delete it.
1547    private void convertToDouble(String tagName) {
1548        String entryValue = getAttribute(tagName);
1549        if (entryValue == null) return;
1550        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1551        switch (dataFormat) {
1552            case IFD_FORMAT_SRATIONAL: {
1553                StringBuilder stringBuilder = new StringBuilder();
1554                String[] components = entryValue.split(",");
1555                for (String component : components) {
1556                    if (stringBuilder.length() > 0) {
1557                        stringBuilder.append(",");
1558                    }
1559                    String[] rationalNumber = component.split("/");
1560                    int numerator = Integer.parseInt(rationalNumber[0]);
1561                    int denominator = Integer.parseInt(rationalNumber[1]);
1562                    if (denominator == 0) {
1563                        numerator = 0;
1564                        denominator = 1;
1565                    }
1566                    stringBuilder.append((double) numerator / denominator);
1567                }
1568                setAttribute(tagName, stringBuilder.toString());
1569                break;
1570            }
1571            case IFD_FORMAT_DOUBLE:
1572                // Keep it as is.
1573                break;
1574            default:
1575                setAttribute(tagName, null);
1576                break;
1577        }
1578    }
1579
1580    // Checks the tag value of a given tag formatted in int type; Otherwise deletes the tag value.
1581    private void convertToRational(String tagName) {
1582        String entryValue = getAttribute(tagName);
1583        if (entryValue == null) return;
1584        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1585        switch (dataFormat) {
1586            case IFD_FORMAT_SLONG:
1587            case IFD_FORMAT_DOUBLE: {
1588                StringBuilder stringBuilder = new StringBuilder();
1589                String[] components = entryValue.split(",");
1590                for (String component : components) {
1591                    if (stringBuilder.length() > 0) {
1592                        stringBuilder.append(",");
1593                    }
1594                    double doubleValue = Double.parseDouble(component);
1595                    stringBuilder.append((int) (doubleValue * 10000.0)).append("/").append(10000);
1596                }
1597                setAttribute(tagName, stringBuilder.toString());
1598                break;
1599            }
1600            case IFD_FORMAT_SRATIONAL:
1601                // Keep it as is.
1602                break;
1603            default:
1604                setAttribute(tagName, null);
1605                break;
1606        }
1607    }
1608
1609    // Checks the tag value of a given tag formatted in int type; Otherwise deletes the tag value.
1610    private void convertToInt(String tagName) {
1611        String entryValue = getAttribute(tagName);
1612        if (entryValue == null) return;
1613        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1614        if (dataFormat != IFD_FORMAT_SLONG) {
1615            setAttribute(tagName, null);
1616        }
1617    }
1618
1619    // Reads image file directory, which is a tag group in EXIF.
1620    private void readImageFileDirectory(ByteOrderAwarenessDataInputStream dataInputStream, int hint)
1621            throws IOException {
1622        if (dataInputStream.peek() + 2 > dataInputStream.mLength) {
1623            // Return if there is no data from the offset.
1624            return;
1625        }
1626        // See JEITA CP-3451 Figure 5. page 9.
1627        short numberOfDirectoryEntry = dataInputStream.readShort();
1628        if (dataInputStream.peek() + 12 * numberOfDirectoryEntry > dataInputStream.mLength) {
1629            // Return if the size of entries is too big.
1630            return;
1631        }
1632
1633        if (DEBUG) {
1634            Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry);
1635        }
1636
1637        for (short i = 0; i < numberOfDirectoryEntry; ++i) {
1638            int tagNumber = dataInputStream.readUnsignedShort();
1639            int dataFormat = dataInputStream.readUnsignedShort();
1640            int numberOfComponents = dataInputStream.readInt();
1641            long nextEntryOffset = dataInputStream.peek() + 4;  // next four bytes is for data
1642                                                                // offset or value.
1643            // Look up a corresponding tag from tag number
1644            String tagName = (String) sExifTagMapsForReading[hint].get(tagNumber);
1645
1646            if (DEBUG) {
1647                Log.d(TAG, String.format("hint: %d, tagNumber: %d, tagName: %s, dataFormat: %d," +
1648                        "numberOfComponents: %d", hint, tagNumber, tagName, dataFormat,
1649                        numberOfComponents));
1650            }
1651
1652            if (tagName == null || dataFormat <= 0 ||
1653                    dataFormat >= IFD_FORMAT_BYTES_PER_FORMAT.length) {
1654                // Skip if the parsed tag number is not defined or invalid data format.
1655                if (tagName == null) {
1656                    Log.w(TAG, "Skip the tag entry since tag number is not defined: " + tagNumber);
1657                } else {
1658                    Log.w(TAG, "Skip the tag entry since data format is invalid: " + dataFormat);
1659                }
1660                dataInputStream.seek(nextEntryOffset);
1661                continue;
1662            }
1663
1664            // Read a value from data field or seek to the value offset which is stored in data
1665            // field if the size of the entry value is bigger than 4.
1666            int byteCount = numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat];
1667            if (byteCount > 4) {
1668                long offset = dataInputStream.readUnsignedInt();
1669                if (DEBUG) {
1670                    Log.d(TAG, "seek to data offset: " + offset);
1671                }
1672                if (offset + byteCount <= dataInputStream.mLength) {
1673                    dataInputStream.seek(offset);
1674                } else {
1675                     // Skip if invalid data offset.
1676                    Log.w(TAG, "Skip the tag entry since data offset is invalid: " + offset);
1677                    dataInputStream.seek(nextEntryOffset);
1678                    continue;
1679                }
1680            }
1681
1682            // Recursively parse IFD when a IFD pointer tag appears.
1683            int innerIfdHint = getIfdHintFromTagNumber(tagNumber);
1684            if (DEBUG) {
1685                Log.d(TAG, "innerIfdHint: " + innerIfdHint + " byteCount: " + byteCount);
1686            }
1687            if (innerIfdHint >= 0) {
1688                long offset = -1L;
1689                // Get offset from data field
1690                switch (dataFormat) {
1691                    case IFD_FORMAT_USHORT: {
1692                        offset = dataInputStream.readUnsignedShort();
1693                        break;
1694                    }
1695                    case IFD_FORMAT_SSHORT: {
1696                        offset = dataInputStream.readShort();
1697                        break;
1698                    }
1699                    case IFD_FORMAT_ULONG: {
1700                        offset = dataInputStream.readUnsignedInt();
1701                        break;
1702                    }
1703                    case IFD_FORMAT_SLONG: {
1704                        offset = dataInputStream.readInt();
1705                        break;
1706                    }
1707                    default: {
1708                        // Nothing to do
1709                        break;
1710                    }
1711                }
1712                if (DEBUG) {
1713                    Log.d(TAG, String.format("Offset: %d, tagName: %s", offset, tagName));
1714                }
1715                if (offset > 0L && offset < dataInputStream.mLength) {
1716                    dataInputStream.seek(offset);
1717                    readImageFileDirectory(dataInputStream, innerIfdHint);
1718                } else {
1719                    Log.w(TAG, "Skip jump into the IFD since its offset is invalid: " + offset);
1720                }
1721
1722                dataInputStream.seek(nextEntryOffset);
1723                continue;
1724            }
1725
1726            if (numberOfComponents == 1 || dataFormat == IFD_FORMAT_STRING
1727                    || dataFormat == IFD_FORMAT_UNDEFINED) {
1728                String entryValue = readExifEntryValue(
1729                        dataInputStream, dataFormat, numberOfComponents);
1730                if (entryValue != null) {
1731                    setAttribute(tagName, entryValue);
1732                }
1733            } else {
1734                StringBuilder entryValueBuilder = new StringBuilder();
1735                for (int c = 0; c < numberOfComponents; ++c) {
1736                    if (entryValueBuilder.length() > 0) {
1737                        entryValueBuilder.append(",");
1738                    }
1739                    entryValueBuilder.append(readExifEntryValue(
1740                            dataInputStream, dataFormat, numberOfComponents));
1741                }
1742                setAttribute(tagName, entryValueBuilder.toString());
1743            }
1744
1745            if (dataInputStream.peek() != nextEntryOffset) {
1746                dataInputStream.seek(nextEntryOffset);
1747            }
1748        }
1749
1750        if (dataInputStream.peek() + 4 <= dataInputStream.mLength) {
1751            long nextIfdOffset = dataInputStream.readUnsignedInt();
1752            if (DEBUG) {
1753                Log.d(TAG, String.format("nextIfdOffset: %d", nextIfdOffset));
1754            }
1755            // The next IFD offset needs to be bigger than 8
1756            // since the first IFD offset is at least 8.
1757            if (nextIfdOffset > 8 && nextIfdOffset < dataInputStream.mLength) {
1758                dataInputStream.seek(nextIfdOffset);
1759                readImageFileDirectory(dataInputStream, IFD_THUMBNAIL_HINT);
1760            }
1761        }
1762    }
1763
1764    // Reads a value from where the entry value are stored.
1765    private String readExifEntryValue(ByteOrderAwarenessDataInputStream dataInputStream,
1766            int dataFormat, int numberOfComponents) throws IOException {
1767        // See TIFF 6.0 spec Types. page 15.
1768        switch (dataFormat) {
1769            case IFD_FORMAT_BYTE: {
1770                return String.valueOf(dataInputStream.readByte());
1771            }
1772            case IFD_FORMAT_SBYTE: {
1773                return String.valueOf(dataInputStream.readByte() & 0xff);
1774            }
1775            case IFD_FORMAT_USHORT: {
1776                return String.valueOf(dataInputStream.readUnsignedShort());
1777            }
1778            case IFD_FORMAT_SSHORT: {
1779                return String.valueOf(dataInputStream.readUnsignedInt());
1780            }
1781            case IFD_FORMAT_ULONG: {
1782                return String.valueOf(dataInputStream.readInt());
1783            }
1784            case IFD_FORMAT_SLONG: {
1785                return String.valueOf(dataInputStream.readInt());
1786            }
1787            case IFD_FORMAT_URATIONAL:
1788            case IFD_FORMAT_SRATIONAL: {
1789                int numerator = dataInputStream.readInt();
1790                int denominator = dataInputStream.readInt();
1791                return numerator + "/" + denominator;
1792            }
1793            case IFD_FORMAT_SINGLE: {
1794                return String.valueOf(dataInputStream.readFloat());
1795            }
1796            case IFD_FORMAT_DOUBLE: {
1797                return String.valueOf(dataInputStream.readDouble());
1798            }
1799            case IFD_FORMAT_UNDEFINED:  // Usually UNDEFINED format is ASCII.
1800            case IFD_FORMAT_STRING: {
1801                byte[] bytes = new byte[numberOfComponents];
1802                dataInputStream.readFully(bytes);
1803                int index = 0;
1804                if (numberOfComponents >= EXIF_ASCII_PREFIX.length) {
1805                    boolean same = true;
1806                    for (int i = 0; i < EXIF_ASCII_PREFIX.length; ++i) {
1807                        if (bytes[i] != EXIF_ASCII_PREFIX[i]) {
1808                            same = false;
1809                            break;
1810                        }
1811                    }
1812                    if (same) {
1813                        index = EXIF_ASCII_PREFIX.length;
1814                    }
1815                }
1816
1817                StringBuilder stringBuilder = new StringBuilder();
1818                while (index < numberOfComponents) {
1819                    int ch = bytes[index];
1820                    if (ch == 0) {
1821                        break;
1822                    }
1823                    if (ch >= 32) {
1824                        stringBuilder.append((char) ch);
1825                    }
1826                    else {
1827                        stringBuilder.append('?');
1828                    }
1829                    ++index;
1830                }
1831                return stringBuilder.toString();
1832            }
1833            default: {
1834                // Nothing to do
1835                return null;
1836            }
1837        }
1838    }
1839
1840    // Gets the corresponding IFD group index of the given tag number for writing Exif Tags.
1841    private static int getIfdHintFromTagNumber(int tagNumber) {
1842        for (int i = 0; i < IFD_POINTER_TAG_HINTS.length; ++i) {
1843            if (IFD_POINTER_TAGS[i].number == tagNumber) {
1844                return IFD_POINTER_TAG_HINTS[i];
1845            }
1846        }
1847        return -1;
1848    }
1849
1850    // Writes an Exif segment into the given output stream.
1851    private int writeExifSegment(ExifDataOutputStream dataOutputStream, int exifOffsetFromBeginning)
1852            throws IOException {
1853        // The following variables are for calculating each IFD tag group size in bytes.
1854        int[] ifdOffsets = new int[EXIF_TAGS.length];
1855        int[] ifdDataSizes = new int[EXIF_TAGS.length];
1856
1857        // Remove IFD pointer tags (we'll re-add it later.)
1858        for (ExifTag tag : IFD_POINTER_TAGS) {
1859            setAttribute(tag.name, null);
1860        }
1861
1862        // Add IFD pointer tags. The next offset of primary image TIFF IFD will have thumbnail IFD
1863        // offset when there is one or more tags in the thumbnail IFD.
1864        if (!mAttributes[IFD_INTEROPERABILITY_HINT].isEmpty()) {
1865            mAttributes[IFD_EXIF_HINT].put(IFD_POINTER_TAGS[2].name, "0");
1866        }
1867        if (!mAttributes[IFD_EXIF_HINT].isEmpty()) {
1868            mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[0].name, "0");
1869        }
1870        if (!mAttributes[IFD_GPS_HINT].isEmpty()) {
1871            mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[1].name, "0");
1872        }
1873        // Remove old thumbnail data
1874        setAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name, null);
1875        setAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, null);
1876        if (mHasThumbnail) {
1877            mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_TAG.name, "0");
1878            mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name,
1879                    String.valueOf(mThumbnailLength));
1880        }
1881
1882        // Remove null value tags.
1883        for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
1884            for (Object obj : mAttributes[hint].entrySet().toArray()) {
1885                Map.Entry entry = (Map.Entry) obj;
1886                if (entry.getValue() == null) {
1887                    mAttributes[hint].remove(entry.getKey());
1888                }
1889            }
1890        }
1891
1892        // Calculate IFD group data area sizes. IFD group data area is assigned to save the entry
1893        // value which has a bigger size than 4 bytes.
1894        for (int i = 0; i < 5; ++i) {
1895            int sum = 0;
1896            for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) {
1897                String entryValue = (String) ((Map.Entry) entry).getValue();
1898                int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1899                int size = getSizeOfExifEntryValue(dataFormat, entryValue);
1900                if (size > 4) {
1901                    sum += size;
1902                }
1903            }
1904            ifdDataSizes[i] += sum;
1905        }
1906
1907        // Calculate IFD offsets.
1908        int position = 8;
1909        for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
1910            if (!mAttributes[hint].isEmpty()) {
1911                ifdOffsets[hint] = position;
1912                position += 2 + mAttributes[hint].size() * 12 + 4 + ifdDataSizes[hint];
1913            }
1914        }
1915        if (mHasThumbnail) {
1916            int thumbnailOffset = position;
1917            mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_TAG.name,
1918                    String.valueOf(thumbnailOffset));
1919            mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name,
1920                    String.valueOf(mThumbnailLength));
1921            mThumbnailOffset = exifOffsetFromBeginning + thumbnailOffset;
1922            position += mThumbnailLength;
1923        }
1924
1925        // Calculate the total size
1926        int totalSize = position + 8;  // eight bytes is for header part.
1927        if (DEBUG) {
1928            Log.d(TAG, "totalSize length: " + totalSize);
1929            for (int i = 0; i < 5; ++i) {
1930                Log.d(TAG, String.format("index: %d, offsets: %d, tag count: %d, data sizes: %d",
1931                        i, ifdOffsets[i], mAttributes[i].size(), ifdDataSizes[i]));
1932            }
1933        }
1934
1935        // Update IFD pointer tags with the calculated offsets.
1936        if (!mAttributes[IFD_EXIF_HINT].isEmpty()) {
1937            mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[0].name,
1938                    String.valueOf(ifdOffsets[IFD_EXIF_HINT]));
1939        }
1940        if (!mAttributes[IFD_GPS_HINT].isEmpty()) {
1941            mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[1].name,
1942                    String.valueOf(ifdOffsets[IFD_GPS_HINT]));
1943        }
1944        if (!mAttributes[IFD_INTEROPERABILITY_HINT].isEmpty()) {
1945            mAttributes[IFD_EXIF_HINT].put(IFD_POINTER_TAGS[2].name,
1946                    String.valueOf(ifdOffsets[IFD_INTEROPERABILITY_HINT]));
1947        }
1948
1949        // Write TIFF Headers. See JEITA CP-3451C Table 1. page 10.
1950        dataOutputStream.writeUnsignedShort(totalSize);
1951        dataOutputStream.write(IDENTIFIER_EXIF_APP1);
1952        dataOutputStream.writeShort(BYTE_ALIGN_MM);
1953        dataOutputStream.writeUnsignedShort(0x2a);
1954        dataOutputStream.writeUnsignedInt(8);
1955
1956        // Write IFD groups. See JEITA CP-3451C Figure 7. page 12.
1957        for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
1958            if (!mAttributes[hint].isEmpty()) {
1959                // See JEITA CP-3451C 4.6.2 IFD structure. page 13.
1960                // Write entry count
1961                dataOutputStream.writeUnsignedShort(mAttributes[hint].size());
1962
1963                // Write entry info
1964                int dataOffset = ifdOffsets[hint] + 2 + mAttributes[hint].size() * 12 + 4;
1965                for (Map.Entry entry : (Set<Map.Entry>) mAttributes[hint].entrySet()) {
1966                    // Convert tag name to tag number.
1967                    int tagNumber = (int) sExifTagMapsForWriting[hint].get(entry.getKey());
1968                    String entryValue = (String) entry.getValue();
1969
1970                    int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1971                    int numberOfComponents = getNumberOfComponentsInExifEntryValue(dataFormat,
1972                            entryValue);
1973                    int byteCount = getSizeOfExifEntryValue(dataFormat, entryValue);
1974
1975                    dataOutputStream.writeUnsignedShort(tagNumber);
1976                    dataOutputStream.writeUnsignedShort(dataFormat);
1977                    dataOutputStream.writeInt(numberOfComponents);
1978                    if (byteCount > 4) {
1979                        dataOutputStream.writeUnsignedInt(dataOffset);
1980                        dataOffset += byteCount;
1981                    } else {
1982                        int bytesWritten = writeExifEntryValue(dataOutputStream, entryValue);
1983                        // Fill zero up to 4 bytes
1984                        if (bytesWritten < 4) {
1985                            for (int i = bytesWritten; i < 4; ++i) {
1986                                dataOutputStream.write(0);
1987                            }
1988                        }
1989                    }
1990                }
1991
1992                // Write the next offset. It writes the offset of thumbnail IFD if there is one or
1993                // more tags in the thumbnail IFD when the current IFD is the primary image TIFF
1994                // IFD; Otherwise 0.
1995                if (hint == 0 && !mAttributes[IFD_THUMBNAIL_HINT].isEmpty()) {
1996                    dataOutputStream.writeUnsignedInt(ifdOffsets[IFD_THUMBNAIL_HINT]);
1997                } else {
1998                    dataOutputStream.writeUnsignedInt(0);
1999                }
2000
2001                // Write values of data field exceeding 4 bytes after the next offset.
2002                for (Map.Entry entry : (Set<Map.Entry>) mAttributes[hint].entrySet()) {
2003                    String entryValue = (String) entry.getValue();
2004
2005                    int dataFormat = getDataFormatOfExifEntryValue(entryValue);
2006                    int byteCount = getSizeOfExifEntryValue(dataFormat, entryValue);
2007                    if (byteCount > 4) {
2008                        writeExifEntryValue(dataOutputStream, entryValue);
2009                    }
2010                }
2011            }
2012        }
2013
2014        // Write thumbnail
2015        if (mHasThumbnail) {
2016            dataOutputStream.write(getThumbnail());
2017        }
2018
2019        return totalSize;
2020    }
2021
2022    // Writes EXIF entry value and its entry value type will be automatically determined.
2023    private static int writeExifEntryValue(ExifDataOutputStream dataOutputStream, String entryValue)
2024            throws IOException {
2025        int bytesWritten = 0;
2026        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
2027
2028        if (dataFormat == IFD_FORMAT_STRING) {
2029            byte[] asciiArray = (entryValue + '\0').getBytes(Charset.forName("US-ASCII"));
2030            dataOutputStream.write(asciiArray);
2031            return asciiArray.length;
2032        }
2033
2034        // Values can be composed of several components. Each component is separated by char ','.
2035        String[] components = entryValue.split(",");
2036        for (String component : components) {
2037            switch (dataFormat) {
2038                case IFD_FORMAT_SLONG:
2039                    dataOutputStream.writeInt(Integer.parseInt(component));
2040                    bytesWritten += 4;
2041                    break;
2042                case IFD_FORMAT_DOUBLE:
2043                    dataOutputStream.writeDouble(Double.parseDouble(component));
2044                    bytesWritten += 8;
2045                    break;
2046                case IFD_FORMAT_SRATIONAL:
2047                    String[] rationalNumber = component.split("/");
2048                    dataOutputStream.writeInt(Integer.parseInt(rationalNumber[0]));
2049                    dataOutputStream.writeInt(Integer.parseInt(rationalNumber[1]));
2050                    bytesWritten += 8;
2051                    break;
2052                default:
2053                    throw new IllegalArgumentException();
2054            }
2055        }
2056        return bytesWritten;
2057    }
2058
2059    // Determines the data format of EXIF entry value.
2060    private static int getDataFormatOfExifEntryValue(String entryValue) {
2061        // See TIFF 6.0 spec Types. page 15.
2062        // Take the first component if there are more than one component.
2063        if (entryValue.contains(",")) {
2064            String[] entryValues = entryValue.split(",");
2065            int dataFormat = getDataFormatOfExifEntryValue(entryValues[0]);
2066            if (dataFormat == IFD_FORMAT_STRING) {
2067                return IFD_FORMAT_STRING;
2068            }
2069            for (int i = 1; i < entryValues.length; ++i) {
2070                if (getDataFormatOfExifEntryValue(entryValues[i]) != dataFormat) {
2071                    return IFD_FORMAT_STRING;
2072                }
2073            }
2074            return dataFormat;
2075        }
2076
2077        if (entryValue.contains("/")) {
2078            String[] rationalNumber = entryValue.split("/");
2079            if (rationalNumber.length == 2) {
2080                try {
2081                    Integer.parseInt(rationalNumber[0]);
2082                    Integer.parseInt(rationalNumber[1]);
2083                    return IFD_FORMAT_SRATIONAL;
2084                } catch (NumberFormatException e)  {
2085                    // Ignored
2086                }
2087            }
2088            return IFD_FORMAT_STRING;
2089        }
2090        try {
2091            Integer.parseInt(entryValue);
2092            return IFD_FORMAT_SLONG;
2093        } catch (NumberFormatException e) {
2094            // Ignored
2095        }
2096        try {
2097            Double.parseDouble(entryValue);
2098            return IFD_FORMAT_DOUBLE;
2099        } catch (NumberFormatException e) {
2100            // Ignored
2101        }
2102        return IFD_FORMAT_STRING;
2103    }
2104
2105    // Determines the size of EXIF entry value.
2106    private static int getSizeOfExifEntryValue(int dataFormat, String entryValue) {
2107        // See TIFF 6.0 spec Types page 15.
2108        if (dataFormat == IFD_FORMAT_STRING) {
2109            return (entryValue + '\0').getBytes(Charset.forName("US-ASCII")).length;
2110        }
2111        int bytesEstimated = 0;
2112        String[] components = entryValue.split(",");
2113        for (String component : components) {
2114            switch (dataFormat) {
2115                case IFD_FORMAT_SLONG:
2116                    bytesEstimated += 4;
2117                    break;
2118                case IFD_FORMAT_DOUBLE:
2119                    bytesEstimated += 8;
2120                    break;
2121                case IFD_FORMAT_SRATIONAL:
2122                    bytesEstimated += 8;
2123                    break;
2124                default:
2125                    throw new IllegalArgumentException();
2126            }
2127        }
2128        return bytesEstimated;
2129    }
2130
2131    // Determines the number of components of EXIF entry value.
2132    private static int getNumberOfComponentsInExifEntryValue(int dataFormat, String entryValue) {
2133        if (dataFormat == IFD_FORMAT_STRING) {
2134            return (entryValue + '\0').getBytes(Charset.forName("US-ASCII")).length;
2135        }
2136        int count = 1;
2137        for (int i = 0; i < entryValue.length(); ++i) {
2138            if (entryValue.charAt(i) == ',') {
2139                ++count;
2140            }
2141        }
2142        return count;
2143    }
2144
2145    // An input stream to parse EXIF data area, which can be written in either little or big endian
2146    // order.
2147    private static class ByteOrderAwarenessDataInputStream extends ByteArrayInputStream {
2148        private static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN;
2149        private static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN;
2150
2151        private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN;
2152        private final long mLength;
2153        private long mPosition;
2154
2155        public ByteOrderAwarenessDataInputStream(byte[] bytes) {
2156            super(bytes);
2157            mLength = bytes.length;
2158            mPosition = 0L;
2159        }
2160
2161        public void setByteOrder(ByteOrder byteOrder) {
2162            mByteOrder = byteOrder;
2163        }
2164
2165        public void seek(long byteCount) throws IOException {
2166            mPosition = 0L;
2167            reset();
2168            if (skip(byteCount) != byteCount) {
2169                throw new IOException("Couldn't seek up to the byteCount");
2170            }
2171        }
2172
2173        public long peek() {
2174            return mPosition;
2175        }
2176
2177        public void readFully(byte[] buffer) throws IOException {
2178            mPosition += buffer.length;
2179            if (mPosition > mLength) {
2180                throw new EOFException();
2181            }
2182            if (super.read(buffer, 0, buffer.length) != buffer.length) {
2183                throw new IOException("Couldn't read up to the length of buffer");
2184            }
2185        }
2186
2187        public byte readByte() throws IOException {
2188            ++mPosition;
2189            if (mPosition > mLength) {
2190                throw new EOFException();
2191            }
2192            int ch = super.read();
2193            if (ch < 0) {
2194                throw new EOFException();
2195            }
2196            return (byte) ch;
2197        }
2198
2199        public short readShort() throws IOException {
2200            mPosition += 2;
2201            if (mPosition > mLength) {
2202                throw new EOFException();
2203            }
2204            int ch1 = super.read();
2205            int ch2 = super.read();
2206            if ((ch1 | ch2) < 0) {
2207                throw new EOFException();
2208            }
2209            if (mByteOrder == LITTLE_ENDIAN) {
2210                return (short) ((ch2 << 8) + (ch1));
2211            } else if (mByteOrder == BIG_ENDIAN) {
2212                return (short) ((ch1 << 8) + (ch2));
2213            }
2214            throw new IOException("Invalid byte order: " + mByteOrder);
2215        }
2216
2217        public int readInt() throws IOException {
2218            mPosition += 4;
2219            if (mPosition > mLength) {
2220                throw new EOFException();
2221            }
2222            int ch1 = super.read();
2223            int ch2 = super.read();
2224            int ch3 = super.read();
2225            int ch4 = super.read();
2226            if ((ch1 | ch2 | ch3 | ch4) < 0) {
2227                throw new EOFException();
2228            }
2229            if (mByteOrder == LITTLE_ENDIAN) {
2230                return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1);
2231            } else if (mByteOrder == BIG_ENDIAN) {
2232                return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4);
2233            }
2234            throw new IOException("Invalid byte order: " + mByteOrder);
2235        }
2236
2237        @Override
2238        public long skip(long byteCount) {
2239            long skipped = super.skip(Math.min(byteCount, mLength - mPosition));
2240            mPosition += skipped;
2241            return skipped;
2242        }
2243
2244        public int readUnsignedShort() throws IOException {
2245            mPosition += 2;
2246            if (mPosition > mLength) {
2247                throw new EOFException();
2248            }
2249            int ch1 = super.read();
2250            int ch2 = super.read();
2251            if ((ch1 | ch2) < 0) {
2252                throw new EOFException();
2253            }
2254            if (mByteOrder == LITTLE_ENDIAN) {
2255                return ((ch2 << 8) + (ch1));
2256            } else if (mByteOrder == BIG_ENDIAN) {
2257                return ((ch1 << 8) + (ch2));
2258            }
2259            throw new IOException("Invalid byte order: " + mByteOrder);
2260        }
2261
2262        public long readUnsignedInt() throws IOException {
2263            return readInt() & 0xffffffffL;
2264        }
2265
2266        public long readLong() throws IOException {
2267            mPosition += 8;
2268            if (mPosition > mLength) {
2269                throw new EOFException();
2270            }
2271            int ch1 = super.read();
2272            int ch2 = super.read();
2273            int ch3 = super.read();
2274            int ch4 = super.read();
2275            int ch5 = super.read();
2276            int ch6 = super.read();
2277            int ch7 = super.read();
2278            int ch8 = super.read();
2279            if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) {
2280                throw new EOFException();
2281            }
2282            if (mByteOrder == LITTLE_ENDIAN) {
2283                return (((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40)
2284                        + ((long) ch5 << 32) + ((long) ch4 << 24) + ((long) ch3 << 16)
2285                        + ((long) ch2 << 8) + (long) ch1);
2286            } else if (mByteOrder == BIG_ENDIAN) {
2287                return (((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40)
2288                        + ((long) ch4 << 32) + ((long) ch5 << 24) + ((long) ch6 << 16)
2289                        + ((long) ch7 << 8) + (long) ch8);
2290            }
2291            throw new IOException("Invalid byte order: " + mByteOrder);
2292        }
2293
2294        public float readFloat() throws IOException {
2295            return Float.intBitsToFloat(readInt());
2296        }
2297
2298        public double readDouble() throws IOException {
2299            return Double.longBitsToDouble(readLong());
2300        }
2301    }
2302
2303    // An output stream to write EXIF data area, that will be written in big endian byte order.
2304    private static class ExifDataOutputStream extends DataOutputStream {
2305        public ExifDataOutputStream(OutputStream out) {
2306            super(out);
2307        }
2308
2309        public void writeUnsignedShort(int val) throws IOException {
2310            writeShort((short) val);
2311        }
2312
2313        public void writeUnsignedInt(long val) throws IOException {
2314            writeInt((int) val);
2315        }
2316    }
2317
2318    // JNI methods for RAW formats.
2319    private static native void nativeInitRaw();
2320    private static native byte[] nativeGetThumbnailFromAsset(
2321            long asset, int thumbnailOffset, int thumbnailLength);
2322    private static native HashMap nativeGetRawAttributesFromAsset(long asset);
2323    private static native HashMap nativeGetRawAttributesFromFileDescriptor(FileDescriptor fd);
2324    private static native HashMap nativeGetRawAttributesFromInputStream(InputStream in);
2325}
2326