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