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