Debian Codegraph @

src/com/drew/metadata/eps/EpsReader.java

raw symbols SCIP
1 package com.drew.metadata.eps;
2
3 import com.drew.imaging.tiff.TiffProcessingException;
4 import com.drew.imaging.tiff.TiffReader;
5 import com.drew.lang.*;
6 import com.drew.lang.annotations.NotNull;
7 import com.drew.lang.annotations.Nullable;
8 import com.drew.metadata.Metadata;
9 import com.drew.metadata.icc.IccReader;
10 import com.drew.metadata.photoshop.PhotoshopReader;
11 import com.drew.metadata.photoshop.PhotoshopTiffHandler;
12 import com.drew.metadata.xmp.XmpReader;
13
14 import java.io.ByteArrayOutputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17
18 /**
19 * Reads file passed in through SequentialReader and parses encountered data:
20 * <ul>
21 * <li>Basic EPS Comments</li>
22 * <li>EXIF</li>
23 * <li>Photoshop</li>
24 * <li>IPTC</li>
25 * <li>ICC Profile</li>
26 * <li>XMP</li>
27 * </ul>
28 * EPS comments are retrieved from EPS directory. Photoshop, ICC Profile, and XMP processing
29 * is passed to their respective reader.
30 * <p/>
31 * EPS Constraints (Source: https://www-cdf.fnal.gov/offline/PostScript/5001.PDF pg.18):
32 * <ul>
33 * <li>Max line length is 255 characters</li>
34 * <li>Lines end with a CR(0xD) or LF(0xA) character (or both, in practice)</li>
35 * <li>':' separates keywords (considered part of the keyword)</li>
36 * <li>Whitespace is either a space(0x20) or tab(0x9)</li>
37 * <li>If there is more than one header, the 1st is truth</li>
38 * </ul>
39 *
40 * @author Payton Garland
41 */
42 public class EpsReader
43 {
44 private int _previousTag;
45
46 /**
47 * Filter method that determines if file will contain an EPS Header. If it does, it will read the necessary
48 * data and then set the position to the beginning of the PostScript data. If it does not, the position will not
49 * be changed. After both scenarios, the main extract method is called.
50 *
51 * @param inputStream InputStream containing file
52 * @param metadata Metadata to add directory to and extracted data
53 */
54 public void extract(@NotNull final InputStream inputStream, @NotNull final Metadata metadata) throws IOException
55 {
56 RandomAccessStreamReader reader = new RandomAccessStreamReader(inputStream);
57 EpsDirectory directory = new EpsDirectory();
58 metadata.addDirectory(directory);
59
60 /*
61 * 0xC5D0D3C6 signifies an EPS Header block which contains 32-bytes of basic information
62 *
63 * 0x25215053 (%!PS) signifies an EPS File and leads straight into the PostScript
64 */
65 switch (reader.getInt32(0)) {
66 case 0xC5D0D3C6:
67 reader.setMotorolaByteOrder(false);
68 int postScriptOffset = reader.getInt32(4);
69 int postScriptLength = reader.getInt32(8);
70 int wmfOffset = reader.getInt32(12);
71 int wmfSize = reader.getInt32(16);
72 int tifOffset = reader.getInt32(20);
73 int tifSize = reader.getInt32(24);
74 //int checkSum = reader.getInt32(28);
75
76 // Get Tiff/WMF preview data if applicable
77 if (tifSize != 0) {
78 directory.setInt(EpsDirectory.TAG_TIFF_PREVIEW_SIZE, tifSize);
79 directory.setInt(EpsDirectory.TAG_TIFF_PREVIEW_OFFSET, tifOffset);
80 // Get Tiff metadata
81 try {
82 ByteArrayReader byteArrayReader = new ByteArrayReader(reader.getBytes(tifOffset, tifSize));
83 new TiffReader().processTiff(byteArrayReader, new PhotoshopTiffHandler(metadata, null), 0);
84 } catch (TiffProcessingException ex) {
85 directory.addError("Unable to process TIFF data: " + ex.getMessage());
86 }
87 } else if (wmfSize != 0) {
88 directory.setInt(EpsDirectory.TAG_WMF_PREVIEW_SIZE, wmfSize);
89 directory.setInt(EpsDirectory.TAG_WMF_PREVIEW_OFFSET, wmfOffset);
90 }
91
92 // TODO avoid allocating byte array here -- read directly from InputStream
93 extract(directory, metadata, new SequentialByteArrayReader(reader.getBytes(postScriptOffset, postScriptLength)));
94 break;
95 case 0x25215053:
96 inputStream.reset();
97 extract(directory, metadata, new StreamReader(inputStream));
98 break;
99 default:
100 directory.addError("File type not supported.");
101 break;
102 }
103 }
104
105 /**
106 * Main method that parses all comments and then distributes data extraction among other methods that parse the
107 * rest of file and store encountered data in metadata (if there exists an entry in EpsDirectory
108 * for the found data). Reads until a begin data/binary comment is found or _reader's estimated
109 * available data has run out (or AI09 End Private Data). Will extract data from normal EPS comments, Photoshop, ICC, and XMP.
110 *
111 * @param metadata Metadata to add directory to and extracted data
112 */
113 private void extract(@NotNull final EpsDirectory directory, @NotNull Metadata metadata, @NotNull SequentialReader reader) throws IOException
114 {
115 StringBuilder line = new StringBuilder();
116
117 while (true) {
118 line.setLength(0);
119
120 // Read the next line, excluding any trailing newline character
121 // Note that for Windows-style line endings ("\r\n") the outer loop will be run a second time with an empty
122 // string, which is fine.
123 while (true) {
124 char c = (char)reader.getByte();
125 if (c == '\r' || c == '\n')
126 break;
127 line.append(c);
128 }
129
130 // Stop when we hit a line that is not a comment
131 if (line.length() != 0 && line.charAt(0) != '%')
132 break;
133
134 String name;
135
136 // ':' signifies there is an associated keyword (should be put in directory)
137 // otherwise, the name could be a marker
138 int colonIndex = line.indexOf(":");
139 if (colonIndex != -1) {
140 name = line.substring(0, colonIndex).trim();
141 String value = line.substring(colonIndex + 1).trim();
142 addToDirectory(directory, name, value);
143 } else {
144 name = line.toString().trim();
145 }
146
147 // Some comments will both have a value and signify a new block to follow
148 if (name.equals("%BeginPhotoshop")) {
149 extractPhotoshopData(metadata, reader);
150 } else if (name.equals("%%BeginICCProfile")) {
151 extractIccData(metadata, reader);
152 } else if (name.equals("%begin_xml_packet")) {
153 extractXmpData(metadata, reader);
154 }
155 }
156 }
157
158 /**
159 * Default case that adds comment with keyword to directory
160 *
161 * @param directory EpsDirectory to add extracted data to
162 * @param name String that holds name of current comment
163 * @param value String that holds value of current comment
164 */
165 private void addToDirectory(@NotNull final EpsDirectory directory, String name, String value) throws IOException
166 {
167 Integer tag = EpsDirectory._tagIntegerMap.get(name);
168
169 if (tag == null)
170 return;
171
172 switch (tag) {
173 case EpsDirectory.TAG_IMAGE_DATA:
174 extractImageData(directory, value);
175 break;
176 case EpsDirectory.TAG_CONTINUE_LINE:
177 directory.setString(_previousTag, directory.getString(_previousTag) + " " + value);
178 break;
179 default:
180 if (EpsDirectory._tagNameMap.containsKey(tag) && !directory.containsTag(tag)) {
181 directory.setString(tag, value);
182 _previousTag = tag;
183 } else {
184 // Set previous tag to an Integer that doesn't exist in EpsDirectory
185 _previousTag = 0;
186 }
187 break;
188 }
189 _previousTag = tag;
190 }
191
192 /**
193 * Parses <code>%ImageData</code> comment which holds several values including width in px,
194 * height in px and color type.
195 */
196 private static void extractImageData(@NotNull final EpsDirectory directory, String imageData) throws IOException
197 {
198 // %ImageData: 1000 1000 8 3 1 1000 7 "beginimage"
199 directory.setString(EpsDirectory.TAG_IMAGE_DATA, imageData.trim());
200
201 String[] imageDataParts = imageData.split(" ");
202
203 int width = Integer.parseInt(imageDataParts[0]);
204 int height = Integer.parseInt(imageDataParts[1]);
205 int colorType = Integer.parseInt(imageDataParts[3]);
206
207 // Only add values that are not already present
208 if (!directory.containsTag(EpsDirectory.TAG_IMAGE_WIDTH))
209 directory.setInt(EpsDirectory.TAG_IMAGE_WIDTH, width);
210 if (!directory.containsTag(EpsDirectory.TAG_IMAGE_HEIGHT))
211 directory.setInt(EpsDirectory.TAG_IMAGE_HEIGHT, height);
212 if (!directory.containsTag(EpsDirectory.TAG_COLOR_TYPE))
213 directory.setInt(EpsDirectory.TAG_COLOR_TYPE, colorType);
214
215 if (!directory.containsTag(EpsDirectory.TAG_RAM_SIZE)) {
216 int bytesPerPixel = 0;
217 if (colorType == 1)
218 bytesPerPixel = 1; // grayscale
219 else if (colorType == 2 || colorType == 3)
220 bytesPerPixel = 3; // Lab or RGB
221 else if (colorType == 4)
222 bytesPerPixel = 3; // CMYK
223
224 if (bytesPerPixel != 0)
225 directory.setInt(EpsDirectory.TAG_RAM_SIZE, bytesPerPixel * width * height);
226 }
227 }
228
229 /**
230 * Decodes a commented hex section, and uses {@link PhotoshopReader} to decode the resulting data.
231 */
232 private static void extractPhotoshopData(@NotNull final Metadata metadata, @NotNull SequentialReader reader) throws IOException
233 {
234 byte[] buffer = decodeHexCommentBlock(reader);
235
236 if (buffer != null)
237 new PhotoshopReader().extract(new SequentialByteArrayReader(buffer), buffer.length, metadata);
238 }
239
240 /**
241 * Decodes a commented hex section, and uses {@link IccReader} to decode the resulting data.
242 */
243 private static void extractIccData(@NotNull final Metadata metadata, @NotNull SequentialReader reader) throws IOException
244 {
245 byte[] buffer = decodeHexCommentBlock(reader);
246
247 if (buffer != null)
248 new IccReader().extract(new ByteArrayReader(buffer), metadata);
249 }
250
251 /**
252 * Extracts an XMP xpacket, and uses {@link XmpReader} to decode the resulting data.
253 */
254 private static void extractXmpData(@NotNull final Metadata metadata, @NotNull SequentialReader reader) throws IOException
255 {
256 byte[] bytes = readUntil(reader, "<?xpacket end=\"w\"?>".getBytes());
257 String xmp = new String(bytes, Charsets.UTF_8);
258 new XmpReader().extract(xmp, metadata);
259 }
260
261 /**
262 * Reads all bytes until the given sentinel is observed.
263 * The sentinel will be included in the returned bytes.
264 */
265 private static byte[] readUntil(@NotNull SequentialReader reader, @NotNull byte[] sentinel) throws IOException
266 {
267 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
268
269 final int length = sentinel.length;
270 int depth = 0;
271
272 while (depth != length) {
273 byte b = reader.getByte();
274 if (b == sentinel[depth])
275 depth++;
276 else
277 depth = 0;
278 bytes.write(b);
279 }
280
281 return bytes.toByteArray();
282 }
283
284 /**
285 * EPS files can contain hexadecimal-encoded ASCII blocks, each prefixed with <c>"% "</c>.
286 * This method reads such a block and returns a byte[] of the decoded contents.
287 * Reading stops at the first invalid line, which is discarded (it's a terminator anyway).
288 * <p/>
289 * For example:
290 * <pre><code>
291 * %BeginPhotoshop: 9564
292 * % 3842494D040400000000005D1C015A00031B25471C0200000200041C02780004
293 * % 6E756C6C1C027A00046E756C6C1C025000046E756C6C1C023700083230313630
294 * % 3331311C023C000B3131343335362B303030301C023E00083230313630333131
295 * % 48000000010000003842494D03FD0000000000080101000000000000
296 * %EndPhotoshop
297 * </code></pre>
298 * When calling this method, the reader must be positioned at the start of the first line containing
299 * hex data, not at the introductory line.
300 *
301 * @return The decoded bytes, or <code>null</code> if decoding failed.
302 */
303 @Nullable
304 private static byte[] decodeHexCommentBlock(@NotNull SequentialReader reader) throws IOException
305 {
306 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
307
308 // Use a state machine to efficiently parse data in a single traversal
309
310 final int AwaitingPercent = 0;
311 final int AwaitingSpace = 1;
312 final int AwaitingHex1 = 2;
313 final int AwaitingHex2 = 3;
314
315 int state = AwaitingPercent;
316
317 int carry = 0;
318 boolean done = false;
319
320 byte b = 0;
321 while (!done) {
322 b = reader.getByte();
323
324 switch (state) {
325 case AwaitingPercent: {
326 switch (b) {
327 case '\r':
328 case '\n':
329 case ' ':
330 // skip newline chars and spaces
331 break;
332 case '%':
333 state = AwaitingSpace;
334 break;
335 default:
336 return null;
337 }
338 break;
339 }
340 case AwaitingSpace: {
341 switch (b) {
342 case ' ':
343 state = AwaitingHex1;
344 break;
345 default:
346 done = true;
347 break;
348 }
349 break;
350 }
351 case AwaitingHex1: {
352 int i = tryHexToInt(b);
353 if (i != -1) {
354 carry = i * 16;
355 state = AwaitingHex2;
356 } else if (b == '\r' || b == '\n') {
357 state = AwaitingPercent;
358 } else {
359 return null;
360 }
361 break;
362 }
363 case AwaitingHex2: {
364 int i = tryHexToInt(b);
365 if (i == -1)
366 return null;
367 bytes.write(carry + i);
368 state = AwaitingHex1;
369 break;
370 }
371 }
372 }
373
374 // skip through the remainder of the last line
375 while (b != '\n')
376 b = reader.getByte();
377
378 return bytes.toByteArray();
379 }
380
381 /**
382 * Treats a byte as an ASCII character, and returns it's numerical value in hexadecimal.
383 * If conversion is not possible, returns -1.
384 */
385 private static int tryHexToInt(byte b)
386 {
387 if (b >= '0' && b <= '9')
388 return b - '0';
389 if (b >= 'A' && b <= 'F')
390 return b - 'A' + 10;
391 if (b >= 'a' && b <= 'f')
392 return b - 'a' + 10;
393 return -1;
394 }
395 }