exifreader 4.39.1 → 4.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,308 @@
1
+ /**
2
+ * ExifReader
3
+ * http://github.com/mattiasw/exifreader
4
+ * Copyright (C) 2011-2026 Mattias Wallander <mattias@wallander.eu>
5
+ * This Source Code Form is subject to the terms of the Mozilla Public
6
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
7
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
+ */
9
+ /* global Buffer, __non_webpack_require__ */
10
+
11
+ import {dataUriToBuffer} from './utils.js';
12
+
13
+ export const HTTP_STATUS_OK = 200;
14
+ export const HTTP_STATUS_SUCCESS_MAX = 299;
15
+ export const HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416;
16
+
17
+ export function isFilePathOrURL(data) {
18
+ return typeof data === 'string';
19
+ }
20
+
21
+ export function isBrowserFileObject(data) {
22
+ return (typeof File !== 'undefined') && (data instanceof File);
23
+ }
24
+
25
+ export function isDataUri(filename) {
26
+ return /^data:[^;,]*(;base64)?,/.test(filename);
27
+ }
28
+
29
+ /**
30
+ * Routes URL / data-URI / file path to the right range-aware primitive and
31
+ * resolves with a plain buffer. Used by the numeric-`length` code path
32
+ * in `load()`.
33
+ *
34
+ * @param {string} filename URL, data URI, or local file path.
35
+ * @param {{length?: number}} [options]
36
+ * @returns {Promise<ArrayBuffer|Buffer>} The whole file, or its first `length` bytes if specified.
37
+ */
38
+ export function loadFile(filename, options) {
39
+ if (/^\w+:\/\//.test(filename)) {
40
+ if (typeof fetch !== 'undefined') {
41
+ return fetchRange(filename, legacyRange(options)).then((r) => r.buffer);
42
+ }
43
+
44
+ return nodeGetRange(filename, legacyRange(options)).then((r) => r.buffer);
45
+ }
46
+
47
+ if (isDataUri(filename)) {
48
+ return Promise.resolve(dataUriToBuffer(filename));
49
+ }
50
+
51
+ return readLocalFileRange(filename, legacyRange(options)).then((r) => r.buffer);
52
+ }
53
+
54
+ /**
55
+ * Browser `File` equivalent of `loadFile`. Used by the numeric-`length`
56
+ * code path in `load()`.
57
+ *
58
+ * @param {File} file
59
+ * @param {{length?: number}} [options]
60
+ * @returns {Promise<ArrayBuffer>}
61
+ */
62
+ export function loadFileObject(file, options) {
63
+ return readFileObjectRange(file, legacyRange(options)).then((r) => r.buffer);
64
+ }
65
+
66
+ function legacyRange(options) {
67
+ if (options && Number.isInteger(options.length) && options.length >= 0) {
68
+ return {start: 0, end: options.length};
69
+ }
70
+ return {start: 0};
71
+ }
72
+
73
+ /**
74
+ * Range-aware browser `fetch`. Sets an HTTP `Range` header when the
75
+ * requested range is not the whole file.
76
+ *
77
+ * @param {string} url
78
+ * @param {{start?: number, end?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`) to read to EOF.
79
+ * @returns {Promise<{buffer: ArrayBuffer, totalSize: number|undefined, status: number|undefined}>}
80
+ * `totalSize` is taken from the `Content-Range` or `Content-Length` response header when present.
81
+ */
82
+ export function fetchRange(url, {start = 0, end} = {}) {
83
+ const options = {method: 'GET'};
84
+ if (start > 0 || (end !== undefined && end !== Infinity)) {
85
+ options.headers = {range: buildRangeHeader(start, end)};
86
+ }
87
+ return fetch(url, options).then((response) => {
88
+ const totalSize = totalSizeFromFetchResponse(response);
89
+ const status = response && typeof response.status === 'number' ? response.status : undefined;
90
+ return Promise.resolve(response.arrayBuffer()).then((buffer) => ({buffer, totalSize, status}));
91
+ });
92
+ }
93
+
94
+ function buildRangeHeader(start, end) {
95
+ if (end === undefined || end === Infinity) {
96
+ return `bytes=${start}-`;
97
+ }
98
+ return `bytes=${start}-${end - 1}`;
99
+ }
100
+
101
+ function totalSizeFromFetchResponse(response) {
102
+ if (!response || !response.headers || typeof response.headers.get !== 'function') {
103
+ return undefined;
104
+ }
105
+ const contentRange = response.headers.get('Content-Range');
106
+ if (contentRange) {
107
+ const match = /\/(\d+|\*)$/.exec(contentRange);
108
+ if (match && match[1] !== '*') {
109
+ return parseInt(match[1], 10);
110
+ }
111
+ }
112
+ const contentLength = response.headers.get('Content-Length');
113
+ if (contentLength) {
114
+ const n = parseInt(contentLength, 10);
115
+ if (Number.isFinite(n)) {
116
+ return n;
117
+ }
118
+ }
119
+ return undefined;
120
+ }
121
+
122
+ /**
123
+ * Range-aware Node `http(s).get`. Same contract as `fetchRange`. Rejects
124
+ * on non-2xx responses with the status line in the error message.
125
+ *
126
+ * @param {string} url
127
+ * @param {{start?: number, end?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`) to read to EOF.
128
+ * @returns {Promise<{buffer: Buffer, totalSize: number|undefined, status: number|undefined}>}
129
+ */
130
+ export function nodeGetRange(url, {start = 0, end} = {}) {
131
+ return new Promise((resolve, reject) => {
132
+ const options = {};
133
+ if (start > 0 || (end !== undefined && end !== Infinity)) {
134
+ options.headers = {range: buildRangeHeader(start, end)};
135
+ }
136
+
137
+ const get = requireNodeGet(url);
138
+ get(url, options, (response) => {
139
+ if ((response.statusCode >= HTTP_STATUS_OK) && (response.statusCode <= HTTP_STATUS_SUCCESS_MAX)) {
140
+ const totalSize = totalSizeFromNodeResponse(response);
141
+ const data = [];
142
+ response.on('data', (chunk) => data.push(Buffer.from(chunk)));
143
+ response.on('error', (error) => reject(error));
144
+ response.on('end', () => resolve({
145
+ buffer: Buffer.concat(data),
146
+ totalSize,
147
+ status: response.statusCode,
148
+ }));
149
+ } else {
150
+ reject(`Could not fetch file: ${response.statusCode} ${response.statusMessage}`);
151
+ response.resume();
152
+ }
153
+ }).on('error', (error) => reject(error));
154
+ });
155
+ }
156
+
157
+ function totalSizeFromNodeResponse(response) {
158
+ if (!response || !response.headers) {
159
+ return undefined;
160
+ }
161
+ const contentRange = response.headers['content-range'];
162
+ if (contentRange) {
163
+ const match = /\/(\d+|\*)$/.exec(contentRange);
164
+ if (match && match[1] !== '*') {
165
+ return parseInt(match[1], 10);
166
+ }
167
+ }
168
+ const contentLength = response.headers['content-length'];
169
+ if (contentLength) {
170
+ const n = parseInt(contentLength, 10);
171
+ if (Number.isFinite(n)) {
172
+ return n;
173
+ }
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ function requireNodeGet(url) {
179
+ if (/^https:\/\//.test(url)) {
180
+ return __non_webpack_require__('https').get;
181
+ }
182
+ return __non_webpack_require__('http').get;
183
+ }
184
+
185
+ /**
186
+ * Range-aware local file reader (Node `fs`). Opens, reads `[start, end)`,
187
+ * closes.
188
+ *
189
+ * @param {string} filename
190
+ * @param {{start?: number, end?: number, totalSize?: number}} [options]
191
+ * Pass `totalSize` (a previously-`stat`-ed size) to skip the
192
+ * `fs.stat` call on subsequent reads of the same file.
193
+ * @returns {Promise<{buffer: Buffer, totalSize: number}>}
194
+ */
195
+ export function readLocalFileRange(filename, {start = 0, end, totalSize} = {}) {
196
+ return new Promise((resolve, reject) => {
197
+ const fs = requireNodeFs();
198
+ fs.open(filename, (openErr, fd) => {
199
+ if (openErr) {
200
+ return reject(openErr);
201
+ }
202
+ resolveTotalSize(fs, filename, totalSize, (statErr, total) => {
203
+ if (statErr) {
204
+ return fs.close(fd, () => reject(statErr));
205
+ }
206
+ const effectiveEnd = (end === undefined || end === Infinity || end > total) ? total : end;
207
+ const effectiveStart = Math.min(Math.max(0, start), effectiveEnd);
208
+ const size = effectiveEnd - effectiveStart;
209
+ const buffer = Buffer.alloc(size);
210
+ if (size === 0) {
211
+ return fs.close(fd, (closeErr) => finishLocalRead(filename, closeErr, buffer, total, resolve));
212
+ }
213
+ fs.read(fd, {buffer, length: size, position: effectiveStart}, (readErr) => {
214
+ if (readErr) {
215
+ return fs.close(fd, () => reject(readErr));
216
+ }
217
+ fs.close(fd, (closeErr) => finishLocalRead(filename, closeErr, buffer, total, resolve));
218
+ });
219
+ });
220
+ });
221
+ });
222
+ }
223
+
224
+ function resolveTotalSize(fs, filename, totalSize, cb) {
225
+ if (totalSize !== undefined) {
226
+ return cb(null, totalSize);
227
+ }
228
+ fs.stat(filename, (err, stat) => cb(err, err ? undefined : stat.size));
229
+ }
230
+
231
+ function finishLocalRead(filename, closeErr, buffer, total, resolve) {
232
+ if (closeErr) {
233
+ console.warn(`Could not close file ${filename}:`, closeErr); // eslint-disable-line no-console
234
+ }
235
+ resolve({buffer, totalSize: total});
236
+ }
237
+
238
+ function requireNodeFs() {
239
+ try {
240
+ return __non_webpack_require__('fs');
241
+ } catch (error) {
242
+ return undefined;
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Range-aware browser `File` reader. Uses `file.slice(start, end)` plus
248
+ * `FileReader.readAsArrayBuffer`.
249
+ *
250
+ * @param {File} file
251
+ * @param {{start?: number, end?: number}} [range]
252
+ * @returns {Promise<{buffer: ArrayBuffer, totalSize: number|undefined}>}
253
+ */
254
+ export function readFileObjectRange(file, {start = 0, end} = {}) {
255
+ return new Promise((resolve, reject) => {
256
+ const reader = new FileReader();
257
+ const totalSize = typeof file.size === 'number' ? file.size : undefined;
258
+ reader.onload = (readerEvent) => resolve({buffer: readerEvent.target.result, totalSize});
259
+ reader.onerror = () => reject(reader.error);
260
+ const hasSlice = file && typeof file.slice === 'function';
261
+ if (hasSlice && (start > 0 || (end !== undefined && end !== Infinity))) {
262
+ const sliceEnd = (end === undefined || end === Infinity) ? totalSize : end;
263
+ reader.readAsArrayBuffer(file.slice(start, sliceEnd));
264
+ } else {
265
+ reader.readAsArrayBuffer(file);
266
+ }
267
+ });
268
+ }
269
+
270
+ /**
271
+ * Concatenate two buffers. Returns a Node `Buffer` when both arguments
272
+ * are Buffers, otherwise an `ArrayBuffer`. Either argument may be
273
+ * nullish, in which case the other is returned as-is.
274
+ *
275
+ * @param {ArrayBuffer|Buffer|null|undefined} a
276
+ * @param {ArrayBuffer|Buffer|null|undefined} b
277
+ * @returns {ArrayBuffer|Buffer}
278
+ */
279
+ export function concatBuffers(a, b) {
280
+ if (!a) {
281
+ return b;
282
+ }
283
+ if (!b) {
284
+ return a;
285
+ }
286
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(a) && Buffer.isBuffer(b)) {
287
+ return Buffer.concat([a, b]);
288
+ }
289
+ const aBytes = bufferToBytes(a);
290
+ const bBytes = bufferToBytes(b);
291
+ const out = new Uint8Array(aBytes.byteLength + bBytes.byteLength);
292
+ out.set(aBytes, 0);
293
+ out.set(bBytes, aBytes.byteLength);
294
+ return out.buffer;
295
+ }
296
+
297
+ function bufferToBytes(b) {
298
+ if (b instanceof ArrayBuffer) {
299
+ return new Uint8Array(b);
300
+ }
301
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(b)) {
302
+ return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
303
+ }
304
+ if (ArrayBuffer.isView(b)) {
305
+ return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
306
+ }
307
+ return new Uint8Array(b);
308
+ }
@@ -34,9 +34,12 @@ function isAvifFile(dataView) {
34
34
  /**
35
35
  * Finds the offsets of an AVIF file in the provided data view.
36
36
  *
37
- * @param {DataView} dataView - The data view to find offsets in.
38
- * @returns {Object} An object containing the offsets of the TIFF header, XMP chunks, ICC chunks, and a boolean indicating if any of these exist.
37
+ * @param {DataView} dataView The data view to find offsets in.
38
+ * @param {Array<Object>=} metadataBlocks Optional out-array. Forwarded to
39
+ * the shared ISO-BMFF findOffsets.
40
+ * @returns {Object} TIFF header offset, XMP chunks, ICC chunks, and whether
41
+ * any were found.
39
42
  */
40
- function findAvifOffsets(dataView) {
41
- return findOffsets(dataView);
43
+ function findAvifOffsets(dataView, metadataBlocks) {
44
+ return findOffsets(dataView, metadataBlocks);
42
45
  }
@@ -12,11 +12,31 @@ export default {
12
12
  const GIF_SIGNATURE_SIZE = 6;
13
13
  const GIF_SIGNATURES = ['GIF87a', 'GIF89a'];
14
14
 
15
+ // 6-byte signature plus 7-byte logical screen descriptor.
16
+ const GIF_HEADER_SIZE = 13;
17
+
18
+ /**
19
+ * Checks if the provided data view represents a GIF file.
20
+ *
21
+ * @param {DataView} dataView The data view to check.
22
+ * @returns {boolean} True if the data view starts with a GIF signature.
23
+ */
15
24
  function isGifFile(dataView) {
16
25
  return !!dataView && GIF_SIGNATURES.includes(getStringFromDataView(dataView, 0, GIF_SIGNATURE_SIZE));
17
26
  }
18
27
 
19
- function findOffsets() {
28
+ /**
29
+ * Finds the GIF logical screen descriptor offset.
30
+ *
31
+ * @param {DataView} _dataView The data view (unused).
32
+ * @param {Array<Object>=} metadataBlocks Optional out-array. When provided,
33
+ * receives one `gif` block covering the GIF header bytes.
34
+ * @returns {{gifHeaderOffset: number}}
35
+ */
36
+ function findOffsets(_dataView, metadataBlocks) {
37
+ if (metadataBlocks) {
38
+ metadataBlocks.push({type: 'gif', start: 0, end: GIF_HEADER_SIZE});
39
+ }
20
40
  return {
21
41
  gifHeaderOffset: 0
22
42
  };
@@ -33,9 +33,12 @@ function isHeicFile(dataView) {
33
33
  /**
34
34
  * Finds the offsets of a HEIC file in the provided data view.
35
35
  *
36
- * @param {DataView} dataView - The data view to find offsets in.
37
- * @returns {Object} An object containing the offsets of the TIFF header, XMP chunks, ICC chunks, and a boolean indicating if any of these exist.
36
+ * @param {DataView} dataView The data view to find offsets in.
37
+ * @param {Array<Object>=} metadataBlocks Optional out-array. Forwarded to
38
+ * the shared ISO-BMFF findOffsets.
39
+ * @returns {Object} TIFF header offset, XMP chunks, ICC chunks, and whether
40
+ * any were found.
38
41
  */
39
- function findHeicOffsets(dataView) {
40
- return findOffsets(dataView);
42
+ function findHeicOffsets(dataView, metadataBlocks) {
43
+ return findOffsets(dataView, metadataBlocks);
41
44
  }
@@ -22,6 +22,7 @@ const TYPE_FTYP = 0x66747970;
22
22
  const TYPE_IPRP = 0x69707270;
23
23
  const TYPE_META = 0x6d657461;
24
24
  const TYPE_ILOC = 0x696c6f63;
25
+ const TYPE_IDAT = 0x69646174;
25
26
  const TYPE_IINF = 0x69696e66;
26
27
  const TYPE_INFE = 0x696e6665;
27
28
  const TYPE_IPCO = 0x6970636f;
@@ -74,6 +75,9 @@ export function parseBox(dataView, offset) {
74
75
  if (type === TYPE_ILOC) {
75
76
  return parseItemLocationBox(dataView, version, contentOffset + VERSION_SIZE, length);
76
77
  }
78
+ if (type === TYPE_IDAT) {
79
+ return parseItemDataBox(contentOffset + VERSION_SIZE, length);
80
+ }
77
81
  if (type === TYPE_IINF) {
78
82
  return parseItemInformationBox(dataView, offset, version, contentOffset + VERSION_SIZE, length);
79
83
  }
@@ -148,15 +152,25 @@ function hasEmptyHighBits(dataView, offset) {
148
152
  * @property {Array<Object>} xmpChunks
149
153
  * @property {Array<Object>} iccChunks
150
154
  * @property {boolean} hasAppMarkers
155
+ * @property {DataView=} exifDataView Synthetic buffer when an Exif item
156
+ * spans multiple extents. tiffHeaderOffset then indexes into this view
157
+ * rather than the source dataView.
158
+ * @property {DataView=} xmpDataView Synthetic buffer when an XMP item
159
+ * spans multiple extents. xmpChunks then references this view.
151
160
  */
152
161
 
153
162
  /**
154
- * Finds the offsets of ISO-BMFF-structued data in the provided data view.
163
+ * Finds the offsets of ISO-BMFF-structured data in the provided data view.
155
164
  *
156
- * @param {DataView} dataView - The data view to find offsets in.
157
- * @returns {Offsets} An object containing the offsets of the TIFF header, XMP chunks, ICC chunks, and a boolean indicating if any of these exist.
165
+ * @param {DataView} dataView The data view to find offsets in.
166
+ * @param {Array<Object>=} metadataBlocks Optional out-array. When provided,
167
+ * receives one block per iloc extent (Exif/XMP) at the resolved file
168
+ * offset (cm 0 direct, cm 1 via the idat box) plus the ICC profile
169
+ * bytes. cm 2 (item_offset) items are skipped.
170
+ * @returns {Offsets} The TIFF header offset, XMP chunks, ICC chunks, and
171
+ * whether any were found.
158
172
  */
159
- export function findOffsets(dataView) {
173
+ export function findOffsets(dataView, metadataBlocks) {
160
174
  if (Constants.USE_EXIF || Constants.USE_XMP || Constants.USE_ICC) {
161
175
  const offsets = {};
162
176
  const metaBox = findMetaBox(dataView);
@@ -166,13 +180,25 @@ export function findOffsets(dataView) {
166
180
  }
167
181
 
168
182
  if (Constants.USE_EXIF) {
169
- offsets.tiffHeaderOffset = findExifOffset(dataView, metaBox);
183
+ const exif = findExifOffset(dataView, metaBox, metadataBlocks);
184
+ if (exif !== undefined) {
185
+ offsets.tiffHeaderOffset = exif.tiffHeaderOffset;
186
+ if (exif.dataView !== undefined) {
187
+ offsets.exifDataView = exif.dataView;
188
+ }
189
+ }
170
190
  }
171
191
  if (Constants.USE_XMP) {
172
- offsets.xmpChunks = findXmpChunks(metaBox);
192
+ const xmp = findXmpChunks(dataView, metaBox, metadataBlocks);
193
+ if (xmp !== undefined) {
194
+ offsets.xmpChunks = xmp.chunks;
195
+ if (xmp.dataView !== undefined) {
196
+ offsets.xmpDataView = xmp.dataView;
197
+ }
198
+ }
173
199
  }
174
200
  if (Constants.USE_ICC) {
175
- offsets.iccChunks = findIccChunks(metaBox);
201
+ offsets.iccChunks = findIccChunks(metaBox, metadataBlocks);
176
202
  }
177
203
  offsets.hasAppMarkers = (offsets.tiffHeaderOffset !== undefined) || (offsets.xmpChunks !== undefined) || (offsets.iccChunks !== undefined);
178
204
  return offsets;
@@ -204,17 +230,106 @@ function findMetaBox(dataView) {
204
230
  return undefined;
205
231
  }
206
232
 
207
- function findExifOffset(dataView, metaBox) {
233
+ function findExifOffset(dataView, metaBox, metadataBlocks) {
208
234
  try {
209
235
  const exifItemId = findIinfExifItemId(metaBox).itemId;
210
236
  const ilocItem = findIlocItem(metaBox, exifItemId);
211
- const exifOffset = ilocItem.baseOffset + ilocItem.extents[0].extentOffset;
212
- return getTiffHeaderOffset(dataView, exifOffset);
237
+ warnIfUnsupportedConstructionMethod(ilocItem);
238
+ const idatContentOffset = findIdatContentOffset(metaBox);
239
+ pushIlocExtentBlocks(metadataBlocks, ilocItem, 'exif', idatContentOffset);
240
+ if (ilocItem.extents.length > 1) {
241
+ const assembled = assembleExtents(dataView, ilocItem, idatContentOffset);
242
+ if (assembled === undefined) {
243
+ return undefined;
244
+ }
245
+ return {
246
+ tiffHeaderOffset: getTiffHeaderOffset(assembled, 0),
247
+ dataView: assembled,
248
+ };
249
+ }
250
+ const exifOffset = resolveExtentToFileOffset(ilocItem, ilocItem.extents[0], idatContentOffset);
251
+ if (exifOffset === undefined) {
252
+ return undefined;
253
+ }
254
+ return {tiffHeaderOffset: getTiffHeaderOffset(dataView, exifOffset)};
213
255
  } catch (error) {
214
256
  return undefined;
215
257
  }
216
258
  }
217
259
 
260
+ function pushIlocExtentBlocks(metadataBlocks, ilocItem, blockType, idatContentOffset) {
261
+ if (!metadataBlocks) {
262
+ return;
263
+ }
264
+ for (let i = 0; i < ilocItem.extents.length; i++) {
265
+ const extent = ilocItem.extents[i];
266
+ const start = resolveExtentToFileOffset(ilocItem, extent, idatContentOffset);
267
+ if (start === undefined) {
268
+ continue;
269
+ }
270
+ metadataBlocks.push({
271
+ type: blockType,
272
+ start,
273
+ end: start + extent.extentLength,
274
+ });
275
+ }
276
+ }
277
+
278
+ // Translates an iloc extent to a real file offset.
279
+ // cm 0 / undefined: baseOffset + extentOffset is already a file offset.
280
+ // cm 1 (idat): bytes live inside the meta box's idat sub-box.
281
+ // cm 2 (item): not yet supported; returns undefined so the item is skipped.
282
+ function resolveExtentToFileOffset(ilocItem, extent, idatContentOffset) {
283
+ const cm = ilocItem.constructionMethod;
284
+ if (cm === undefined || cm === 0) {
285
+ return ilocItem.baseOffset + extent.extentOffset;
286
+ }
287
+ if (cm === 1 && idatContentOffset !== undefined) {
288
+ return idatContentOffset + ilocItem.baseOffset + extent.extentOffset;
289
+ }
290
+ return undefined;
291
+ }
292
+
293
+ function findIdatContentOffset(metaBox) {
294
+ const idatBox = metaBox.subBoxes.find((box) => box.type === 'idat');
295
+ return idatBox ? idatBox.contentOffset : undefined;
296
+ }
297
+
298
+ function warnIfUnsupportedConstructionMethod(ilocItem) {
299
+ if (ilocItem.constructionMethod === 2) {
300
+ // eslint-disable-next-line no-console
301
+ console.warn('This file uses iloc constructionMethod 2 (item_offset) which is currently not supported by ExifReader. Contact the maintainer to get it fixed.');
302
+ }
303
+ }
304
+
305
+ // Copies the bytes of every iloc extent into a single contiguous buffer.
306
+ // Used when an item spans more than one extent, the parsers downstream
307
+ // require contiguous bytes. Returns undefined if any extent fails to
308
+ // resolve or falls outside the source dataView.
309
+ function assembleExtents(dataView, ilocItem, idatContentOffset) {
310
+ const resolved = [];
311
+ let totalLength = 0;
312
+ for (let i = 0; i < ilocItem.extents.length; i++) {
313
+ const extent = ilocItem.extents[i];
314
+ const start = resolveExtentToFileOffset(ilocItem, extent, idatContentOffset);
315
+ if (start === undefined || start + extent.extentLength > dataView.byteLength) {
316
+ return undefined;
317
+ }
318
+ resolved.push({start, length: extent.extentLength});
319
+ totalLength += extent.extentLength;
320
+ }
321
+ const buffer = new Uint8Array(totalLength);
322
+ let writeOffset = 0;
323
+ for (let i = 0; i < resolved.length; i++) {
324
+ const {start, length} = resolved[i];
325
+ for (let j = 0; j < length; j++) {
326
+ buffer[writeOffset + j] = dataView.getUint8(start + j);
327
+ }
328
+ writeOffset += length;
329
+ }
330
+ return new DataView(buffer.buffer);
331
+ }
332
+
218
333
  function findIinfExifItemId(metaBox) {
219
334
  return metaBox.subBoxes.find((box) => box.type === 'iinf').itemInfos.find((itemInfo) => itemInfo.itemType === ITEM_INFO_TYPE_EXIF);
220
335
  }
@@ -230,17 +345,36 @@ export function getTiffHeaderOffset(dataView, exifOffset) {
230
345
  return exifOffset + TIFF_HEADER_OFFSET_SIZE + dataView.getUint32(exifOffset);
231
346
  }
232
347
 
233
- function findXmpChunks(metaBox) {
348
+ function findXmpChunks(dataView, metaBox, metadataBlocks) {
234
349
  try {
235
350
  const xmpItemId = findIinfXmpItemId(metaBox).itemId;
236
351
  const ilocItem = findIlocItem(metaBox, xmpItemId);
237
- const ilocItemExtent = findIlocItem(metaBox, xmpItemId).extents[0];
238
- return [
239
- {
240
- dataOffset: ilocItem.baseOffset + ilocItemExtent.extentOffset,
241
- length: ilocItemExtent.extentLength,
352
+ warnIfUnsupportedConstructionMethod(ilocItem);
353
+ const idatContentOffset = findIdatContentOffset(metaBox);
354
+ pushIlocExtentBlocks(metadataBlocks, ilocItem, 'xmp', idatContentOffset);
355
+ if (ilocItem.extents.length > 1) {
356
+ const assembled = assembleExtents(dataView, ilocItem, idatContentOffset);
357
+ if (assembled === undefined) {
358
+ return undefined;
242
359
  }
243
- ];
360
+ return {
361
+ chunks: [{dataOffset: 0, length: assembled.byteLength}],
362
+ dataView: assembled,
363
+ };
364
+ }
365
+ const ilocItemExtent = ilocItem.extents[0];
366
+ const dataOffset = resolveExtentToFileOffset(ilocItem, ilocItemExtent, idatContentOffset);
367
+ if (dataOffset === undefined) {
368
+ return undefined;
369
+ }
370
+ return {
371
+ chunks: [
372
+ {
373
+ dataOffset,
374
+ length: ilocItemExtent.extentLength,
375
+ }
376
+ ],
377
+ };
244
378
  } catch (error) {
245
379
  return undefined;
246
380
  }
@@ -251,7 +385,7 @@ function findIinfXmpItemId(metaBox) {
251
385
  .itemInfos.find((itemInfo) => itemInfo.itemType === ITEM_INFO_TYPE_MIME && itemInfo.contentType === 'application/rdf+xml');
252
386
  }
253
387
 
254
- function findIccChunks(metaBox) {
388
+ function findIccChunks(metaBox, metadataBlocks) {
255
389
  // This finds the first ICC chunk, but there could be one for each image
256
390
  // that is embedded in the file. If it turns out we need to match the ICC
257
391
  // chunk to a specific image, we need to check the "ipma" in addition to the
@@ -263,6 +397,13 @@ function findIccChunks(metaBox) {
263
397
  .properties.find((box) => box.type === 'colr')
264
398
  .icc;
265
399
  if (icc) {
400
+ if (metadataBlocks) {
401
+ metadataBlocks.push({
402
+ type: 'icc',
403
+ start: icc.offset,
404
+ end: icc.offset + icc.length,
405
+ });
406
+ }
266
407
  return [icc];
267
408
  }
268
409
  } catch (error) {
@@ -335,6 +476,16 @@ function parseMetadataBox(dataView, startOffset, contentOffset, length) {
335
476
  };
336
477
  }
337
478
 
479
+ function parseItemDataBox(contentOffset, length) {
480
+ const FLAGS_SIZE = 3;
481
+
482
+ return {
483
+ type: 'idat',
484
+ contentOffset: contentOffset + FLAGS_SIZE,
485
+ length,
486
+ };
487
+ }
488
+
338
489
  /**
339
490
  * @param {DataView} dataView
340
491
  * @param {number} offset The offset to start parsing from.