Debian Codegraph @

src/com/drew/metadata/xmp/XmpReader.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.xmp;
22
23 import com.adobe.internal.xmp.XMPException;
24 import com.adobe.internal.xmp.XMPIterator;
25 import com.adobe.internal.xmp.XMPMeta;
26 import com.adobe.internal.xmp.XMPMetaFactory;
27 import com.adobe.internal.xmp.impl.ByteBuffer;
28 import com.adobe.internal.xmp.options.ParseOptions;
29 import com.adobe.internal.xmp.properties.XMPPropertyInfo;
30 import com.drew.imaging.jpeg.JpegSegmentMetadataReader;
31 import com.drew.imaging.jpeg.JpegSegmentType;
32 import com.drew.lang.SequentialByteArrayReader;
33 import com.drew.lang.SequentialReader;
34 import com.drew.metadata.Directory;
35 import com.drew.lang.annotations.NotNull;
36 import com.drew.lang.annotations.Nullable;
37 import com.drew.metadata.Metadata;
38 import com.drew.metadata.StringValue;
39
40 import java.io.IOException;
41 import java.util.Collection;
42 import java.util.Collections;
43
44 /**
45 * Extracts XMP data from JPEG APP1 segments.
46 * <p>
47 * Note that XMP uses a namespace and path format for identifying values, which does not map to metadata-extractor's
48 * integer based tag identifiers. Therefore, XMP data is extracted and exposed via {@link XmpDirectory#getXMPMeta()}
49 * which returns an instance of Adobe's {@link XMPMeta} which exposes the full XMP data set.
50 * <p>
51 * The extraction is done with Adobe's XmpCore-Library (XMP-Toolkit)
52 * Copyright (c) 1999 - 2007, Adobe Systems Incorporated All rights reserved.
53 *
54 * @author Torsten Skadell
55 * @author Drew Noakes https://drewnoakes.com
56 * @author https://github.com/bezineb5
57 */
58 public class XmpReader implements JpegSegmentMetadataReader
59 {
60 @NotNull
61 private static final String XMP_JPEG_PREAMBLE = "http://ns.adobe.com/xap/1.0/\0";
62 @NotNull
63 private static final String XMP_EXTENSION_JPEG_PREAMBLE = "http://ns.adobe.com/xmp/extension/\0";
64 @NotNull
65 private static final String SCHEMA_XMP_NOTES = "http://ns.adobe.com/xmp/note/";
66 @NotNull
67 private static final String ATTRIBUTE_EXTENDED_XMP = "xmpNote:HasExtendedXMP";
68 // Limit photoshop:DocumentAncestors node as it can reach over 100000 items and make parsing extremely slow.
69 // This is not a typical value but it may happen https://forums.adobe.com/thread/2081839
70 @NotNull
71 private static final ParseOptions PARSE_OPTIONS = new ParseOptions().setXMPNodesToLimit(Collections.singletonMap("photoshop:DocumentAncestors", 1000));
72
73 /**
74 * Extended XMP constants
75 */
76 private static final int EXTENDED_XMP_GUID_LENGTH = 32;
77 private static final int EXTENDED_XMP_INT_LENGTH = 4;
78
79 @NotNull
80 public Iterable<JpegSegmentType> getSegmentTypes()
81 {
82 return Collections.singletonList(JpegSegmentType.APP1);
83 }
84
85 /**
86 * Version specifically for dealing with XMP found in JPEG segments. This form of XMP has a peculiar preamble, which
87 * must be removed before parsing the XML.
88 *
89 * @param segments The byte array from which the metadata should be extracted.
90 * @param metadata The {@link Metadata} object into which extracted values should be merged.
91 * @param segmentType The {@link JpegSegmentType} being read.
92 */
93 public void readJpegSegments(@NotNull Iterable<byte[]> segments, @NotNull Metadata metadata, @NotNull JpegSegmentType segmentType)
94 {
95 final int preambleLength = XMP_JPEG_PREAMBLE.length();
96 final int extensionPreambleLength = XMP_EXTENSION_JPEG_PREAMBLE.length();
97 String extendedXMPGUID = null;
98 byte[] extendedXMPBuffer = null;
99
100 for (byte[] segmentBytes : segments) {
101 // XMP in a JPEG file has an identifying preamble which is not valid XML
102 if (segmentBytes.length >= preambleLength) {
103 // NOTE we expect the full preamble here, but some images (such as that reported on GitHub #102)
104 // start with "XMP\0://ns.adobe.com/xap/1.0/" which appears to be an error but is easily recovered
105 // from. In such cases, the actual XMP data begins at the same offset.
106 if (XMP_JPEG_PREAMBLE.equalsIgnoreCase(new String(segmentBytes, 0, preambleLength)) ||
107 "XMP".equalsIgnoreCase(new String(segmentBytes, 0, 3))) {
108
109 byte[] xmlBytes = new byte[segmentBytes.length - preambleLength];
110 System.arraycopy(segmentBytes, preambleLength, xmlBytes, 0, xmlBytes.length);
111 extract(xmlBytes, metadata);
112 // Check in the Standard XMP if there should be a Extended XMP part in other chunks.
113 extendedXMPGUID = getExtendedXMPGUID(metadata);
114 continue;
115 }
116 }
117
118 // If we know that there's Extended XMP chunks, look for them.
119 if (extendedXMPGUID != null &&
120 segmentBytes.length >= extensionPreambleLength &&
121 XMP_EXTENSION_JPEG_PREAMBLE.equalsIgnoreCase(new String(segmentBytes, 0, extensionPreambleLength))) {
122
123 extendedXMPBuffer = processExtendedXMPChunk(metadata, segmentBytes, extendedXMPGUID, extendedXMPBuffer);
124 }
125 }
126
127 // Now that the Extended XMP chunks have been concatenated, let's parse and merge with the Standard XMP.
128 if (extendedXMPBuffer != null) {
129 extract(extendedXMPBuffer, metadata);
130 }
131 }
132
133 /**
134 * Performs the XMP data extraction, adding found values to the specified instance of {@link Metadata}.
135 * <p>
136 * The extraction is done with Adobe's XMPCore library.
137 */
138 public void extract(@NotNull final byte[] xmpBytes, @NotNull Metadata metadata)
139 {
140 extract(xmpBytes, metadata, null);
141 }
142
143 /**
144 * Performs the XMP data extraction, adding found values to the specified instance of {@link Metadata}.
145 * <p>
146 * The extraction is done with Adobe's XMPCore library.
147 */
148 public void extract(@NotNull final byte[] xmpBytes, @NotNull Metadata metadata, @Nullable Directory parentDirectory)
149 {
150 extract(xmpBytes, 0, xmpBytes.length, metadata, parentDirectory);
151 }
152
153 /**
154 * Performs the XMP data extraction, adding found values to the specified instance of {@link Metadata}.
155 * <p>
156 * The extraction is done with Adobe's XMPCore library.
157 */
158 public void extract(@NotNull final byte[] xmpBytes, int offset, int length, @NotNull Metadata metadata, @Nullable Directory parentDirectory)
159 {
160 XmpDirectory directory = new XmpDirectory();
161
162 if (parentDirectory != null)
163 directory.setParent(parentDirectory);
164
165 try {
166 XMPMeta xmpMeta;
167
168 // If all xmpBytes are requested, no need to make a new ByteBuffer
169 if (offset == 0 && length == xmpBytes.length) {
170 xmpMeta = XMPMetaFactory.parseFromBuffer(xmpBytes, PARSE_OPTIONS);
171 } else {
172 ByteBuffer buffer = new ByteBuffer(xmpBytes, offset, length);
173 xmpMeta = XMPMetaFactory.parse(buffer.getByteStream(), PARSE_OPTIONS);
174 }
175
176 directory.setXMPMeta(xmpMeta);
177 } catch (XMPException e) {
178 directory.addError("Error processing XMP data: " + e.getMessage());
179 }
180
181 if (!directory.isEmpty())
182 metadata.addDirectory(directory);
183 }
184
185 /**
186 * Performs the XMP data extraction, adding found values to the specified instance of {@link Metadata}.
187 * <p>
188 * The extraction is done with Adobe's XMPCore library.
189 */
190 public void extract(@NotNull final String xmpString, @NotNull Metadata metadata)
191 {
192 extract(xmpString, metadata, null);
193 }
194
195 /**
196 * Performs the XMP data extraction, adding found values to the specified instance of {@link Metadata}.
197 * <p>
198 * The extraction is done with Adobe's XMPCore library.
199 */
200 public void extract(@NotNull final StringValue xmpString, @NotNull Metadata metadata)
201 {
202 extract(xmpString.getBytes(), metadata, null);
203 }
204
205 /**
206 * Performs the XMP data extraction, adding found values to the specified instance of {@link Metadata}.
207 * <p>
208 * The extraction is done with Adobe's XMPCore library.
209 */
210 public void extract(@NotNull final String xmpString, @NotNull Metadata metadata, @Nullable Directory parentDirectory)
211 {
212 XmpDirectory directory = new XmpDirectory();
213
214 if (parentDirectory != null)
215 directory.setParent(parentDirectory);
216
217 try {
218 XMPMeta xmpMeta = XMPMetaFactory.parseFromString(xmpString, PARSE_OPTIONS);
219 directory.setXMPMeta(xmpMeta);
220 } catch (XMPException e) {
221 directory.addError("Error processing XMP data: " + e.getMessage());
222 }
223
224 if (!directory.isEmpty())
225 metadata.addDirectory(directory);
226 }
227
228 /**
229 * Determine if there is an extended XMP section based on the standard XMP part.
230 * The xmpNote:HasExtendedXMP attribute contains the GUID of the Extended XMP chunks.
231 */
232 @Nullable
233 private static String getExtendedXMPGUID(@NotNull Metadata metadata)
234 {
235 final Collection<XmpDirectory> xmpDirectories = metadata.getDirectoriesOfType(XmpDirectory.class);
236
237 for (XmpDirectory directory : xmpDirectories) {
238 final XMPMeta xmpMeta = directory.getXMPMeta();
239
240 try {
241 final XMPIterator itr = xmpMeta.iterator(SCHEMA_XMP_NOTES, null, null);
242 if (itr == null)
243 continue;
244
245 while (itr.hasNext()) {
246 final XMPPropertyInfo pi = (XMPPropertyInfo) itr.next();
247 if (ATTRIBUTE_EXTENDED_XMP.equals(pi.getPath())) {
248 return pi.getValue();
249 }
250 }
251 } catch (XMPException e) {
252 // Fail silently here: we had a reading issue, not a decoding issue.
253 }
254 }
255
256 return null;
257 }
258
259 /**
260 * Process an Extended XMP chunk. It will read the bytes from segmentBytes and validates that the GUID the requested one.
261 * It will progressively fill the buffer with each chunk.
262 * The format is specified in this document:
263 * http://www.adobe.com/content/dam/Adobe/en/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
264 * at page 19
265 */
266 @Nullable
267 private static byte[] processExtendedXMPChunk(@NotNull Metadata metadata, @NotNull byte[] segmentBytes, @NotNull String extendedXMPGUID, @Nullable byte[] extendedXMPBuffer)
268 {
269 final int extensionPreambleLength = XMP_EXTENSION_JPEG_PREAMBLE.length();
270 final int segmentLength = segmentBytes.length;
271 final int totalOffset = extensionPreambleLength + EXTENDED_XMP_GUID_LENGTH + EXTENDED_XMP_INT_LENGTH + EXTENDED_XMP_INT_LENGTH;
272
273 if (segmentLength >= totalOffset) {
274 try {
275 /*
276 * The chunk contains:
277 * - A null-terminated signature string of "http://ns.adobe.com/xmp/extension/".
278 * - A 128-bit GUID stored as a 32-byte ASCII hex string, capital A-F, no null termination.
279 * The GUID is a 128-bit MD5 digest of the full ExtendedXMP serialization.
280 * - The full length of the ExtendedXMP serialization as a 32-bit unsigned integer
281 * - The offset of this portion as a 32-bit unsigned integer
282 * - The portion of the ExtendedXMP
283 */
284 final SequentialReader reader = new SequentialByteArrayReader(segmentBytes);
285 reader.skip(extensionPreambleLength);
286 final String segmentGUID = reader.getString(EXTENDED_XMP_GUID_LENGTH);
287
288 if (extendedXMPGUID.equals(segmentGUID)) {
289 final int fullLength = (int)reader.getUInt32();
290 final int chunkOffset = (int)reader.getUInt32();
291
292 if (extendedXMPBuffer == null)
293 extendedXMPBuffer = new byte[fullLength];
294
295 if (extendedXMPBuffer.length == fullLength) {
296 System.arraycopy(segmentBytes, totalOffset, extendedXMPBuffer, chunkOffset, segmentLength - totalOffset);
297 } else {
298 XmpDirectory directory = new XmpDirectory();
299 directory.addError(String.format("Inconsistent length for the Extended XMP buffer: %d instead of %d", fullLength, extendedXMPBuffer.length));
300 metadata.addDirectory(directory);
301 }
302 }
303 } catch (IOException ex) {
304 XmpDirectory directory = new XmpDirectory();
305 directory.addError(ex.getMessage());
306 metadata.addDirectory(directory);
307 }
308 }
309
310 return extendedXMPBuffer;
311 }
312 }