ExifInterface.java revision 89cb1945424f1d4c7278d24cd09f0a8d09093883
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 APP1 segment in JPEG
609    private static final byte[] IDENTIFIER_APP1 = "Exif\0\0".getBytes(Charset.forName("US-ASCII"));
610    // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with
611    // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start
612    // of frame(baseline DCT) and the image size info exists in its beginning part.
613    private static final byte MARKER = (byte) 0xff;
614    private static final byte MARKER_SOI = (byte) 0xd8;
615    private static final byte MARKER_SOF0 = (byte) 0xc0;
616    private static final byte MARKER_SOF1 = (byte) 0xc1;
617    private static final byte MARKER_SOF2 = (byte) 0xc2;
618    private static final byte MARKER_SOF3 = (byte) 0xc3;
619    private static final byte MARKER_SOF5 = (byte) 0xc5;
620    private static final byte MARKER_SOF6 = (byte) 0xc6;
621    private static final byte MARKER_SOF7 = (byte) 0xc7;
622    private static final byte MARKER_SOF9 = (byte) 0xc9;
623    private static final byte MARKER_SOF10 = (byte) 0xca;
624    private static final byte MARKER_SOF11 = (byte) 0xcb;
625    private static final byte MARKER_SOF13 = (byte) 0xcd;
626    private static final byte MARKER_SOF14 = (byte) 0xce;
627    private static final byte MARKER_SOF15 = (byte) 0xcf;
628    private static final byte MARKER_SOS = (byte) 0xda;
629    private static final byte MARKER_APP1 = (byte) 0xe1;
630    private static final byte MARKER_COM = (byte) 0xfe;
631    private static final byte MARKER_EOI = (byte) 0xd9;
632
633    static {
634        System.loadLibrary("media_jni");
635        nativeInitRaw();
636        sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
637        sFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
638
639        // Build up the hash tables to look up Exif tags for reading Exif tags.
640        for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
641            sExifTagMapsForReading[hint] = new HashMap();
642            sExifTagMapsForWriting[hint] = new HashMap();
643            for (ExifTag tag : EXIF_TAGS[hint]) {
644                sExifTagMapsForReading[hint].put(tag.number, tag.name);
645                sExifTagMapsForWriting[hint].put(tag.name, tag.number);
646            }
647        }
648    }
649
650    private final String mFilename;
651    private final FileDescriptor mSeekableFileDescriptor;
652    private final AssetManager.AssetInputStream mAssetInputStream;
653    private boolean mIsRaw;
654    private final HashMap[] mAttributes = new HashMap[EXIF_TAGS.length];
655    private boolean mHasThumbnail;
656    // The following values used for indicating a thumbnail position.
657    private int mThumbnailOffset;
658    private int mThumbnailLength;
659    private byte[] mThumbnailBytes;
660
661    // Pattern to check non zero timestamp
662    private static final Pattern sNonZeroTimePattern = Pattern.compile(".*[1-9].*");
663
664    /**
665     * Reads Exif tags from the specified image file.
666     */
667    public ExifInterface(String filename) throws IOException {
668        if (filename == null) {
669            throw new IllegalArgumentException("filename cannot be null");
670        }
671        FileInputStream in = new FileInputStream(filename);
672        mAssetInputStream = null;
673        mFilename = filename;
674        if (isSeekableFD(in.getFD())) {
675            mSeekableFileDescriptor = in.getFD();
676        } else {
677            mSeekableFileDescriptor = null;
678        }
679        loadAttributes(in);
680    }
681
682    /**
683     * Reads Exif tags from the specified image file descriptor. Attribute mutation is supported
684     * for seekable file descriptors only.
685     */
686    public ExifInterface(FileDescriptor fileDescriptor) throws IOException {
687        if (fileDescriptor == null) {
688            throw new IllegalArgumentException("parcelFileDescriptor cannot be null");
689        }
690        mAssetInputStream = null;
691        mFilename = null;
692        if (isSeekableFD(fileDescriptor)) {
693            mSeekableFileDescriptor = fileDescriptor;
694        } else {
695            mSeekableFileDescriptor = null;
696        }
697        loadAttributes(new FileInputStream(fileDescriptor));
698    }
699
700    /**
701     * Reads Exif tags from the specified image input stream. Attribute mutation is not supported
702     * for input streams.
703     */
704    public ExifInterface(InputStream inputStream) throws IOException {
705        if (inputStream == null) {
706            throw new IllegalArgumentException("inputStream cannot be null");
707        }
708        mFilename = null;
709        if (inputStream instanceof AssetManager.AssetInputStream) {
710            mAssetInputStream = (AssetManager.AssetInputStream) inputStream;
711            mSeekableFileDescriptor = null;
712        } else if (inputStream instanceof FileInputStream
713                && isSeekableFD(((FileInputStream) inputStream).getFD())) {
714            mAssetInputStream = null;
715            mSeekableFileDescriptor = ((FileInputStream) inputStream).getFD();
716        } else {
717            mAssetInputStream = null;
718            mSeekableFileDescriptor = null;
719        }
720        loadAttributes(inputStream);
721    }
722
723    /**
724     * Returns the value of the specified tag or {@code null} if there
725     * is no such tag in the image file.
726     *
727     * @param tag the name of the tag.
728     */
729    public String getAttribute(String tag) {
730        // Retrieves all tag groups. The value from primary image tag group has a higher priority
731        // than the value from the thumbnail tag group if there are more than one candidates.
732        for (int i = 0; i < EXIF_TAGS.length; ++i) {
733            Object value = mAttributes[i].get(tag);
734            if (value != null) {
735                return (String) value;
736            }
737        }
738        return null;
739    }
740
741    /**
742     * Returns the integer value of the specified tag. If there is no such tag
743     * in the image file or the value cannot be parsed as integer, return
744     * <var>defaultValue</var>.
745     *
746     * @param tag the name of the tag.
747     * @param defaultValue the value to return if the tag is not available.
748     */
749    public int getAttributeInt(String tag, int defaultValue) {
750        String value = getAttribute(tag);
751        if (value == null) return defaultValue;
752        try {
753            return Integer.valueOf(value);
754        } catch (NumberFormatException e) {
755            return defaultValue;
756        }
757    }
758
759    /**
760     * Returns the double value of the tag that is specified as rational or contains a
761     * double-formatted value. If there is no such tag in the image file or the value cannot be
762     * parsed as double, return <var>defaultValue</var>.
763     *
764     * @param tag the name of the tag.
765     * @param defaultValue the value to return if the tag is not available.
766     */
767    public double getAttributeDouble(String tag, double defaultValue) {
768        String value = getAttribute(tag);
769        if (value == null) return defaultValue;
770        try {
771            int index = value.indexOf("/");
772            if (index == -1) return Double.parseDouble(value);
773            double denom = Double.parseDouble(value.substring(index + 1));
774            if (denom == 0) return defaultValue;
775            double num = Double.parseDouble(value.substring(0, index));
776            return num / denom;
777        } catch (NumberFormatException e) {
778            return defaultValue;
779        }
780    }
781
782    /**
783     * Set the value of the specified tag.
784     *
785     * @param tag the name of the tag.
786     * @param value the value of the tag.
787     */
788    public void setAttribute(String tag, String value) {
789        for (int i = 0 ; i < EXIF_TAGS.length; ++i) {
790            if (sExifTagMapsForWriting[i].containsKey(tag)) {
791                mAttributes[i].put(tag, value);
792            }
793        }
794    }
795
796    /**
797     * This function decides which parser to read the image data according to the given input stream
798     * type and the content of the input stream. In each case, it reads the first three bytes to
799     * determine whether the image data format is JPEG or not.
800     */
801    private void loadAttributes(@NonNull InputStream in) throws IOException {
802        // Initialize mAttributes.
803        for (int i = 0; i < EXIF_TAGS.length; ++i) {
804            mAttributes[i] = new HashMap();
805        }
806
807        // Process RAW input stream
808        if (mAssetInputStream != null) {
809            long asset = mAssetInputStream.getNativeAsset();
810            if (handleRawResult(nativeGetRawAttributesFromAsset(asset))) {
811                return;
812            }
813        } else if (mSeekableFileDescriptor != null) {
814            if (handleRawResult(nativeGetRawAttributesFromFileDescriptor(
815                    mSeekableFileDescriptor))) {
816                return;
817            }
818        } else {
819            in = new BufferedInputStream(in, JPEG_SIGNATURE_SIZE);
820            if (!isJpegInputStream((BufferedInputStream) in) && handleRawResult(
821                    nativeGetRawAttributesFromInputStream(in))) {
822                return;
823            }
824        }
825
826        // Process JPEG input stream
827        getJpegAttributes(in);
828
829        if (DEBUG) {
830            printAttributes();
831        }
832    }
833
834    private static boolean isJpegInputStream(BufferedInputStream in) throws IOException {
835        in.mark(JPEG_SIGNATURE_SIZE);
836        byte[] signatureBytes = new byte[JPEG_SIGNATURE_SIZE];
837        if (in.read(signatureBytes) != JPEG_SIGNATURE_SIZE) {
838            throw new EOFException();
839        }
840        boolean isJpeg = Arrays.equals(JPEG_SIGNATURE, signatureBytes);
841        in.reset();
842        return isJpeg;
843    }
844
845    private boolean handleRawResult(HashMap map) {
846        if (map == null) {
847            return false;
848        }
849
850        // Mark for disabling the save feature.
851        mIsRaw = true;
852
853        for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
854            String attrName = (String) entry.getKey();
855
856            switch (attrName) {
857                case TAG_HAS_THUMBNAIL:
858                    mHasThumbnail = ((String) entry.getValue()).equalsIgnoreCase("true");
859                    break;
860                case TAG_THUMBNAIL_OFFSET:
861                    mThumbnailOffset = Integer.parseInt((String) entry.getValue());
862                    break;
863                case TAG_THUMBNAIL_LENGTH:
864                    mThumbnailLength = Integer.parseInt((String) entry.getValue());
865                    break;
866                case TAG_THUMBNAIL_DATA:
867                    mThumbnailBytes = (byte[]) entry.getValue();
868                    break;
869                default:
870                    setAttribute(attrName, (String) entry.getValue());
871                    break;
872            }
873        }
874
875        if (DEBUG) {
876            printAttributes();
877        }
878        return true;
879    }
880
881    private static boolean isSeekableFD(FileDescriptor fd) throws IOException {
882        try {
883            Os.lseek(fd, 0, OsConstants.SEEK_CUR);
884            return true;
885        } catch (ErrnoException e) {
886            return false;
887        }
888    }
889
890    // Prints out attributes for debugging.
891    private void printAttributes() {
892        for (int i = 0; i < mAttributes.length; ++i) {
893            Log.d(TAG, "The size of tag group[" + i + "]: " + mAttributes[i].size());
894            for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) {
895                Log.d(TAG, "tagName: " + entry.getKey() + ", tagValue: " + entry.getValue());
896            }
897        }
898    }
899
900    /**
901     * Save the tag data into the original image file. This is expensive because it involves
902     * copying all the data from one file to another and deleting the old file and renaming the
903     * other. It's best to use{@link #setAttribute(String,String)} to set all attributes to write
904     * and make a single call rather than multiple calls for each attribute.
905     */
906    public void saveAttributes() throws IOException {
907        if (mIsRaw) {
908            throw new UnsupportedOperationException(
909                    "ExifInterface does not support saving attributes on RAW formats.");
910        }
911        if (mSeekableFileDescriptor == null && mFilename == null) {
912            throw new UnsupportedOperationException(
913                    "ExifInterface does not support saving attributes for the current input.");
914        }
915
916        // Keep the thumbnail in memory
917        mThumbnailBytes = getThumbnail();
918
919        FileInputStream in = null;
920        FileOutputStream out = null;
921        File tempFile = null;
922        try {
923            // Move the original file to temporary file.
924            if (mFilename != null) {
925                tempFile = new File(mFilename + ".tmp");
926                File originalFile = new File(mFilename);
927                if (!originalFile.renameTo(tempFile)) {
928                    throw new IOException("Could'nt rename to " + tempFile.getAbsolutePath());
929                }
930            } else if (mSeekableFileDescriptor != null) {
931                tempFile = File.createTempFile("temp", "jpg");
932                Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET);
933                in = new FileInputStream(mSeekableFileDescriptor);
934                out = new FileOutputStream(tempFile);
935                Streams.copy(in, out);
936            }
937        } catch (ErrnoException e) {
938            e.rethrowAsIOException();
939        } finally {
940            IoUtils.closeQuietly(in);
941            IoUtils.closeQuietly(out);
942        }
943
944        in = null;
945        out = null;
946        try {
947            // Save the new file.
948            in = new FileInputStream(tempFile);
949            if (mFilename != null) {
950                out = new FileOutputStream(mFilename);
951            } else if (mSeekableFileDescriptor != null) {
952                Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET);
953                out = new FileOutputStream(mSeekableFileDescriptor);
954            }
955            saveJpegAttributes(in, out);
956        } catch (ErrnoException e) {
957            e.rethrowAsIOException();
958        } finally {
959            IoUtils.closeQuietly(in);
960            IoUtils.closeQuietly(out);
961            tempFile.delete();
962        }
963
964        // Discard the thumbnail in memory
965        mThumbnailBytes = null;
966    }
967
968    /**
969     * Returns true if the image file has a thumbnail.
970     */
971    public boolean hasThumbnail() {
972        return mHasThumbnail;
973    }
974
975    /**
976     * Returns the thumbnail inside the image file, or {@code null} if there is no thumbnail.
977     * The returned data is in JPEG format and can be decoded using
978     * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)}
979     */
980    public byte[] getThumbnail() {
981        if (!mHasThumbnail) {
982            return null;
983        }
984        if (mThumbnailBytes != null) {
985            return mThumbnailBytes;
986        }
987
988        // Read the thumbnail.
989        FileInputStream in = null;
990        try {
991            if (mAssetInputStream != null) {
992                return nativeGetThumbnailFromAsset(
993                        mAssetInputStream.getNativeAsset(), mThumbnailOffset, mThumbnailLength);
994            } else if (mFilename != null) {
995                in = new FileInputStream(mFilename);
996            } else if (mSeekableFileDescriptor != null) {
997                Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET);
998                in = new FileInputStream(mSeekableFileDescriptor);
999            }
1000            if (in == null) {
1001                // Should not be reached this.
1002                throw new FileNotFoundException();
1003            }
1004            if (in.skip(mThumbnailOffset) != mThumbnailOffset) {
1005                throw new IOException("Corrupted image");
1006            }
1007            byte[] buffer = new byte[mThumbnailLength];
1008            if (in.read(buffer) != mThumbnailLength) {
1009                throw new IOException("Corrupted image");
1010            }
1011            return buffer;
1012        } catch (IOException | ErrnoException e) {
1013            // Couldn't get a thumbnail image.
1014        } finally {
1015            IoUtils.closeQuietly(in);
1016        }
1017        return null;
1018    }
1019
1020    /**
1021     * Returns the offset and length of thumbnail inside the image file, or
1022     * {@code null} if there is no thumbnail.
1023     *
1024     * @return two-element array, the offset in the first value, and length in
1025     *         the second, or {@code null} if no thumbnail was found.
1026     * @hide
1027     */
1028    public long[] getThumbnailRange() {
1029        long[] range = new long[2];
1030        range[0] = mThumbnailOffset;
1031        range[1] = mThumbnailLength;
1032        return range;
1033    }
1034
1035    /**
1036     * Stores the latitude and longitude value in a float array. The first element is
1037     * the latitude, and the second element is the longitude. Returns false if the
1038     * Exif tags are not available.
1039     */
1040    public boolean getLatLong(float output[]) {
1041        String latValue = getAttribute(TAG_GPS_LATITUDE);
1042        String latRef = getAttribute(TAG_GPS_LATITUDE_REF);
1043        String lngValue = getAttribute(TAG_GPS_LONGITUDE);
1044        String lngRef = getAttribute(TAG_GPS_LONGITUDE_REF);
1045
1046        if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
1047            try {
1048                output[0] = convertRationalLatLonToFloat(latValue, latRef);
1049                output[1] = convertRationalLatLonToFloat(lngValue, lngRef);
1050                return true;
1051            } catch (IllegalArgumentException e) {
1052                // if values are not parseable
1053            }
1054        }
1055
1056        return false;
1057    }
1058
1059    /**
1060     * Return the altitude in meters. If the exif tag does not exist, return
1061     * <var>defaultValue</var>.
1062     *
1063     * @param defaultValue the value to return if the tag is not available.
1064     */
1065    public double getAltitude(double defaultValue) {
1066        double altitude = getAttributeDouble(TAG_GPS_ALTITUDE, -1);
1067        int ref = getAttributeInt(TAG_GPS_ALTITUDE_REF, -1);
1068
1069        if (altitude >= 0 && ref >= 0) {
1070            return (altitude * ((ref == 1) ? -1 : 1));
1071        } else {
1072            return defaultValue;
1073        }
1074    }
1075
1076    /**
1077     * Returns number of milliseconds since Jan. 1, 1970, midnight local time.
1078     * Returns -1 if the date time information if not available.
1079     * @hide
1080     */
1081    public long getDateTime() {
1082        String dateTimeString = getAttribute(TAG_DATETIME);
1083        if (dateTimeString == null
1084                || !sNonZeroTimePattern.matcher(dateTimeString).matches()) return -1;
1085
1086        ParsePosition pos = new ParsePosition(0);
1087        try {
1088            // The exif field is in local time. Parsing it as if it is UTC will yield time
1089            // since 1/1/1970 local time
1090            Date datetime = sFormatter.parse(dateTimeString, pos);
1091            if (datetime == null) return -1;
1092            long msecs = datetime.getTime();
1093
1094            String subSecs = getAttribute(TAG_SUBSECTIME);
1095            if (subSecs != null) {
1096                try {
1097                    long sub = Long.valueOf(subSecs);
1098                    while (sub > 1000) {
1099                        sub /= 10;
1100                    }
1101                    msecs += sub;
1102                } catch (NumberFormatException e) {
1103                    // Ignored
1104                }
1105            }
1106            return msecs;
1107        } catch (IllegalArgumentException e) {
1108            return -1;
1109        }
1110    }
1111
1112    /**
1113     * Returns number of milliseconds since Jan. 1, 1970, midnight UTC.
1114     * Returns -1 if the date time information if not available.
1115     * @hide
1116     */
1117    public long getGpsDateTime() {
1118        String date = getAttribute(TAG_GPS_DATESTAMP);
1119        String time = getAttribute(TAG_GPS_TIMESTAMP);
1120        if (date == null || time == null
1121                || (!sNonZeroTimePattern.matcher(date).matches()
1122                && !sNonZeroTimePattern.matcher(time).matches())) return -1;
1123
1124        String dateTimeString = date + ' ' + time;
1125
1126        ParsePosition pos = new ParsePosition(0);
1127        try {
1128            Date datetime = sFormatter.parse(dateTimeString, pos);
1129            if (datetime == null) return -1;
1130            return datetime.getTime();
1131        } catch (IllegalArgumentException e) {
1132            return -1;
1133        }
1134    }
1135
1136    private static float convertRationalLatLonToFloat(String rationalString, String ref) {
1137        try {
1138            String [] parts = rationalString.split(",");
1139
1140            String [] pair;
1141            pair = parts[0].split("/");
1142            double degrees = Double.parseDouble(pair[0].trim())
1143                    / Double.parseDouble(pair[1].trim());
1144
1145            pair = parts[1].split("/");
1146            double minutes = Double.parseDouble(pair[0].trim())
1147                    / Double.parseDouble(pair[1].trim());
1148
1149            pair = parts[2].split("/");
1150            double seconds = Double.parseDouble(pair[0].trim())
1151                    / Double.parseDouble(pair[1].trim());
1152
1153            double result = degrees + (minutes / 60.0) + (seconds / 3600.0);
1154            if ((ref.equals("S") || ref.equals("W"))) {
1155                return (float) -result;
1156            }
1157            return (float) result;
1158        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
1159            // Not valid
1160            throw new IllegalArgumentException();
1161        }
1162    }
1163
1164    // Loads EXIF attributes from a JPEG input stream.
1165    private void getJpegAttributes(InputStream inputStream) throws IOException {
1166        // See JPEG File Interchange Format Specification page 5.
1167        if (DEBUG) {
1168            Log.d(TAG, "getJpegAttributes starting with: " + inputStream);
1169        }
1170        DataInputStream dataInputStream = new DataInputStream(inputStream);
1171        byte marker;
1172        int bytesRead = 0;
1173        ++bytesRead;
1174        if ((marker = dataInputStream.readByte()) != MARKER) {
1175            throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff));
1176        }
1177        ++bytesRead;
1178        if (dataInputStream.readByte() != MARKER_SOI) {
1179            throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff));
1180        }
1181        while (true) {
1182            ++bytesRead;
1183            marker = dataInputStream.readByte();
1184            if (marker != MARKER) {
1185                throw new IOException("Invalid marker:" + Integer.toHexString(marker & 0xff));
1186            }
1187            ++bytesRead;
1188            marker = dataInputStream.readByte();
1189            if (DEBUG) {
1190                Log.d(TAG, "Found JPEG segment indicator: " + Integer.toHexString(marker & 0xff));
1191            }
1192
1193            // EOI indicates the end of an image and in case of SOS, JPEG image stream starts and
1194            // the image data will terminate right after.
1195            if (marker == MARKER_EOI || marker == MARKER_SOS) {
1196                break;
1197            }
1198            bytesRead += 2;
1199            int length = dataInputStream.readUnsignedShort() - 2;
1200            if (length < 0)
1201                throw new IOException("Invalid length");
1202            bytesRead += length;
1203            switch (marker) {
1204                case MARKER_APP1: {
1205                    if (DEBUG) {
1206                        Log.d(TAG, "MARKER_APP1");
1207                    }
1208                    bytesRead -= length;
1209                    if (length < 6) {
1210                        throw new IOException("Invalid exif");
1211                    }
1212                    byte[] identifier = new byte[6];
1213                    if (inputStream.read(identifier) != 6) {
1214                        throw new IOException("Invalid exif");
1215                    }
1216                    if (!Arrays.equals(identifier, IDENTIFIER_APP1)) {
1217                        throw new IOException("Invalid app1 identifier");
1218                    }
1219                    bytesRead += 6;
1220                    length -= 6;
1221                    if (length <= 0) {
1222                        throw new IOException("Invalid exif");
1223                    }
1224                    byte[] bytes = new byte[length];
1225                    if (dataInputStream.read(bytes) != length) {
1226                        throw new IOException("Invalid exif");
1227                    }
1228                    readExifSegment(bytes, bytesRead);
1229                    bytesRead += length;
1230                    length = 0;
1231                    break;
1232                }
1233
1234                case MARKER_COM: {
1235                    byte[] bytes = new byte[length];
1236                    if (dataInputStream.read(bytes) != length) {
1237                        throw new IOException("Invalid exif");
1238                    }
1239                    setAttribute("UserComment", new String(bytes, Charset.forName("US-ASCII")));
1240                    break;
1241                }
1242
1243                case MARKER_SOF0:
1244                case MARKER_SOF1:
1245                case MARKER_SOF2:
1246                case MARKER_SOF3:
1247                case MARKER_SOF5:
1248                case MARKER_SOF6:
1249                case MARKER_SOF7:
1250                case MARKER_SOF9:
1251                case MARKER_SOF10:
1252                case MARKER_SOF11:
1253                case MARKER_SOF13:
1254                case MARKER_SOF14:
1255                case MARKER_SOF15: {
1256                    dataInputStream.skipBytes(1);
1257                    setAttribute("ImageLength",
1258                            String.valueOf(dataInputStream.readUnsignedShort()));
1259                    setAttribute("ImageWidth", String.valueOf(dataInputStream.readUnsignedShort()));
1260                    length -= 5;
1261                    break;
1262                }
1263
1264                default: {
1265                    break;
1266                }
1267            }
1268            if (length < 0) {
1269                throw new IOException("Invalid length");
1270            }
1271            dataInputStream.skipBytes(length);
1272        }
1273    }
1274
1275    // Stores a new JPEG image with EXIF attributes into a given output stream.
1276    private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream)
1277            throws IOException {
1278        // See JPEG File Interchange Format Specification page 5.
1279        if (DEBUG) {
1280            Log.d(TAG, "saveJpegAttributes starting with (inputStream: " + inputStream
1281                    + ", outputStream: " + outputStream + ")");
1282        }
1283        DataInputStream dataInputStream = new DataInputStream(inputStream);
1284        ExifDataOutputStream dataOutputStream = new ExifDataOutputStream(outputStream);
1285        int bytesRead = 0;
1286        ++bytesRead;
1287        if (dataInputStream.readByte() != MARKER) {
1288            throw new IOException("Invalid marker");
1289        }
1290        dataOutputStream.writeByte(MARKER);
1291        ++bytesRead;
1292        if (dataInputStream.readByte() != MARKER_SOI) {
1293            throw new IOException("Invalid marker");
1294        }
1295        dataOutputStream.writeByte(MARKER_SOI);
1296
1297        byte[] bytes = new byte[4096];
1298
1299        while (true) {
1300            ++bytesRead;
1301            if (dataInputStream.readByte() != MARKER) {
1302                throw new IOException("Invalid marker");
1303            }
1304            dataOutputStream.writeByte(MARKER);
1305            ++bytesRead;
1306            byte marker = dataInputStream.readByte();
1307            dataOutputStream.writeByte(marker);
1308            switch (marker) {
1309                case MARKER_APP1: {
1310                    // Rewrite EXIF segment
1311                    int length = dataInputStream.readUnsignedShort() - 2;
1312                    if (length < 0)
1313                        throw new IOException("Invalid length");
1314                    bytesRead += 2;
1315                    int read;
1316                    while ((read = dataInputStream.read(
1317                            bytes, 0, Math.min(length, bytes.length))) > 0) {
1318                        length -= read;
1319                    }
1320                    bytesRead += length;
1321                    writeExifSegment(dataOutputStream, bytesRead);
1322                    break;
1323                }
1324                case MARKER_EOI:
1325                case MARKER_SOS: {
1326                    // Copy all the remaining data
1327                    Streams.copy(dataInputStream, dataOutputStream);
1328                    return;
1329                }
1330                default: {
1331                    // Copy JPEG segment
1332                    int length = dataInputStream.readUnsignedShort();
1333                    dataOutputStream.writeUnsignedShort(length);
1334                    if (length < 0)
1335                        throw new IOException("Invalid length");
1336                    length -= 2;
1337                    bytesRead += 2;
1338                    int read;
1339                    while ((read = dataInputStream.read(
1340                            bytes, 0, Math.min(length, bytes.length))) > 0) {
1341                        dataOutputStream.write(bytes, 0, read);
1342                        length -= read;
1343                    }
1344                    bytesRead += length;
1345                    break;
1346                }
1347            }
1348        }
1349    }
1350
1351    // Reads the given EXIF byte area and save its tag data into attributes.
1352    private void readExifSegment(byte[] exifBytes, int exifOffsetFromBeginning) throws IOException {
1353        // Parse TIFF Headers. See JEITA CP-3451C Table 1. page 10.
1354        ByteOrderAwarenessDataInputStream dataInputStream =
1355                new ByteOrderAwarenessDataInputStream(exifBytes);
1356
1357        // Read byte align
1358        short byteOrder = dataInputStream.readShort();
1359        switch (byteOrder) {
1360            case BYTE_ALIGN_II:
1361                if (DEBUG) {
1362                    Log.d(TAG, "readExifSegment: Byte Align II");
1363                }
1364                dataInputStream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
1365                break;
1366            case BYTE_ALIGN_MM:
1367                if (DEBUG) {
1368                    Log.d(TAG, "readExifSegment: Byte Align MM");
1369                }
1370                dataInputStream.setByteOrder(ByteOrder.BIG_ENDIAN);
1371                break;
1372            default:
1373                throw new IOException("Invalid byte order: " + Integer.toHexString(byteOrder));
1374        }
1375
1376        int startCode = dataInputStream.readUnsignedShort();
1377        if (startCode != 0x2a) {
1378            throw new IOException("Invalid exif start: " + Integer.toHexString(startCode));
1379        }
1380
1381        // Read first ifd offset
1382        long firstIfdOffset = dataInputStream.readUnsignedInt();
1383        if (firstIfdOffset < 8 || firstIfdOffset >= exifBytes.length) {
1384            throw new IOException("Invalid first Ifd offset: " + firstIfdOffset);
1385        }
1386        firstIfdOffset -= 8;
1387        if (firstIfdOffset > 0) {
1388            if (dataInputStream.skip(firstIfdOffset) != firstIfdOffset)
1389                throw new IOException("Couldn't jump to first Ifd: " + firstIfdOffset);
1390        }
1391
1392        // Read primary image TIFF image file directory.
1393        readImageFileDirectory(dataInputStream, IFD_TIFF_HINT);
1394
1395        // Process thumbnail.
1396        String jpegInterchangeFormatString = getAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name);
1397        String jpegInterchangeFormatLengthString =
1398                getAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name);
1399        if (jpegInterchangeFormatString != null && jpegInterchangeFormatLengthString != null) {
1400            try {
1401                int jpegInterchangeFormat = Integer.parseInt(jpegInterchangeFormatString);
1402                int jpegInterchangeFormatLength = Integer
1403                        .parseInt(jpegInterchangeFormatLengthString);
1404                // The following code limits the size of thumbnail size not to overflow EXIF data area.
1405                jpegInterchangeFormatLength = Math.min(jpegInterchangeFormat
1406                        + jpegInterchangeFormatLength, exifOffsetFromBeginning + exifBytes.length)
1407                        - jpegInterchangeFormat;
1408                if (jpegInterchangeFormat > 0 && jpegInterchangeFormatLength > 0) {
1409                    mHasThumbnail = true;
1410                    mThumbnailOffset = exifOffsetFromBeginning + jpegInterchangeFormat;
1411                    mThumbnailLength = jpegInterchangeFormatLength;
1412
1413                    if (mFilename == null && mAssetInputStream == null
1414                            && mSeekableFileDescriptor == null) {
1415                        // Save the thumbnail in memory if the input doesn't support reading again.
1416                        byte[] thumbnailBytes = new byte[jpegInterchangeFormatLength];
1417                        dataInputStream.seek(jpegInterchangeFormat);
1418                        dataInputStream.readFully(thumbnailBytes);
1419                        mThumbnailBytes = thumbnailBytes;
1420
1421                        if (DEBUG) {
1422                            Bitmap bitmap = BitmapFactory.decodeByteArray(
1423                                    thumbnailBytes, 0, thumbnailBytes.length);
1424                            Log.d(TAG, "Thumbnail offset: " + mThumbnailOffset + ", length: "
1425                                    + mThumbnailLength + ", width: " + bitmap.getWidth()
1426                                    + ", height: "
1427                                    + bitmap.getHeight());
1428                        }
1429                    }
1430                }
1431            } catch (NumberFormatException e) {
1432                // Ignored the corrupted image.
1433            }
1434        }
1435
1436        // For compatibility, keep data formats as follows.
1437        convertToInt(TAG_IMAGE_WIDTH);
1438        convertToInt(TAG_IMAGE_LENGTH);
1439        convertToInt(TAG_ORIENTATION);
1440        convertToInt(TAG_FLASH);
1441        convertToRational(TAG_FOCAL_LENGTH);
1442        convertToDouble(TAG_DIGITAL_ZOOM_RATIO);
1443        convertToDouble(TAG_EXPOSURE_TIME);
1444        convertToDouble(TAG_F_NUMBER);
1445        convertToDouble(TAG_SUBJECT_DISTANCE);
1446        convertToInt(TAG_ISO);
1447        convertToDouble(TAG_EXPOSURE_BIAS_VALUE);
1448        convertToInt(TAG_WHITE_BALANCE);
1449        convertToInt(TAG_LIGHT_SOURCE);
1450        convertToInt(TAG_METERING_MODE);
1451        convertToInt(TAG_EXPOSURE_PROGRAM);
1452        convertToInt(TAG_EXPOSURE_MODE);
1453        convertToRational(TAG_GPS_ALTITUDE);
1454        convertToInt(TAG_GPS_ALTITUDE_REF);
1455        convertToRational(TAG_GPS_LONGITUDE);
1456        convertToRational(TAG_GPS_LATITUDE);
1457        convertToTimetamp(TAG_GPS_TIMESTAMP);
1458
1459        // The value of DATETIME tag has the same value of DATETIME_ORIGINAL tag.
1460        String valueOfDateTimeOriginal = getAttribute("DateTimeOriginal");
1461        if (valueOfDateTimeOriginal != null) {
1462            setAttribute(TAG_DATETIME, valueOfDateTimeOriginal);
1463        }
1464
1465        // Add the default value.
1466        if (getAttribute(TAG_IMAGE_WIDTH) == null) {
1467            setAttribute(TAG_IMAGE_WIDTH, "0");
1468        }
1469        if (getAttribute(TAG_IMAGE_LENGTH) == null) {
1470            setAttribute(TAG_IMAGE_LENGTH, "0");
1471        }
1472        if (getAttribute(TAG_ORIENTATION) == null) {
1473            setAttribute(TAG_ORIENTATION, "0");
1474        }
1475        if (getAttribute(TAG_LIGHT_SOURCE) == null) {
1476            setAttribute(TAG_LIGHT_SOURCE, "0");
1477        }
1478    }
1479
1480    // Converts the tag value to timestamp; Otherwise deletes the given tag.
1481    private void convertToTimetamp(String tagName) {
1482        String entryValue = getAttribute(tagName);
1483        if (entryValue == null) return;
1484        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1485        String[] components = entryValue.split(",");
1486        if (dataFormat == IFD_FORMAT_SRATIONAL && components.length == 3) {
1487            StringBuilder stringBuilder = new StringBuilder();
1488            for (String component : components) {
1489                if (stringBuilder.length() > 0) {
1490                    stringBuilder.append(":");
1491                }
1492                String[] rationalNumber = component.split("/");
1493                int numerator = Integer.parseInt(rationalNumber[0]);
1494                int denominator = Integer.parseInt(rationalNumber[1]);
1495                if (denominator == 0) {
1496                    numerator = 0;
1497                    denominator = 1;
1498                }
1499                int value = numerator / denominator;
1500                stringBuilder.append(String.format("%02d", value));
1501            }
1502            setAttribute(tagName, stringBuilder.toString());
1503        } else if (dataFormat != IFD_FORMAT_STRING) {
1504            setAttribute(tagName, null);
1505        }
1506    }
1507
1508    // Checks the tag value of a given tag formatted in double type; Otherwise try to convert it to
1509    // double type or delete it.
1510    private void convertToDouble(String tagName) {
1511        String entryValue = getAttribute(tagName);
1512        if (entryValue == null) return;
1513        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1514        switch (dataFormat) {
1515            case IFD_FORMAT_SRATIONAL: {
1516                StringBuilder stringBuilder = new StringBuilder();
1517                String[] components = entryValue.split(",");
1518                for (String component : components) {
1519                    if (stringBuilder.length() > 0) {
1520                        stringBuilder.append(",");
1521                    }
1522                    String[] rationalNumber = component.split("/");
1523                    int numerator = Integer.parseInt(rationalNumber[0]);
1524                    int denominator = Integer.parseInt(rationalNumber[1]);
1525                    if (denominator == 0) {
1526                        numerator = 0;
1527                        denominator = 1;
1528                    }
1529                    stringBuilder.append((double) numerator / denominator);
1530                }
1531                setAttribute(tagName, stringBuilder.toString());
1532                break;
1533            }
1534            case IFD_FORMAT_DOUBLE:
1535                // Keep it as is.
1536                break;
1537            default:
1538                setAttribute(tagName, null);
1539                break;
1540        }
1541    }
1542
1543    // Checks the tag value of a given tag formatted in int type; Otherwise deletes the tag value.
1544    private void convertToRational(String tagName) {
1545        String entryValue = getAttribute(tagName);
1546        if (entryValue == null) return;
1547        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1548        switch (dataFormat) {
1549            case IFD_FORMAT_SLONG:
1550            case IFD_FORMAT_DOUBLE: {
1551                StringBuilder stringBuilder = new StringBuilder();
1552                String[] components = entryValue.split(",");
1553                for (String component : components) {
1554                    if (stringBuilder.length() > 0) {
1555                        stringBuilder.append(",");
1556                    }
1557                    double doubleValue = Double.parseDouble(component);
1558                    stringBuilder.append((int) (doubleValue * 10000.0)).append("/").append(10000);
1559                }
1560                setAttribute(tagName, stringBuilder.toString());
1561                break;
1562            }
1563            case IFD_FORMAT_SRATIONAL:
1564                // Keep it as is.
1565                break;
1566            default:
1567                setAttribute(tagName, null);
1568                break;
1569        }
1570    }
1571
1572    // Checks the tag value of a given tag formatted in int type; Otherwise deletes the tag value.
1573    private void convertToInt(String tagName) {
1574        String entryValue = getAttribute(tagName);
1575        if (entryValue == null) return;
1576        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1577        if (dataFormat != IFD_FORMAT_SLONG) {
1578            setAttribute(tagName, null);
1579        }
1580    }
1581
1582    // Reads image file directory, which is a tag group in EXIF.
1583    private void readImageFileDirectory(ByteOrderAwarenessDataInputStream dataInputStream, int hint)
1584            throws IOException {
1585        // See JEITA CP-3451 Figure 5. page 9.
1586        short numberOfDirectoryEntry = dataInputStream.readShort();
1587
1588        if (DEBUG) {
1589            Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry);
1590        }
1591
1592        for (short i = 0; i < numberOfDirectoryEntry; ++i) {
1593            int tagNumber = dataInputStream.readUnsignedShort();
1594            int dataFormat = dataInputStream.readUnsignedShort();
1595            int numberOfComponents = dataInputStream.readInt();
1596            long nextEntryOffset = dataInputStream.peek() + 4;  // next four bytes is for data
1597                                                                // offset or value.
1598
1599            if (DEBUG) {
1600                Log.d(TAG, String.format("tagNumber: %d, dataFormat: %d, numberOfComponents: %d",
1601                        tagNumber, dataFormat, numberOfComponents));
1602            }
1603
1604            // Read a value from data field or seek to the value offset which is stored in data
1605            // field if the size of the entry value is bigger than 4.
1606            int byteCount = numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat];
1607            if (byteCount > 4) {
1608                long offset = dataInputStream.readUnsignedInt();
1609                if (DEBUG) {
1610                    Log.d(TAG, "seek to data offset: " + offset);
1611                }
1612                dataInputStream.seek(offset);
1613            }
1614
1615            // Look up a corresponding tag from tag number
1616            String tagName = (String) sExifTagMapsForReading[hint].get(tagNumber);
1617            // Skip if the parsed tag number is not defined.
1618            if (tagName == null) {
1619                dataInputStream.seek(nextEntryOffset);
1620                continue;
1621            }
1622
1623            // Recursively parse IFD when a IFD pointer tag appears.
1624            int innerIfdHint = getIfdHintFromTagNumber(tagNumber);
1625            if (innerIfdHint >= 0) {
1626                long offset = -1L;
1627                // Get offset from data field
1628                switch (dataFormat) {
1629                    case IFD_FORMAT_USHORT: {
1630                        offset = dataInputStream.readUnsignedShort();
1631                        break;
1632                    }
1633                    case IFD_FORMAT_SSHORT: {
1634                        offset = dataInputStream.readShort();
1635                        break;
1636                    }
1637                    case IFD_FORMAT_ULONG: {
1638                        offset = dataInputStream.readUnsignedInt();
1639                        break;
1640                    }
1641                    case IFD_FORMAT_SLONG: {
1642                        offset = dataInputStream.readInt();
1643                        break;
1644                    }
1645                    default: {
1646                        // Nothing to do
1647                        break;
1648                    }
1649                }
1650                if (DEBUG) {
1651                    Log.d(TAG, String.format("Offset: %d, tagName: %s", offset, tagName));
1652                }
1653                if (offset > 0L) {
1654                    dataInputStream.seek(offset);
1655                    readImageFileDirectory(dataInputStream, innerIfdHint);
1656                }
1657
1658                dataInputStream.seek(nextEntryOffset);
1659                continue;
1660            }
1661
1662            if (numberOfComponents == 1 || dataFormat == IFD_FORMAT_STRING
1663                    || dataFormat == IFD_FORMAT_UNDEFINED) {
1664                String entryValue = readExifEntryValue(
1665                        dataInputStream, dataFormat, numberOfComponents);
1666                if (entryValue != null) {
1667                    setAttribute(tagName, entryValue);
1668                }
1669            } else {
1670                StringBuilder entryValueBuilder = new StringBuilder();
1671                for (int c = 0; c < numberOfComponents; ++c) {
1672                    if (entryValueBuilder.length() > 0) {
1673                        entryValueBuilder.append(",");
1674                    }
1675                    entryValueBuilder.append(readExifEntryValue(
1676                            dataInputStream, dataFormat, numberOfComponents));
1677                }
1678                setAttribute(tagName, entryValueBuilder.toString());
1679            }
1680
1681            if (dataInputStream.peek() != nextEntryOffset) {
1682                dataInputStream.seek(nextEntryOffset);
1683            }
1684        }
1685
1686        long nextIfdOffset = dataInputStream.readUnsignedInt();
1687        if (DEBUG) {
1688            Log.d(TAG, String.format("nextIfdOffset: %d", nextIfdOffset));
1689        }
1690        // The next IFD offset needs to be bigger than 8 since the first IFD offset is at least 8.
1691        if (nextIfdOffset > 8) {
1692            dataInputStream.seek(nextIfdOffset);
1693            readImageFileDirectory(dataInputStream, IFD_THUMBNAIL_HINT);
1694        }
1695    }
1696
1697    // Reads a value from where the entry value are stored.
1698    private String readExifEntryValue(ByteOrderAwarenessDataInputStream dataInputStream,
1699            int dataFormat, int numberOfComponents) throws IOException {
1700        // See TIFF 6.0 spec Types. page 15.
1701        switch (dataFormat) {
1702            case IFD_FORMAT_BYTE: {
1703                return String.valueOf(dataInputStream.readByte());
1704            }
1705            case IFD_FORMAT_SBYTE: {
1706                return String.valueOf(dataInputStream.readByte() & 0xff);
1707            }
1708            case IFD_FORMAT_USHORT: {
1709                return String.valueOf(dataInputStream.readUnsignedShort());
1710            }
1711            case IFD_FORMAT_SSHORT: {
1712                return String.valueOf(dataInputStream.readUnsignedInt());
1713            }
1714            case IFD_FORMAT_ULONG: {
1715                return String.valueOf(dataInputStream.readInt());
1716            }
1717            case IFD_FORMAT_SLONG: {
1718                return String.valueOf(dataInputStream.readInt());
1719            }
1720            case IFD_FORMAT_URATIONAL:
1721            case IFD_FORMAT_SRATIONAL: {
1722                int numerator = dataInputStream.readInt();
1723                int denominator = dataInputStream.readInt();
1724                return numerator + "/" + denominator;
1725            }
1726            case IFD_FORMAT_SINGLE: {
1727                return String.valueOf(dataInputStream.readFloat());
1728            }
1729            case IFD_FORMAT_DOUBLE: {
1730                return String.valueOf(dataInputStream.readDouble());
1731            }
1732            case IFD_FORMAT_UNDEFINED:  // Usually UNDEFINED format is ASCII.
1733            case IFD_FORMAT_STRING: {
1734                byte[] bytes = new byte[numberOfComponents];
1735                dataInputStream.readFully(bytes);
1736                int index = 0;
1737                if (numberOfComponents >= EXIF_ASCII_PREFIX.length) {
1738                    boolean same = true;
1739                    for (int i = 0; i < EXIF_ASCII_PREFIX.length; ++i) {
1740                        if (bytes[i] != EXIF_ASCII_PREFIX[i]) {
1741                            same = false;
1742                            break;
1743                        }
1744                    }
1745                    if (same) {
1746                        index = EXIF_ASCII_PREFIX.length;
1747                    }
1748                }
1749
1750                StringBuilder stringBuilder = new StringBuilder();
1751                while (true) {
1752                    int ch = bytes[index];
1753                    if (ch == 0)
1754                        break;
1755                    if (ch >= 32)
1756                        stringBuilder.append((char) ch);
1757                    else
1758                        stringBuilder.append('?');
1759                    ++index;
1760                    if (index == numberOfComponents)
1761                        break;
1762                }
1763                return stringBuilder.toString();
1764            }
1765            default: {
1766                // Nothing to do
1767                return null;
1768            }
1769        }
1770    }
1771
1772    // Gets the corresponding IFD group index of the given tag number for writing Exif Tags.
1773    private static int getIfdHintFromTagNumber(int tagNumber) {
1774        for (int i = 0; i < IFD_POINTER_TAG_HINTS.length; ++i) {
1775            if (IFD_POINTER_TAGS[i].number == tagNumber)
1776                return IFD_POINTER_TAG_HINTS[i];
1777        }
1778        return -1;
1779    }
1780
1781    // Writes an Exif segment into the given output stream.
1782    private int writeExifSegment(ExifDataOutputStream dataOutputStream, int exifOffsetFromBeginning)
1783            throws IOException {
1784        // The following variables are for calculating each IFD tag group size in bytes.
1785        int[] ifdOffsets = new int[EXIF_TAGS.length];
1786        int[] ifdDataSizes = new int[EXIF_TAGS.length];
1787
1788        // Remove IFD pointer tags (we'll re-add it later.)
1789        for (ExifTag tag : IFD_POINTER_TAGS) {
1790            setAttribute(tag.name, null);
1791        }
1792
1793        // Add IFD pointer tags. The next offset of primary image TIFF IFD will have thumbnail IFD
1794        // offset when there is one or more tags in the thumbnail IFD.
1795        if (!mAttributes[IFD_INTEROPERABILITY_HINT].isEmpty()) {
1796            mAttributes[IFD_EXIF_HINT].put(IFD_POINTER_TAGS[2].name, "0");
1797        }
1798        if (!mAttributes[IFD_EXIF_HINT].isEmpty()) {
1799            mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[0].name, "0");
1800        }
1801        if (!mAttributes[IFD_GPS_HINT].isEmpty()) {
1802            mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[1].name, "0");
1803        }
1804        // Remove old thumbnail data
1805        setAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name, null);
1806        setAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, null);
1807        if (mHasThumbnail) {
1808            mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_TAG.name, "0");
1809            mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name,
1810                    String.valueOf(mThumbnailLength));
1811        }
1812
1813        // Remove null value tags.
1814        for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
1815            for (Object obj : mAttributes[hint].entrySet().toArray()) {
1816                Map.Entry entry = (Map.Entry) obj;
1817                if (entry.getValue() == null) {
1818                    mAttributes[hint].remove(entry.getKey());
1819                }
1820            }
1821        }
1822
1823        // Calculate IFD group data area sizes. IFD group data area is assigned to save the entry
1824        // value which has a bigger size than 4 bytes.
1825        for (int i = 0; i < 5; ++i) {
1826            int sum = 0;
1827            for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) {
1828                String entryValue = (String) ((Map.Entry) entry).getValue();
1829                int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1830                int size = getSizeOfExifEntryValue(dataFormat, entryValue);
1831                if (size > 4) {
1832                    sum += size;
1833                }
1834            }
1835            ifdDataSizes[i] += sum;
1836        }
1837
1838        // Calculate IFD offsets.
1839        int position = 8;
1840        for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
1841            if (!mAttributes[hint].isEmpty()) {
1842                ifdOffsets[hint] = position;
1843                position += 2 + mAttributes[hint].size() * 12 + 4 + ifdDataSizes[hint];
1844            }
1845        }
1846        if (mHasThumbnail) {
1847            int thumbnailOffset = position;
1848            mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_TAG.name,
1849                    String.valueOf(thumbnailOffset));
1850            mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name,
1851                    String.valueOf(mThumbnailLength));
1852            mThumbnailOffset = exifOffsetFromBeginning + thumbnailOffset;
1853            position += mThumbnailLength;
1854        }
1855
1856        // Calculate the total size
1857        int totalSize = position + 8;  // eight bytes is for header part.
1858        if (DEBUG) {
1859            Log.d(TAG, "totalSize length: " + totalSize);
1860            for (int i = 0; i < 5; ++i) {
1861                Log.d(TAG, String.format("index: %d, offsets: %d, tag count: %d, data sizes: %d",
1862                        i, ifdOffsets[i], mAttributes[i].size(), ifdDataSizes[i]));
1863            }
1864        }
1865
1866        // Update IFD pointer tags with the calculated offsets.
1867        if (!mAttributes[IFD_EXIF_HINT].isEmpty()) {
1868            mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[0].name,
1869                    String.valueOf(ifdOffsets[IFD_EXIF_HINT]));
1870        }
1871        if (!mAttributes[IFD_GPS_HINT].isEmpty()) {
1872            mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[1].name,
1873                    String.valueOf(ifdOffsets[IFD_GPS_HINT]));
1874        }
1875        if (!mAttributes[IFD_INTEROPERABILITY_HINT].isEmpty()) {
1876            mAttributes[IFD_EXIF_HINT].put(IFD_POINTER_TAGS[2].name,
1877                    String.valueOf(ifdOffsets[IFD_INTEROPERABILITY_HINT]));
1878        }
1879
1880        // Write TIFF Headers. See JEITA CP-3451C Table 1. page 10.
1881        dataOutputStream.writeUnsignedShort(totalSize);
1882        dataOutputStream.write(IDENTIFIER_APP1);
1883        dataOutputStream.writeShort(BYTE_ALIGN_MM);
1884        dataOutputStream.writeUnsignedShort(0x2a);
1885        dataOutputStream.writeUnsignedInt(8);
1886
1887        // Write IFD groups. See JEITA CP-3451C Figure 7. page 12.
1888        for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
1889            if (!mAttributes[hint].isEmpty()) {
1890                // See JEITA CP-3451C 4.6.2 IFD structure. page 13.
1891                // Write entry count
1892                dataOutputStream.writeUnsignedShort(mAttributes[hint].size());
1893
1894                // Write entry info
1895                int dataOffset = ifdOffsets[hint] + 2 + mAttributes[hint].size() * 12 + 4;
1896                for (Map.Entry entry : (Set<Map.Entry>) mAttributes[hint].entrySet()) {
1897                    // Convert tag name to tag number.
1898                    int tagNumber = (int) sExifTagMapsForWriting[hint].get(entry.getKey());
1899                    String entryValue = (String) entry.getValue();
1900
1901                    int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1902                    int numberOfComponents = getNumberOfComponentsInExifEntryValue(dataFormat,
1903                            entryValue);
1904                    int byteCount = getSizeOfExifEntryValue(dataFormat, entryValue);
1905
1906                    dataOutputStream.writeUnsignedShort(tagNumber);
1907                    dataOutputStream.writeUnsignedShort(dataFormat);
1908                    dataOutputStream.writeInt(numberOfComponents);
1909                    if (byteCount > 4) {
1910                        dataOutputStream.writeUnsignedInt(dataOffset);
1911                        dataOffset += byteCount;
1912                    } else {
1913                        int bytesWritten = writeExifEntryValue(dataOutputStream, entryValue);
1914                        // Fill zero up to 4 bytes
1915                        if (bytesWritten < 4) {
1916                            for (int i = bytesWritten; i < 4; ++i) {
1917                                dataOutputStream.write(0);
1918                            }
1919                        }
1920                    }
1921                }
1922
1923                // Write the next offset. It writes the offset of thumbnail IFD if there is one or
1924                // more tags in the thumbnail IFD when the current IFD is the primary image TIFF
1925                // IFD; Otherwise 0.
1926                if (hint == 0 && !mAttributes[IFD_THUMBNAIL_HINT].isEmpty()) {
1927                    dataOutputStream.writeUnsignedInt(ifdOffsets[IFD_THUMBNAIL_HINT]);
1928                } else {
1929                    dataOutputStream.writeUnsignedInt(0);
1930                }
1931
1932                // Write values of data field exceeding 4 bytes after the next offset.
1933                for (Map.Entry entry : (Set<Map.Entry>) mAttributes[hint].entrySet()) {
1934                    String entryValue = (String) entry.getValue();
1935
1936                    int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1937                    int byteCount = getSizeOfExifEntryValue(dataFormat, entryValue);
1938                    if (byteCount > 4) {
1939                        writeExifEntryValue(dataOutputStream, entryValue);
1940                    }
1941                }
1942            }
1943        }
1944
1945        // Write thumbnail
1946        if (mHasThumbnail) {
1947            dataOutputStream.write(getThumbnail());
1948        }
1949
1950        return totalSize;
1951    }
1952
1953    // Writes EXIF entry value and its entry value type will be automatically determined.
1954    private static int writeExifEntryValue(ExifDataOutputStream dataOutputStream, String entryValue)
1955            throws IOException {
1956        int bytesWritten = 0;
1957        int dataFormat = getDataFormatOfExifEntryValue(entryValue);
1958
1959        // Values can be composed of several components. Each component is separated by char ','.
1960        String[] components = entryValue.split(",");
1961        for (String component : components) {
1962            switch (dataFormat) {
1963                case IFD_FORMAT_SLONG:
1964                    dataOutputStream.writeInt(Integer.parseInt(component));
1965                    bytesWritten += 4;
1966                    break;
1967                case IFD_FORMAT_DOUBLE:
1968                    dataOutputStream.writeDouble(Double.parseDouble(component));
1969                    bytesWritten += 8;
1970                    break;
1971                case IFD_FORMAT_STRING:
1972                    byte[] asciiArray = (component + '\0').getBytes(Charset.forName("US-ASCII"));
1973                    dataOutputStream.write(asciiArray);
1974                    bytesWritten += asciiArray.length;
1975                    break;
1976                case IFD_FORMAT_SRATIONAL:
1977                    String[] rationalNumber = component.split("/");
1978                    dataOutputStream.writeInt(Integer.parseInt(rationalNumber[0]));
1979                    dataOutputStream.writeInt(Integer.parseInt(rationalNumber[1]));
1980                    bytesWritten += 8;
1981                    break;
1982                default:
1983                    throw new IllegalArgumentException();
1984            }
1985        }
1986        return bytesWritten;
1987    }
1988
1989    // Determines the data format of EXIF entry value.
1990    private static int getDataFormatOfExifEntryValue(String entryValue) {
1991        // See TIFF 6.0 spec Types. page 15.
1992        // Take the first component if there are more than one component.
1993        if (entryValue.contains(",")) {
1994            entryValue = entryValue.split(",")[0];
1995        }
1996
1997        if (entryValue.contains("/")) {
1998            return IFD_FORMAT_SRATIONAL;
1999        }
2000        try {
2001            Integer.parseInt(entryValue);
2002            return IFD_FORMAT_SLONG;
2003        } catch (NumberFormatException e) {
2004            // Ignored
2005        }
2006        try {
2007            Double.parseDouble(entryValue);
2008            return IFD_FORMAT_DOUBLE;
2009        } catch (NumberFormatException e) {
2010            // Ignored
2011        }
2012        return IFD_FORMAT_STRING;
2013    }
2014
2015    // Determines the size of EXIF entry value.
2016    private static int getSizeOfExifEntryValue(int dataFormat, String entryValue) {
2017        // See TIFF 6.0 spec Types page 15.
2018        int bytesEstimated = 0;
2019        String[] components = entryValue.split(",");
2020        for (String component : components) {
2021            switch (dataFormat) {
2022                case IFD_FORMAT_SLONG:
2023                    bytesEstimated += 4;
2024                    break;
2025                case IFD_FORMAT_DOUBLE:
2026                    bytesEstimated += 8;
2027                    break;
2028                case IFD_FORMAT_STRING:
2029                    bytesEstimated
2030                            += (component + '\0').getBytes(Charset.forName("US-ASCII")).length;
2031                    break;
2032                case IFD_FORMAT_SRATIONAL:
2033                    bytesEstimated += 8;
2034                    break;
2035                default:
2036                    throw new IllegalArgumentException();
2037            }
2038        }
2039        return bytesEstimated;
2040    }
2041
2042    // Determines the number of components of EXIF entry value.
2043    private static int getNumberOfComponentsInExifEntryValue(int dataFormat, String entryValue) {
2044        if (dataFormat == IFD_FORMAT_STRING) {
2045            return (entryValue + '\0').getBytes(Charset.forName("US-ASCII")).length;
2046        }
2047        int count = 1;
2048        for (int i = 0; i < entryValue.length(); ++i) {
2049            if (entryValue.charAt(i) == ',') {
2050                ++count;
2051            }
2052        }
2053        return count;
2054    }
2055
2056    // An input stream to parse EXIF data area, which can be written in either little or big endian
2057    // order.
2058    private static class ByteOrderAwarenessDataInputStream extends ByteArrayInputStream {
2059        private static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN;
2060        private static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN;
2061
2062        private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN;
2063        private final long mLength;
2064        private long mPosition;
2065
2066        public ByteOrderAwarenessDataInputStream(byte[] bytes) {
2067            super(bytes);
2068            mLength = bytes.length;
2069            mPosition = 0L;
2070        }
2071
2072        public void setByteOrder(ByteOrder byteOrder) {
2073            mByteOrder = byteOrder;
2074        }
2075
2076        public void seek(long byteCount) throws IOException {
2077            mPosition = 0L;
2078            reset();
2079            if (skip(byteCount) != byteCount)
2080                throw new IOException("Couldn't seek up to the byteCount");
2081        }
2082
2083        public long peek() {
2084            return mPosition;
2085        }
2086
2087        public void readFully(byte[] buffer) throws IOException {
2088            mPosition += buffer.length;
2089            if (mPosition > mLength)
2090                throw new EOFException();
2091            if (super.read(buffer, 0, buffer.length) != buffer.length) {
2092                throw new IOException("Couldn't read up to the length of buffer");
2093            }
2094        }
2095
2096        public byte readByte() throws IOException {
2097            ++mPosition;
2098            if (mPosition > mLength)
2099                throw new EOFException();
2100            int ch = super.read();
2101            if (ch < 0)
2102                throw new EOFException();
2103            return (byte) ch;
2104        }
2105
2106        public short readShort() throws IOException {
2107            mPosition += 2;
2108            if (mPosition > mLength)
2109                throw new EOFException();
2110            int ch1 = super.read();
2111            int ch2 = super.read();
2112            if ((ch1 | ch2) < 0)
2113                throw new EOFException();
2114            if (mByteOrder == LITTLE_ENDIAN) {
2115                return (short) ((ch2 << 8) + (ch1));
2116            } else if (mByteOrder == BIG_ENDIAN) {
2117                return (short) ((ch1 << 8) + (ch2));
2118            }
2119            throw new IOException("Invalid byte order: " + mByteOrder);
2120        }
2121
2122        public int readInt() throws IOException {
2123            mPosition += 4;
2124            if (mPosition > mLength)
2125                throw new EOFException();
2126            int ch1 = super.read();
2127            int ch2 = super.read();
2128            int ch3 = super.read();
2129            int ch4 = super.read();
2130            if ((ch1 | ch2 | ch3 | ch4) < 0)
2131                throw new EOFException();
2132            if (mByteOrder == LITTLE_ENDIAN) {
2133                return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1);
2134            } else if (mByteOrder == BIG_ENDIAN) {
2135                return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4);
2136            }
2137            throw new IOException("Invalid byte order: " + mByteOrder);
2138        }
2139
2140        @Override
2141        public long skip(long byteCount) {
2142            long skipped = super.skip(Math.min(byteCount, mLength - mPosition));
2143            mPosition += skipped;
2144            return skipped;
2145        }
2146
2147        public int readUnsignedShort() throws IOException {
2148            mPosition += 2;
2149            if (mPosition > mLength)
2150                throw new EOFException();
2151            int ch1 = super.read();
2152            int ch2 = super.read();
2153            if ((ch1 | ch2) < 0)
2154                throw new EOFException();
2155            if (mByteOrder == LITTLE_ENDIAN) {
2156                return ((ch2 << 8) + (ch1));
2157            } else if (mByteOrder == BIG_ENDIAN) {
2158                return ((ch1 << 8) + (ch2));
2159            }
2160            throw new IOException("Invalid byte order: " + mByteOrder);
2161        }
2162
2163        public long readUnsignedInt() throws IOException {
2164            return readInt() & 0xffffffffL;
2165        }
2166
2167        public long readLong() throws IOException {
2168            mPosition += 8;
2169            if (mPosition > mLength)
2170                throw new EOFException();
2171            int ch1 = super.read();
2172            int ch2 = super.read();
2173            int ch3 = super.read();
2174            int ch4 = super.read();
2175            int ch5 = super.read();
2176            int ch6 = super.read();
2177            int ch7 = super.read();
2178            int ch8 = super.read();
2179            if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0)
2180                throw new EOFException();
2181            if (mByteOrder == LITTLE_ENDIAN) {
2182                return (((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40)
2183                        + ((long) ch5 << 32) + ((long) ch4 << 24) + ((long) ch3 << 16)
2184                        + ((long) ch2 << 8) + (long) ch1);
2185            } else if (mByteOrder == BIG_ENDIAN) {
2186                return (((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40)
2187                        + ((long) ch4 << 32) + ((long) ch5 << 24) + ((long) ch6 << 16)
2188                        + ((long) ch7 << 8) + (long) ch8);
2189            }
2190            throw new IOException("Invalid byte order: " + mByteOrder);
2191        }
2192
2193        public float readFloat() throws IOException {
2194            return Float.intBitsToFloat(readInt());
2195        }
2196
2197        public double readDouble() throws IOException {
2198            return Double.longBitsToDouble(readLong());
2199        }
2200    }
2201
2202    // An output stream to write EXIF data area, that will be written in big endian byte order.
2203    private static class ExifDataOutputStream extends DataOutputStream {
2204        public ExifDataOutputStream(OutputStream out) {
2205            super(out);
2206        }
2207
2208        public void writeUnsignedShort(int val) throws IOException {
2209            writeShort((short) val);
2210        }
2211
2212        public void writeUnsignedInt(long val) throws IOException {
2213            writeInt((int) val);
2214        }
2215    }
2216
2217    // JNI methods for RAW formats.
2218    private static native void nativeInitRaw();
2219    private static native byte[] nativeGetThumbnailFromAsset(
2220            long asset, int thumbnailOffset, int thumbnailLength);
2221    private static native HashMap nativeGetRawAttributesFromAsset(long asset);
2222    private static native HashMap nativeGetRawAttributesFromFileDescriptor(FileDescriptor fd);
2223    private static native HashMap nativeGetRawAttributesFromInputStream(InputStream in);
2224}
2225