Debian Codegraph @

src/com/drew/metadata/gif/GifReader.java

raw symbols SCIP
1 /*
2 * Copyright 2002-2019 Drew Noakes and contributors
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 * More information about this project is available at:
17 *
18 * https://drewnoakes.com/code/exif/
19 * https://github.com/drewnoakes/metadata-extractor
20 */
21 package com.drew.metadata.gif;
22
23 import com.drew.lang.ByteArrayReader;
24 import com.drew.lang.Charsets;
25 import com.drew.lang.SequentialReader;
26 import com.drew.lang.annotations.NotNull;
27 import com.drew.lang.annotations.Nullable;
28
29 import com.drew.metadata.*;
30 import com.drew.metadata.gif.GifControlDirectory.DisposalMethod;
31 import com.drew.metadata.icc.IccReader;
32 import com.drew.metadata.xmp.XmpReader;
33
34 import java.io.ByteArrayOutputStream;
35 import java.io.IOException;
36
37 /**
38 * Reader of GIF encoded data.
39 *
40 * Resources:
41 * <ul>
42 * <li>https://wiki.whatwg.org/wiki/GIF</li>
43 * <li>https://www.w3.org/Graphics/GIF/spec-gif89a.txt</li>
44 * <li>http://web.archive.org/web/20100929230301/http://www.etsimo.uniovi.es/gifanim/gif87a.txt</li>
45 * </ul>
46 *
47 * @author Drew Noakes https://drewnoakes.com
48 * @author Kevin Mott https://github.com/kwhopper
49 */
50 public class GifReader
51 {
52 private static final String GIF_87A_VERSION_IDENTIFIER = "87a";
53 private static final String GIF_89A_VERSION_IDENTIFIER = "89a";
54
55 public void extract(@NotNull final SequentialReader reader, final @NotNull Metadata metadata)
56 {
57 reader.setMotorolaByteOrder(false);
58
59 GifHeaderDirectory header;
60 try {
61 header = readGifHeader(reader);
62 metadata.addDirectory(header);
63 } catch (IOException ex) {
64 metadata.addDirectory(new ErrorDirectory("IOException processing GIF data"));
65 return;
66 }
67
68 if(header.hasErrors())
69 return;
70
71 try {
72 // Skip over any global colour table if GlobalColorTable is present.
73 Integer globalColorTableSize = null;
74 try {
75 boolean hasGlobalColorTable = header.getBoolean(GifHeaderDirectory.TAG_HAS_GLOBAL_COLOR_TABLE);
76 if(hasGlobalColorTable) {
77 globalColorTableSize = header.getInteger(GifHeaderDirectory.TAG_COLOR_TABLE_SIZE);
78 }
79 } catch (MetadataException e) {
80 // This exception should never occur here.
81 metadata.addDirectory(new ErrorDirectory("GIF did not had hasGlobalColorTable bit."));
82 }
83 if (globalColorTableSize != null)
84 {
85 // Colour table has R/G/B byte triplets
86 reader.skip(3 * globalColorTableSize);
87 }
88
89 // After the header comes a sequence of blocks
90 while (true)
91 {
92 byte marker;
93 try {
94 marker = reader.getInt8();
95 } catch (IOException ex) {
96 return;
97 }
98
99 switch (marker)
100 {
101 case (byte)'!': // 0x21
102 {
103 readGifExtensionBlock(reader, metadata);
104 break;
105 }
106 case (byte)',': // 0x2c
107 {
108 metadata.addDirectory(readImageBlock(reader));
109
110 // skip image data blocks
111 skipBlocks(reader);
112 break;
113 }
114 case (byte)';': // 0x3b
115 {
116 // terminator
117 return;
118 }
119 default:
120 {
121 // Anything other than these types is unexpected.
122 // GIF87a spec says to keep reading until a separator is found.
123 // GIF89a spec says file is corrupt.
124 metadata.addDirectory(new ErrorDirectory("Unknown gif block marker found."));
125 return;
126 }
127 }
128 }
129 } catch (IOException e) {
130 metadata.addDirectory(new ErrorDirectory("IOException processing GIF data"));
131 }
132 }
133
134 private static GifHeaderDirectory readGifHeader(@NotNull final SequentialReader reader) throws IOException
135 {
136 // FILE HEADER
137 //
138 // 3 - signature: "GIF"
139 // 3 - version: either "87a" or "89a"
140 //
141 // LOGICAL SCREEN DESCRIPTOR
142 //
143 // 2 - pixel width
144 // 2 - pixel height
145 // 1 - screen and color map information flags (0 is LSB)
146 // 0-2 Size of the global color table
147 // 3 Color table sort flag (89a only)
148 // 4-6 Color resolution
149 // 7 Global color table flag
150 // 1 - background color index
151 // 1 - pixel aspect ratio
152
153 GifHeaderDirectory headerDirectory = new GifHeaderDirectory();
154
155 String signature = reader.getString(3);
156
157 if (!signature.equals("GIF"))
158 {
159 headerDirectory.addError("Invalid GIF file signature");
160 return headerDirectory;
161 }
162
163 String version = reader.getString(3);
164
165 if (!version.equals(GIF_87A_VERSION_IDENTIFIER) && !version.equals(GIF_89A_VERSION_IDENTIFIER)) {
166 headerDirectory.addError("Unexpected GIF version");
167 return headerDirectory;
168 }
169
170 headerDirectory.setString(GifHeaderDirectory.TAG_GIF_FORMAT_VERSION, version);
171
172 // LOGICAL SCREEN DESCRIPTOR
173
174 headerDirectory.setInt(GifHeaderDirectory.TAG_IMAGE_WIDTH, reader.getUInt16());
175 headerDirectory.setInt(GifHeaderDirectory.TAG_IMAGE_HEIGHT, reader.getUInt16());
176
177 short flags = reader.getUInt8();
178
179 // First three bits = (BPP - 1)
180 int colorTableSize = 1 << ((flags & 7) + 1);
181 int bitsPerPixel = ((flags & 0x70) >> 4) + 1;
182 boolean hasGlobalColorTable = (flags >> 7) != 0;
183
184 headerDirectory.setInt(GifHeaderDirectory.TAG_COLOR_TABLE_SIZE, colorTableSize);
185
186 if (version.equals(GIF_89A_VERSION_IDENTIFIER)) {
187 boolean isColorTableSorted = (flags & 8) != 0;
188 headerDirectory.setBoolean(GifHeaderDirectory.TAG_IS_COLOR_TABLE_SORTED, isColorTableSorted);
189 }
190
191 headerDirectory.setInt(GifHeaderDirectory.TAG_BITS_PER_PIXEL, bitsPerPixel);
192 headerDirectory.setBoolean(GifHeaderDirectory.TAG_HAS_GLOBAL_COLOR_TABLE, hasGlobalColorTable);
193
194 headerDirectory.setInt(GifHeaderDirectory.TAG_BACKGROUND_COLOR_INDEX, reader.getUInt8());
195
196 int aspectRatioByte = reader.getUInt8();
197 if (aspectRatioByte != 0) {
198 float pixelAspectRatio = (float)((aspectRatioByte + 15d) / 64d);
199 headerDirectory.setFloat(GifHeaderDirectory.TAG_PIXEL_ASPECT_RATIO, pixelAspectRatio);
200 }
201
202 return headerDirectory;
203 }
204
205 private static void readGifExtensionBlock(SequentialReader reader, Metadata metadata) throws IOException
206 {
207 byte extensionLabel = reader.getInt8();
208 short blockSizeBytes = reader.getUInt8();
209 long blockStartPos = reader.getPosition();
210
211 switch (extensionLabel)
212 {
213 case (byte) 0x01:
214 Directory plainTextBlock = readPlainTextBlock(reader, blockSizeBytes);
215 if (plainTextBlock != null)
216 metadata.addDirectory(plainTextBlock);
217 break;
218 case (byte) 0xf9:
219 metadata.addDirectory(readControlBlock(reader));
220 break;
221 case (byte) 0xfe:
222 metadata.addDirectory(readCommentBlock(reader, blockSizeBytes));
223 break;
224 case (byte) 0xff:
225 readApplicationExtensionBlock(reader, blockSizeBytes, metadata);
226 break;
227 default:
228 metadata.addDirectory(new ErrorDirectory(String.format("Unsupported GIF extension block with type 0x%02X.", extensionLabel)));
229 break;
230 }
231
232 long skipCount = blockStartPos + blockSizeBytes - reader.getPosition();
233 if (skipCount > 0)
234 reader.skip(skipCount);
235 }
236
237 @Nullable
238 private static Directory readPlainTextBlock(SequentialReader reader, int blockSizeBytes) throws IOException
239 {
240 // It seems this extension is deprecated. If somebody finds an image with this in it, could implement here.
241 // Just skip the entire block for now.
242
243 if (blockSizeBytes != 12)
244 return new ErrorDirectory(String.format("Invalid GIF plain text block size. Expected 12, got %d.", blockSizeBytes));
245
246 // skip 'blockSizeBytes' bytes
247 reader.skip(12);
248
249 // keep reading and skipping until a 0 byte is reached
250 skipBlocks(reader);
251
252 return null;
253 }
254
255 private static GifCommentDirectory readCommentBlock(SequentialReader reader, int blockSizeBytes) throws IOException
256 {
257 byte[] buffer = gatherBytes(reader, blockSizeBytes);
258 return new GifCommentDirectory(new StringValue(buffer, Charsets.ASCII));
259 }
260
261 private static void readApplicationExtensionBlock(SequentialReader reader, int blockSizeBytes, Metadata metadata) throws IOException
262 {
263 if (blockSizeBytes != 11)
264 {
265 metadata.addDirectory(new ErrorDirectory(String.format("Invalid GIF application extension block size. Expected 11, got %d.", blockSizeBytes)));
266 return;
267 }
268
269 String extensionType = reader.getString(blockSizeBytes, Charsets.UTF_8);
270
271 if (extensionType.equals("XMP DataXMP"))
272 {
273 // XMP data extension
274 byte[] xmpBytes = gatherBytes(reader);
275 int xmpLengh = xmpBytes.length - 257; // Exclude the "magic trailer", see XMP Specification Part 3, 1.1.2 GIF
276 if (xmpLengh > 0) {
277 // Only extract valid blocks
278 new XmpReader().extract(xmpBytes, 0, xmpBytes.length - 257, metadata, null);
279 }
280 }
281 else if (extensionType.equals("ICCRGBG1012"))
282 {
283 // ICC profile extension
284 byte[] iccBytes = gatherBytes(reader, ((int) reader.getByte()) & 0xff);
285 if (iccBytes.length != 0)
286 new IccReader().extract(new ByteArrayReader(iccBytes), metadata);
287 }
288 else if (extensionType.equals("NETSCAPE2.0"))
289 {
290 reader.skip(2);
291 // Netscape's animated GIF extension
292 // Iteration count (0 means infinite)
293 int iterationCount = reader.getUInt16();
294 // Skip terminator
295 reader.skip(1);
296 GifAnimationDirectory animationDirectory = new GifAnimationDirectory();
297 animationDirectory.setInt(GifAnimationDirectory.TAG_ITERATION_COUNT, iterationCount);
298 metadata.addDirectory(animationDirectory);
299 }
300 else
301 {
302 skipBlocks(reader);
303 }
304 }
305
306 private static GifControlDirectory readControlBlock(SequentialReader reader) throws IOException
307 {
308 GifControlDirectory directory = new GifControlDirectory();
309
310 short packedFields = reader.getUInt8();
311 directory.setObject(GifControlDirectory.TAG_DISPOSAL_METHOD, DisposalMethod.typeOf((packedFields >> 2) & 7));
312 directory.setBoolean(GifControlDirectory.TAG_USER_INPUT_FLAG, (packedFields & 2) >> 1 == 1);
313 directory.setBoolean(GifControlDirectory.TAG_TRANSPARENT_COLOR_FLAG, (packedFields & 1) == 1);
314 directory.setInt(GifControlDirectory.TAG_DELAY, reader.getUInt16());
315 directory.setInt(GifControlDirectory.TAG_TRANSPARENT_COLOR_INDEX, reader.getUInt8());
316
317 // skip 0x0 block terminator
318 reader.skip(1);
319
320 return directory;
321 }
322
323 private static GifImageDirectory readImageBlock(SequentialReader reader) throws IOException
324 {
325 GifImageDirectory imageDirectory = new GifImageDirectory();
326
327 imageDirectory.setInt(GifImageDirectory.TAG_LEFT, reader.getUInt16());
328 imageDirectory.setInt(GifImageDirectory.TAG_TOP, reader.getUInt16());
329 imageDirectory.setInt(GifImageDirectory.TAG_WIDTH, reader.getUInt16());
330 imageDirectory.setInt(GifImageDirectory.TAG_HEIGHT, reader.getUInt16());
331
332 byte flags = reader.getByte();
333 boolean hasColorTable = (flags >> 7) != 0;
334 boolean isInterlaced = (flags & 0x40) != 0;
335
336 imageDirectory.setBoolean(GifImageDirectory.TAG_HAS_LOCAL_COLOUR_TABLE, hasColorTable);
337 imageDirectory.setBoolean(GifImageDirectory.TAG_IS_INTERLACED, isInterlaced);
338
339 if (hasColorTable)
340 {
341 boolean isColorTableSorted = (flags & 0x20) != 0;
342 imageDirectory.setBoolean(GifImageDirectory.TAG_IS_COLOR_TABLE_SORTED, isColorTableSorted);
343
344 int bitsPerPixel = (flags & 0x7) + 1;
345 imageDirectory.setInt(GifImageDirectory.TAG_LOCAL_COLOUR_TABLE_BITS_PER_PIXEL, bitsPerPixel);
346
347 // skip color table
348 reader.skip(3 * (2 << (flags & 0x7)));
349 }
350
351 // skip "LZW Minimum Code Size" byte
352 reader.getByte();
353
354 return imageDirectory;
355 }
356
357 private static byte[] gatherBytes(SequentialReader reader) throws IOException
358 {
359 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
360 byte[] buffer = new byte[257];
361
362 while (true)
363 {
364 byte b = reader.getByte();
365 if (b == 0)
366 return bytes.toByteArray();
367
368 int bInt = b & 0xFF;
369
370 buffer[0] = b;
371 reader.getBytes(buffer, 1, bInt);
372 bytes.write(buffer, 0, bInt + 1);
373 }
374 }
375
376 private static byte[] gatherBytes(SequentialReader reader, int firstLength) throws IOException
377 {
378 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
379
380 int length = firstLength;
381
382 while (length > 0)
383 {
384 buffer.write(reader.getBytes(length), 0, length);
385
386 length = reader.getByte() & 0xff;
387 }
388
389 return buffer.toByteArray();
390 }
391
392 private static void skipBlocks(SequentialReader reader) throws IOException
393 {
394 while (true)
395 {
396 short length = reader.getUInt8();
397
398 if (length == 0)
399 return;
400
401 reader.skip(length);
402 }
403 }
404 }